myc-core 8.3.0+beta

Provide base features of the Mycelium project as s and Use-cases.
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
mod licensed_resources;
mod owner;
mod tenant_ownerships;

use std::collections::HashMap;

pub use licensed_resources::{LicensedResource, LicensedResources};
pub use owner::Owner;
pub use tenant_ownerships::{TenantOwnership, TenantsOwnership};

use super::{
    account::VerboseStatus, guest_role::Permission,
    native_error_codes::NativeErrorCodes, related_accounts::RelatedAccounts,
};
use crate::domain::{
    actors::SystemActor,
    dtos::{account::AccountMetaKey, email::Email},
};

use mycelium_base::utils::errors::{execution_err, MappedErrors};
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
use uuid::Uuid;

#[derive(Clone, Debug)]
pub(crate) struct Decision {}

impl Decision {
    #[tracing::instrument(name = "allow", skip_all)]
    pub fn allow<T: ToString>(reason: T) {
        tracing::trace!("AllowedBy: {}", reason.to_string());
    }

    #[tracing::instrument(name = "deny", skip_all)]
    pub fn deny<T: ToString>(reason: T) {
        tracing::warn!("DeniedBy: {}", reason.to_string());
    }
}

/// This object should be used over the application layer operations.
#[derive(Clone, Debug, Deserialize, Serialize, ToSchema, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct Profile {
    #[serde(alias = "owner_credentials")]
    pub owners: Vec<Owner>,

    /// The account unique id
    ///
    /// Such ID is related to the account primary-key instead of the owner
    /// primary key. In the case of the subscription accounts (accounts flagged
    /// with `is_subscription`) such ID should be propagated along the
    /// application flow.
    #[serde(alias = "current_account_id")]
    pub acc_id: Uuid,

    /// If profile belongs to a `subscription` account
    ///
    /// Subscription accounts should be used to manage legal entities. Only
    /// subscription accounts should receive guest accounts.
    pub is_subscription: bool,

    /// If profile belongs to a `manager` account
    ///
    /// Manager accounts should be used by users with elevated privileges inside
    /// the Mycelium platform. Such user should perform actions like create
    /// roles, guest-roles, guest default-user accounts to work into
    /// subscription accounts.
    pub is_manager: bool,

    /// If profile belongs to a `staff` account
    ///
    /// Staff user has elevated roles into the application. Like managers, staff
    /// users has elevated privileges. Only staff user has permission to
    /// delegate other staffs.
    pub is_staff: bool,

    /// If the account owner is active
    ///
    /// Profiles exists to abstract account privileges. If the profile is
    /// related to an inactive owner the profile could not perform any action.
    /// Only staff or manager user should perform the activation of such users.
    pub owner_is_active: bool,

    /// If the account itself is inactive
    ///
    /// When inactive accounts should not perform internal operations.
    pub account_is_active: bool,

    /// If the account was approved after registration
    ///
    /// New accounts should be approved by manager or staff users after their
    /// registration into the Mycelium platform. Case the approval was
    /// performed, this flag should be true.
    pub account_was_approved: bool,

    /// If the account was archived after registration
    ///
    /// New accounts should be archived. After archived accounts should not be
    /// included at default filtering actions.
    pub account_was_archived: bool,

    /// If the account was deleted after registration
    ///
    /// New accounts should be deleted. After deleted accounts should not be
    /// included at default filtering actions.
    pub account_was_deleted: bool,

    /// Indicate the profile status for humans
    ///
    /// The profile status is composed of all account flags statuses
    /// composition. But it is not readable for humans. These struct attribute
    /// allows human users to understand the account status without read the
    /// flags, avoiding misinterpretation of this.
    pub verbose_status: Option<VerboseStatus>,

    /// Accounts guested to the current profile
    ///
    /// Guest accounts delivers information about the guest account role and
    /// their respective permissions inside the host account. A single account
    /// should be several licenses into the same account.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub licensed_resources: Option<LicensedResources>,

    /// Tenants which the profile has ownership
    ///
    /// This field should be used to store the tenants that the profile has
    /// ownership. The ownership should be used to filter the licensed resources
    /// during system validations.
    ///
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tenants_ownership: Option<TenantsOwnership>,

    /// The Account Meta
    ///
    /// Store metadata about the account.
    ///
    #[serde(skip_serializing_if = "Option::is_none")]
    pub meta: Option<HashMap<AccountMetaKey, String>>,

    /// This argument stores the licensed resources state
    ///
    /// The licensed_resources_state should store the current filtering state.
    /// The filtering state should be populated when a filtering cascade is
    /// performed. As example:
    ///
    /// If a profile with two licensed resources is filtered by the tenant_id
    /// the state should store the tenant id used to filter licensed resources.
    ///
    /// State formatting:
    ///
    /// ```json
    /// [
    ///    "1:tenantId:123e4567-e89b-12d3-a456-426614174000",
    /// ]
    /// ```
    ///
    /// And then, if the used apply a secondary filter, by permission, the state
    /// should be updated to:
    ///
    /// ```json
    /// [
    ///   "1:tenantId:123e4567-e89b-12d3-a456-426614174000",
    ///   "2:permission:1",
    /// ]
    /// ```
    ///
    /// If a consecutive filter with more one tenant is applied, the state
    /// should be updated to:
    ///
    /// ```json
    /// [
    ///  "1:tenantId:123e4567-e89b-12d3-a456-426614174000",
    ///  "2:permission:1",
    ///  "3:tenantId:123e4567-e89b-12d3-a456-426614174001",
    /// ]
    /// ```
    ///
    #[serde(skip_serializing_if = "Option::is_none")]
    filtering_state: Option<Vec<String>>,
}

impl Default for Profile {
    fn default() -> Self {
        Self::new(
            vec![],
            Uuid::new_v4(),
            false,
            false,
            false,
            true,
            true,
            true,
            false,
            false,
            None,
            None,
            None,
        )
    }
}

impl Profile {
    pub fn new(
        owners: Vec<Owner>,
        acc_id: Uuid,
        is_subscription: bool,
        is_manager: bool,
        is_staff: bool,
        owner_is_active: bool,
        account_is_active: bool,
        account_was_approved: bool,
        account_was_archived: bool,
        account_was_deleted: bool,
        verbose_status: Option<VerboseStatus>,
        licensed_resources: Option<LicensedResources>,
        tenants_ownership: Option<TenantsOwnership>,
    ) -> Self {
        Self {
            owners,
            acc_id,
            is_subscription,
            is_manager,
            is_staff,
            owner_is_active,
            account_is_active,
            account_was_approved,
            account_was_archived,
            account_was_deleted,
            verbose_status,
            licensed_resources,
            tenants_ownership,
            filtering_state: None,
            meta: None,
        }
    }

    /// Update the filtering state
    ///
    /// This method updates the filtering state with the new key and value.
    ///
    #[tracing::instrument(name = "update_state", skip_all)]
    fn update_state(&self, key: String, value: String) -> Self {
        let mut state = self.filtering_state.clone().unwrap_or_default();

        state.push(format!(
            "{}:{}",
            state.len() + 1,
            format!("{}:{}", key, value)
        ));

        Self {
            filtering_state: Some(state),
            ..self.clone()
        }
    }

    /// Profile string
    ///
    /// This method returns a string representation of the profile.
    ///
    #[tracing::instrument(name = "profile_string", skip_all)]
    pub fn profile_string(&self) -> String {
        format!("profile/{}", self.acc_id)
    }

    /// Profile redacted string
    ///
    /// Print the profile using the profile_string struct method and a list of
    /// owners, using the `redacted_email` structural method of the email field
    /// present in owners.
    ///
    #[tracing::instrument(name = "profile_redacted", skip_all)]
    pub fn profile_redacted(&self) -> String {
        format!(
            "profile/{} owners: [{}]",
            self.acc_id,
            self.owners
                .iter()
                .map(|i| Email::from_string(i.email.to_owned())
                    .unwrap()
                    .redacted_email())
                .collect::<Vec<String>>()
                .join(", ")
        )
    }

    /// Get the owners ids
    ///
    /// This method returns the ids of the owners of the profile.
    ///
    #[tracing::instrument(name = "get_owners_ids", skip_all)]
    pub fn get_owners_ids(&self) -> Vec<Uuid> {
        self.owners.iter().map(|i| i.id).collect()
    }

    /// Check if the profile has administration privileges
    ///
    /// This method checks if the profile has administration privileges. If the
    /// profile has no administration privileges, it returns false.
    ///
    #[tracing::instrument(name = "has_admin_privileges", skip_all)]
    pub fn has_admin_privileges(&self) -> bool {
        self.is_staff || self.is_manager
    }

    /// Check if the profile has administration privileges or return error
    ///
    /// This method checks if the profile has administration privileges. If the
    /// profile has no administration privileges, it returns an error.
    ///
    #[tracing::instrument(name = "has_admin_privileges_or_error", skip_all)]
    pub fn has_admin_privileges_or_error(&self) -> Result<(), MappedErrors> {
        match self.is_staff || self.is_manager {
            false => {
                Decision::deny(
                    "Current account has no administration privileges",
                );

                execution_err(
                    "Current account has no administration privileges",
                )
                .with_code(NativeErrorCodes::MYC00019)
                .with_exp_true()
                .as_error()
            }
            true => {
                Decision::allow(
                    "Current account has administration privileges",
                );

                Ok(())
            }
        }
    }

    /// Filter the licensed resources by permit flags
    ///
    /// This method filters resources that have ALL the specified flags
    /// present in their `permit_flags` field.
    #[tracing::instrument(name = "has_permit_flags", skip_all)]
    pub fn has_permit_flags<T: ToString>(&self, flags: Vec<T>) -> Self {
        let flags: Vec<String> =
            flags.into_iter().map(|f| f.to_string()).collect();

        //
        // Filter the licensed resources by permit flags
        //
        let licensed_resources =
            if let Some(resources) = self.licensed_resources.as_ref() {
                let records: Vec<LicensedResource> = resources
                    .to_licenses_vector()
                    .iter()
                    .filter(|i| {
                        if let Some(permit_flags) = &i.permit_flags {
                            flags.iter().all(|f| permit_flags.contains(f))
                        } else {
                            false
                        }
                    })
                    .map(|i| i.to_owned())
                    .collect();

                if records.is_empty() {
                    None
                } else {
                    Some(LicensedResources::Records(records))
                }
            } else {
                None
            };

        //
        // Return the new profile
        //
        Self {
            licensed_resources,
            ..self
                .update_state("permittedFlags".to_string(), flags.join(","))
                .clone()
        }
    }

    /// Filter the licensed resources by deny flags
    ///
    /// This method filters resources that do NOT have ANY of the specified
    /// flags present in their `deny_flags` field.
    #[tracing::instrument(name = "has_not_deny_flags", skip_all)]
    pub fn has_not_deny_flags<T: ToString>(&self, flags: Vec<T>) -> Self {
        let flags: Vec<String> =
            flags.into_iter().map(|f| f.to_string()).collect();

        //
        // Filter the licensed resources by deny flags
        //
        let licensed_resources =
            if let Some(resources) = self.licensed_resources.as_ref() {
                let records: Vec<LicensedResource> = resources
                    .to_licenses_vector()
                    .iter()
                    .filter(|i| {
                        if let Some(deny_flags) = &i.deny_flags {
                            !flags.iter().any(|f| deny_flags.contains(f))
                        } else {
                            true
                        }
                    })
                    .map(|i| i.to_owned())
                    .collect();

                if records.is_empty() {
                    None
                } else {
                    Some(LicensedResources::Records(records))
                }
            } else {
                None
            };

        //
        // Return the new profile
        //
        Self {
            licensed_resources,
            ..self
                .update_state("deniedFlags".to_string(), flags.join(","))
                .clone()
        }
    }

    /// Filter the licensed resources to the tenant
    ///
    /// This method should be used to filter licensed resources to the tenant
    /// that the profile is currently working on.
    #[tracing::instrument(name = "on_tenant", skip_all)]
    pub fn on_tenant(&self, tenant_id: Uuid) -> Self {
        //
        // Filter the licensed resources to the tenant
        //
        let licensed_resources =
            if let Some(resources) = self.licensed_resources.as_ref() {
                let records: Vec<LicensedResource> = resources
                    .to_licenses_vector()
                    .iter()
                    .filter(|i| i.tenant_id == tenant_id)
                    .map(|i| i.to_owned())
                    .collect();

                if records.is_empty() {
                    None
                } else {
                    Some(LicensedResources::Records(records))
                }
            } else {
                None
            };

        //
        // Return the new profile
        //
        Self {
            licensed_resources,
            ..self
                .update_state("tenantId".to_string(), tenant_id.to_string())
                .clone()
        }
    }

    /// Filter the licensed resources to the tenant as manager
    ///
    /// This method should be used to filter licensed resources to the tenant
    /// that the profile is currently working on.
    #[tracing::instrument(name = "on_tenant_as_manager", skip_all)]
    pub fn on_tenant_as_manager(
        &self,
        tenant_id: Uuid,
        permission: Permission,
    ) -> Self {
        let profile = self
            .on_tenant(tenant_id)
            .with_permission(permission)
            .with_roles(vec![SystemActor::TenantManager]);

        //
        // Return the new profile
        //
        Self {
            ..profile
                .update_state("isTenantManager".to_string(), "true".to_string())
                .clone()
        }
    }

    /// Filter the licensed resources to the account
    ///
    /// This method should be used to filter licensed resources to the account
    /// that the profile is currently working on.
    #[tracing::instrument(name = "on_account", skip_all)]
    pub fn on_account(&self, account_id: Uuid) -> Self {
        let licensed_resources =
            if let Some(resources) = self.licensed_resources.as_ref() {
                let records: Vec<LicensedResource> = resources
                    .to_licenses_vector()
                    .iter()
                    .filter(|i| i.acc_id == account_id)
                    .map(|i| i.to_owned())
                    .collect();

                if records.is_empty() {
                    None
                } else {
                    Some(LicensedResources::Records(records))
                }
            } else {
                None
            };

        Self {
            licensed_resources,
            ..self
                .update_state("accountId".to_string(), account_id.to_string())
                .clone()
        }
    }

    /// Filter the tenant ownership by the tenant
    #[tracing::instrument(name = "with_tenant_ownership_or_error", skip_all)]
    pub fn with_tenant_ownership_or_error(
        &self,
        tenant_id: Uuid,
    ) -> Result<Self, MappedErrors> {
        if let Some(tenants) = self.tenants_ownership.as_ref() {
            let tenants = tenants.to_ownership_vector();

            if tenants.iter().any(|i| i.id == tenant_id) {
                let profile = Self {
                    ..self
                        .clone()
                        .update_state(
                            "tenantOwnership".to_string(),
                            tenant_id.to_string(),
                        )
                        .clone()
                };

                Decision::allow("Current account has tenant ownership");

                return Ok(profile);
            }
        }

        Decision::deny("Current account has no tenant ownership");

        execution_err(format!(
            "Insufficient privileges to perform these action (no tenant ownership): {}",
            self.filtering_state.to_owned().unwrap_or(vec![]).join(", ")
        ))
        .with_code(NativeErrorCodes::MYC00019)
        .with_exp_true()
        .as_error()
    }

    /// Filter the licensed resources to include only the standard system
    /// accounts
    #[tracing::instrument(name = "with_system_accounts_access", skip_all)]
    pub fn with_system_accounts_access(&self) -> Self {
        //
        // Filter the licensed resources to the default accounts
        //
        let licensed_resources =
            if let Some(resources) = self.licensed_resources.as_ref() {
                let records: Vec<LicensedResource> = resources
                    .to_licenses_vector()
                    .iter()
                    .filter(|i| i.sys_acc)
                    .map(|i| i.to_owned())
                    .collect();

                if records.is_empty() {
                    None
                } else {
                    Some(LicensedResources::Records(records))
                }
            } else {
                None
            };

        //
        // Return the new profile
        //
        Self {
            licensed_resources,
            ..self
                .update_state("isAccStd".to_string(), "true".to_string())
                .clone()
        }
    }

    /// Filter the licensed resources to include only licenses with read access
    #[tracing::instrument(name = "with_read_access", skip_all)]
    pub fn with_read_access(&self) -> Self {
        self.with_permission(Permission::Read)
    }

    /// Filter the licensed resources to include only licenses with write access
    #[tracing::instrument(name = "with_write_access", skip_all)]
    pub fn with_write_access(&self) -> Self {
        self.with_permission(Permission::Write)
    }

    /// Filter licensed resources by permission
    ///
    /// This is an internal method that should be used to filter the licensed
    /// resources by permission.
    ///
    #[tracing::instrument(name = "with_permission", skip_all)]
    fn with_permission(&self, permission: Permission) -> Self {
        //
        // Filter the licensed resources to the permission
        //
        let licensed_resources =
            if let Some(resources) = self.licensed_resources.as_ref() {
                let records: Vec<LicensedResource> = resources
                    .to_licenses_vector()
                    .iter()
                    .filter(|i| i.perm.to_i32() >= permission.to_i32())
                    .map(|i| i.to_owned())
                    .collect();

                if records.is_empty() {
                    None
                } else {
                    Some(LicensedResources::Records(records))
                }
            } else {
                None
            };

        //
        // Return the new profile
        //
        Self {
            licensed_resources,
            ..self
                .update_state(
                    "permission".to_string(),
                    permission.to_i32().to_string(),
                )
                .clone()
        }
    }

    /// Filter the licensed resources to include only the roles
    ///
    /// This method filters the licensed resources to include only the roles
    /// that the profile has.
    ///
    #[tracing::instrument(name = "with_roles", skip_all)]
    pub fn with_roles<T: ToString>(&self, roles: Vec<T>) -> Self {
        //
        // Filter the licensed resources to the roles
        //
        let licensed_resources =
            if let Some(resources) = self.licensed_resources.as_ref() {
                let records: Vec<LicensedResource> = resources
                    .to_licenses_vector()
                    .iter()
                    .filter(|i| {
                        roles
                            .iter()
                            .map(|i| i.to_string())
                            .collect::<Vec<String>>()
                            .contains(&i.role)
                    })
                    .map(|i| i.to_owned())
                    .collect();

                if records.is_empty() {
                    None
                } else {
                    Some(LicensedResources::Records(records))
                }
            } else {
                None
            };

        //
        // Return the new profile
        //
        Self {
            licensed_resources,
            ..self
                .update_state(
                    "role".to_string(),
                    roles
                        .iter()
                        .map(|i| i.to_string())
                        .collect::<Vec<String>>()
                        .join(","),
                )
                .clone()
        }
    }

    /// Get the related account or error
    ///
    /// This method returns the related account or error.
    ///
    #[tracing::instrument(name = "get_related_account_or_error", skip_all)]
    pub fn get_related_account_or_error(
        &self,
    ) -> Result<RelatedAccounts, MappedErrors> {
        if self.is_staff {
            Decision::allow("Current account has staff privileges");

            return Ok(RelatedAccounts::HasStaffPrivileges);
        }

        if self.is_manager {
            Decision::allow("Current account has manager privileges");

            return Ok(RelatedAccounts::HasManagerPrivileges);
        }

        if let Some(resources) = self.licensed_resources.as_ref() {
            let records: Vec<LicensedResource> = resources.to_licenses_vector();

            if records.is_empty() {
                Decision::deny(
                    "No licensed resources found to perform these action",
                );

                return execution_err(
                    "No licensed resources found to perform these action"
                        .to_string(),
                )
                .with_code(NativeErrorCodes::MYC00019)
                .with_exp_true()
                .as_error();
            }

            Decision::allow("Current account has licensed resources");

            return Ok(RelatedAccounts::AllowedAccounts(
                records.iter().map(|i| i.acc_id).collect(),
            ));
        }

        Decision::deny("Current account has no licensed resources");

        execution_err(format!(
            "Insufficient privileges to perform these action (no accounts): {}",
            self.filtering_state.to_owned().unwrap_or(vec![]).join(", ")
        ))
        .with_code(NativeErrorCodes::MYC00019)
        .with_exp_true()
        .as_error()
    }

    /// Get the tenant wide permission or error
    ///
    /// Use this method to check permission requirements of use-cases accessible
    /// to users with specific roles or with tenant wide permissions. The tenant
    /// wide permissions will be checked first. If the profile has tenant wide
    /// permissions, the method will return the related accounts. If the profile
    /// has no tenant wide permissions, the method will return the related
    /// accounts.
    ///
    #[tracing::instrument(
        name = "get_tenant_wide_permission_or_error",
        skip_all
    )]
    pub fn get_tenant_wide_permission_or_error(
        &self,
        tenant_id: Uuid,
        permission: Permission,
    ) -> Result<RelatedAccounts, MappedErrors> {
        //
        // Check if the profile has staff privileges
        //
        if self.is_staff {
            Decision::allow("Current account has staff privileges");

            return Ok(RelatedAccounts::HasStaffPrivileges);
        }

        //
        // Check if the profile has manager privileges
        //
        if self.is_manager {
            Decision::allow("Current account has manager privileges");

            return Ok(RelatedAccounts::HasManagerPrivileges);
        }

        //
        // Check if the profile has tenant ownership
        //
        if let Some(tenants) = self.tenants_ownership.as_ref() {
            let tenants = tenants.to_ownership_vector();

            if tenants.iter().any(|i| i.id == tenant_id) {
                Decision::allow("Current account has tenant ownership");

                return Ok(RelatedAccounts::HasTenantWidePrivileges(tenant_id));
            }
        }

        //
        // Check if the profile has tenant wide privileges by using the
        // tenant manager role.
        //
        if self
            .on_tenant_as_manager(tenant_id, permission)
            .get_ids_or_error()
            .is_ok()
        {
            Decision::allow("Current account has tenant wide privileges");

            return Ok(RelatedAccounts::HasTenantWidePrivileges(tenant_id));
        }

        Decision::deny("Insufficient privileges to perform these action (no tenant wide permission)");

        execution_err(format!(
            "Insufficient privileges to perform these action (no tenant wide permission): {}",
            self.filtering_state.to_owned().unwrap_or(vec![]).join(", ")
        ))
        .with_code(NativeErrorCodes::MYC00019)
        .with_exp_true()
        .as_error()
    }

    /// Get the related accounts or tenant wide permission or error
    ///
    /// Use this method to check permission requirements of use-cases accessible
    /// to users with specific roles or with tenant wide permissions. The tenant
    /// wide permissions will be checked first. If the profile has tenant wide
    /// permissions, the method will return the related accounts. If the profile
    /// has no tenant wide permissions, the method will return the related
    /// accounts.
    ///
    #[tracing::instrument(
        name = "get_related_accounts_or_tenant_wide_permission_or_error",
        skip_all
    )]
    pub fn get_related_accounts_or_tenant_wide_permission_or_error(
        &self,
        tenant_id: Uuid,
        permission: Permission,
    ) -> Result<RelatedAccounts, MappedErrors> {
        //
        // Check if the profile has tenant wide privileges
        //
        if let Ok(related_accounts) =
            self.get_tenant_wide_permission_or_error(tenant_id, permission)
        {
            Decision::allow("Current account has tenant wide privileges");

            return Ok(related_accounts);
        }

        //
        // Check if the profile has access to the account
        //
        Decision::allow("Current account has access to the account");

        self.get_related_account_or_error()
    }

    /// Get the ids or error
    ///
    /// This method returns the ids of the licensed resources or error.
    ///
    #[tracing::instrument(name = "get_ids_or_error", skip_all)]
    pub fn get_ids_or_error(&self) -> Result<Vec<Uuid>, MappedErrors> {
        let ids: Vec<Uuid> = self
            .licensed_resources
            .to_owned()
            .unwrap_or(LicensedResources::Records(vec![]))
            .to_licenses_vector()
            .iter()
            .map(|i| i.acc_id)
            .collect();

        //
        // If none of the conditions are true, return an error
        //
        if !vec![
            //
            // The profile has more than one licensed resource and the profile
            // is not the owner of the account
            //
            !ids.is_empty(),
            //
            // The profile has no admin privileges
            //
            self.has_admin_privileges(),
        ]
        .into_iter()
        .any(|i| i)
        {
            Decision::deny(
                "Insufficient privileges to perform these action (no ids)",
            );

            return execution_err(format!(
                "Insufficient privileges to perform these action (no ids): {}",
                self.filtering_state.to_owned().unwrap_or(vec![]).join(", ")
            ))
            .with_code(NativeErrorCodes::MYC00019)
            .with_exp_true()
            .as_error();
        }

        Decision::allow("Current account has enough ids");

        Ok(ids)
    }
}

// * ---------------------------------------------------------------------------
// * TESTS
// * ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::{
        LicensedResource, LicensedResources, Profile, TenantOwnership,
        TenantsOwnership,
    };
    use crate::domain::dtos::{
        guest_role::Permission, related_accounts::RelatedAccounts,
    };
    use chrono::Local;
    use std::str::FromStr;
    use test_log::test;
    use uuid::Uuid;

    // Define the tenant_id to share between tests
    fn tenant_id() -> Uuid {
        Uuid::from_str("e497848f-a0d4-49f4-8288-c3df11416ff1").unwrap()
    }

    fn profile() -> Profile {
        let tenant_id = tenant_id();

        Profile {
            owners: vec![],
            acc_id: Uuid::new_v4(),
            is_subscription: false,
            is_manager: false,
            is_staff: false,
            owner_is_active: true,
            account_is_active: true,
            account_was_approved: true,
            account_was_archived: false,
            account_was_deleted: false,
            verbose_status: None,
            meta: None,
            licensed_resources: Some(LicensedResources::Records(vec![
                LicensedResource {
                    acc_id: Uuid::new_v4(),
                    tenant_id,
                    role_id: Uuid::new_v4(),
                    acc_name: "Guest Account Name".to_string(),
                    sys_acc: false,
                    role: "service".to_string(),
                    perm: Permission::Write,
                    verified: true,
                    permit_flags: None,
                    deny_flags: None,
                },
                LicensedResource {
                    acc_id: Uuid::new_v4(),
                    tenant_id,
                    role_id: Uuid::new_v4(),
                    acc_name: "Guest Account Name".to_string(),
                    sys_acc: true,
                    role: "newbie".to_string(),
                    perm: Permission::Read,
                    verified: true,
                    permit_flags: None,
                    deny_flags: None,
                },
                LicensedResource {
                    acc_id: Uuid::new_v4(),
                    tenant_id: Uuid::new_v4(),
                    role_id: Uuid::new_v4(),
                    acc_name: "Guest Account Name".to_string(),
                    sys_acc: true,
                    role: "service".to_string(),
                    perm: Permission::Write,
                    verified: true,
                    permit_flags: None,
                    deny_flags: None,
                },
            ])),
            tenants_ownership: Some(TenantsOwnership::Records(vec![
                TenantOwnership {
                    id: tenant_id,
                    name: "Tenant Name".to_string(),
                    since: Local::now(),
                },
            ])),
            filtering_state: None,
        }
    }

    #[test]
    fn test_licensed_resources_from_and_to_string() {
        let licensed_resource = LicensedResource {
            acc_id: Uuid::new_v4(),
            tenant_id: Uuid::new_v4(),
            role_id: Uuid::new_v4(),
            acc_name: "Guest Account Name".to_string(),
            sys_acc: false,
            role: "service".to_string(),
            perm: Permission::Write,
            verified: true,
            permit_flags: None,
            deny_flags: None,
        };

        let licensed_resource_string = licensed_resource.to_string();

        let licensed_resource_parsed =
            LicensedResource::from_str(&licensed_resource_string).unwrap();

        assert_eq!(licensed_resource, licensed_resource_parsed);
    }

    #[test]
    fn test_load_uuid() {
        let uuid_hex_string = "d776e96f94174520b2a99298136031b0";

        let uuid = LicensedResource::load_uuid(uuid_hex_string.to_string());

        assert!(uuid.is_ok());

        assert_eq!(
            Uuid::from_str("d776e96f-9417-4520-b2a9-9298136031b0").unwrap(),
            uuid.unwrap()
        );
    }

    #[test]
    fn test_filtering_permissions() {
        let profile = profile();
        let profile_with_read = profile.with_read_access();
        let profile_with_write = profile.with_write_access();
        let profile_with_standard = profile.with_system_accounts_access();

        assert_eq!(
            3,
            profile_with_read
                .licensed_resources
                .unwrap()
                .to_licenses_vector()
                .len()
        );

        assert_eq!(
            2,
            profile_with_write
                .licensed_resources
                .unwrap()
                .to_licenses_vector()
                .len()
        );

        assert_eq!(
            2,
            profile_with_standard
                .licensed_resources
                .unwrap()
                .to_licenses_vector()
                .len()
        );
    }

    #[test]
    fn test_filtering_on_tenant_cascade() {
        let tenant_id = tenant_id();
        let profile = profile();

        let profile_on_tenant = profile.on_tenant(tenant_id);

        assert_eq!(
            2,
            profile_on_tenant
                .licensed_resources
                .clone()
                .unwrap()
                .to_licenses_vector()
                .len()
        );

        let profile_on_tenant_with_read = profile_on_tenant.with_read_access();
        let profile_on_tenant_with_write =
            profile_on_tenant.with_write_access();
        assert_eq!(
            2,
            profile_on_tenant_with_read
                .licensed_resources
                .unwrap()
                .to_licenses_vector()
                .len()
        );

        assert_eq!(
            1,
            profile_on_tenant_with_write
                .licensed_resources
                .unwrap()
                .to_licenses_vector()
                .len()
        );
    }

    #[test]
    fn test_filtering_by_role() {
        let tenant_id = tenant_id();
        let profile = profile();

        let profile_on_tenant = profile.on_tenant(tenant_id);

        let profile_on_tenant_with_roles =
            profile_on_tenant.with_roles(["service".to_string()].to_vec());

        assert_eq!(
            1,
            profile_on_tenant_with_roles
                .licensed_resources
                .unwrap()
                .to_licenses_vector()
                .len()
        );

        let profile_on_tenant_with_roles =
            profile_on_tenant.with_roles(["newbie".to_string()].to_vec());

        assert_eq!(
            1,
            profile_on_tenant_with_roles
                .licensed_resources
                .unwrap()
                .to_licenses_vector()
                .len()
        );

        let profile_on_tenant_with_roles =
            profile_on_tenant.with_roles(["service", "newbie"].to_vec());

        assert_eq!(
            2,
            profile_on_tenant_with_roles
                .licensed_resources
                .unwrap()
                .to_licenses_vector()
                .len()
        );
    }

    #[test]
    fn test_filtering_as_default() {
        let tenant_id = tenant_id();
        let profile = profile();
        let profile_on_tenant = profile.on_tenant(tenant_id);

        let profile_on_tenant_with_standard =
            profile_on_tenant.with_system_accounts_access();

        assert_eq!(
            1,
            profile_on_tenant_with_standard
                .licensed_resources
                .unwrap()
                .to_licenses_vector()
                .len()
        );
    }

    #[test]
    fn test_with_tenant_ownership_or_error() {
        let tenant_id = tenant_id();
        let profile = profile();

        let profile_on_tenant = profile.on_tenant(tenant_id);

        assert!(profile_on_tenant
            .with_tenant_ownership_or_error(tenant_id)
            .is_ok());

        assert!(profile_on_tenant
            .with_tenant_ownership_or_error(Uuid::new_v4())
            .is_err());
    }

    #[test]
    fn test_get_my_account_details() {
        let profile = profile();
        let result_ok = profile.get_related_account_or_error();

        assert!(result_ok.is_ok());

        let related_accounts = result_ok.unwrap();

        assert_ne!(related_accounts, RelatedAccounts::HasManagerPrivileges);
        assert_ne!(related_accounts, RelatedAccounts::HasStaffPrivileges);

        let account_ids = match related_accounts {
            RelatedAccounts::AllowedAccounts(ids) => ids,
            _ => vec![],
        };

        let licensed_resources = profile.licensed_resources.unwrap();

        let licensed_resources_ids = licensed_resources.to_licenses_vector();

        assert_eq!(account_ids.len(), licensed_resources_ids.len());
        assert!(!account_ids.contains(&profile.acc_id));
    }

    fn profile_with_flags() -> Profile {
        let tenant_id = tenant_id();

        Profile {
            owners: vec![],
            acc_id: Uuid::new_v4(),
            is_subscription: false,
            is_manager: false,
            is_staff: false,
            owner_is_active: true,
            account_is_active: true,
            account_was_approved: true,
            account_was_archived: false,
            account_was_deleted: false,
            verbose_status: None,
            meta: None,
            licensed_resources: Some(LicensedResources::Records(vec![
                LicensedResource {
                    acc_id: Uuid::new_v4(),
                    tenant_id,
                    role_id: Uuid::new_v4(),
                    acc_name: "Account with permit flags".to_string(),
                    sys_acc: false,
                    role: "admin".to_string(),
                    perm: Permission::Write,
                    verified: true,
                    permit_flags: Some(vec![
                        "dashboard".to_string(),
                        "settings".to_string(),
                        "reports".to_string(),
                    ]),
                    deny_flags: None,
                },
                LicensedResource {
                    acc_id: Uuid::new_v4(),
                    tenant_id,
                    role_id: Uuid::new_v4(),
                    acc_name: "Account with deny flags".to_string(),
                    sys_acc: false,
                    role: "viewer".to_string(),
                    perm: Permission::Read,
                    verified: true,
                    permit_flags: Some(vec!["dashboard".to_string()]),
                    deny_flags: Some(vec![
                        "settings".to_string(),
                        "admin_panel".to_string(),
                    ]),
                },
                LicensedResource {
                    acc_id: Uuid::new_v4(),
                    tenant_id,
                    role_id: Uuid::new_v4(),
                    acc_name: "Account without flags".to_string(),
                    sys_acc: false,
                    role: "guest".to_string(),
                    perm: Permission::Read,
                    verified: true,
                    permit_flags: None,
                    deny_flags: None,
                },
                LicensedResource {
                    acc_id: Uuid::new_v4(),
                    tenant_id,
                    role_id: Uuid::new_v4(),
                    acc_name: "Account with all flags".to_string(),
                    sys_acc: false,
                    role: "superuser".to_string(),
                    perm: Permission::Write,
                    verified: true,
                    permit_flags: Some(vec![
                        "dashboard".to_string(),
                        "settings".to_string(),
                        "reports".to_string(),
                        "admin_panel".to_string(),
                    ]),
                    deny_flags: Some(vec!["dangerous_action".to_string()]),
                },
            ])),
            tenants_ownership: Some(TenantsOwnership::Records(vec![
                TenantOwnership {
                    id: tenant_id,
                    name: "Tenant Name".to_string(),
                    since: Local::now(),
                },
            ])),
            filtering_state: None,
        }
    }

    #[test]
    fn test_has_permit_flags_single_flag() {
        let profile = profile_with_flags();

        // Filter by single flag "dashboard" - should match 3 resources
        // (admin, viewer, superuser have dashboard)
        let filtered = profile.has_permit_flags(vec!["dashboard"]);

        assert_eq!(
            3,
            filtered
                .licensed_resources
                .unwrap()
                .to_licenses_vector()
                .len()
        );
    }

    #[test]
    fn test_has_permit_flags_multiple_flags() {
        let profile = profile_with_flags();

        // Filter by multiple flags - should match only resources that have ALL
        // flags (admin and superuser have dashboard + settings)
        let filtered = profile.has_permit_flags(vec!["dashboard", "settings"]);

        assert_eq!(
            2,
            filtered
                .licensed_resources
                .unwrap()
                .to_licenses_vector()
                .len()
        );
    }

    #[test]
    fn test_has_permit_flags_all_three_flags() {
        let profile = profile_with_flags();

        // Filter by three flags - should match admin and superuser
        let filtered =
            profile.has_permit_flags(vec!["dashboard", "settings", "reports"]);

        assert_eq!(
            2,
            filtered
                .licensed_resources
                .unwrap()
                .to_licenses_vector()
                .len()
        );
    }

    #[test]
    fn test_has_permit_flags_no_match() {
        let profile = profile_with_flags();

        // Filter by flag that no one has
        let filtered = profile.has_permit_flags(vec!["nonexistent_flag"]);

        assert!(filtered.licensed_resources.is_none());
    }

    #[test]
    fn test_has_permit_flags_updates_state() {
        let profile = profile_with_flags();

        let filtered = profile.has_permit_flags(vec!["dashboard", "settings"]);

        assert!(filtered.filtering_state.is_some());
        let state = filtered.filtering_state.unwrap();
        assert!(state
            .iter()
            .any(|s| s.contains("permittedFlags:dashboard,settings")));
    }

    #[test]
    fn test_has_not_deny_flags_single_flag() {
        let profile = profile_with_flags();

        // Filter out resources that have "settings" in deny_flags
        // Should exclude viewer (has settings in deny_flags)
        // Should keep: admin (no deny_flags), guest (no deny_flags), superuser
        // (deny_flags doesn't contain settings)
        let filtered = profile.has_not_deny_flags(vec!["settings"]);

        assert_eq!(
            3,
            filtered
                .licensed_resources
                .unwrap()
                .to_licenses_vector()
                .len()
        );
    }

    #[test]
    fn test_has_not_deny_flags_multiple_flags() {
        let profile = profile_with_flags();

        // Filter out resources that have "settings" OR "admin_panel" in
        // deny_flags Should exclude viewer (has both)
        // Should keep: admin (no deny_flags), guest (no deny_flags), superuser
        // (deny_flags doesn't contain these)
        let filtered =
            profile.has_not_deny_flags(vec!["settings", "admin_panel"]);

        assert_eq!(
            3,
            filtered
                .licensed_resources
                .unwrap()
                .to_licenses_vector()
                .len()
        );
    }

    #[test]
    fn test_has_not_deny_flags_no_exclusion() {
        let profile = profile_with_flags();

        // Filter by flag that no one has in deny_flags
        // Should keep all 4 resources
        let filtered = profile.has_not_deny_flags(vec!["nonexistent_flag"]);

        assert_eq!(
            4,
            filtered
                .licensed_resources
                .unwrap()
                .to_licenses_vector()
                .len()
        );
    }

    #[test]
    fn test_has_not_deny_flags_exclude_all_with_deny() {
        let profile = profile_with_flags();

        // Filter by "dangerous_action" - should exclude superuser
        // Should keep: admin, viewer, guest (3 resources)
        let filtered = profile.has_not_deny_flags(vec!["dangerous_action"]);

        assert_eq!(
            3,
            filtered
                .licensed_resources
                .unwrap()
                .to_licenses_vector()
                .len()
        );
    }

    #[test]
    fn test_has_not_deny_flags_updates_state() {
        let profile = profile_with_flags();

        let filtered =
            profile.has_not_deny_flags(vec!["settings", "admin_panel"]);

        assert!(filtered.filtering_state.is_some());
        let state = filtered.filtering_state.unwrap();
        assert!(state
            .iter()
            .any(|s| s.contains("deniedFlags:settings,admin_panel")));
    }

    #[test]
    fn test_combined_permit_and_deny_flags() {
        let profile = profile_with_flags();

        // First filter by permit_flags, then by deny_flags
        let filtered = profile
            .has_permit_flags(vec!["dashboard"])
            .has_not_deny_flags(vec!["settings"]);

        // dashboard: admin, viewer, superuser (3)
        // then exclude settings in deny: viewer has it, so 2 remain
        assert_eq!(
            2,
            filtered
                .licensed_resources
                .unwrap()
                .to_licenses_vector()
                .len()
        );
    }

    #[test]
    fn test_flags_with_tenant_filter() {
        let tenant_id = tenant_id();
        let profile = profile_with_flags();

        // Combine tenant filter with flags filter
        let filtered = profile
            .on_tenant(tenant_id)
            .has_permit_flags(vec!["dashboard", "settings"]);

        assert_eq!(
            2,
            filtered
                .licensed_resources
                .unwrap()
                .to_licenses_vector()
                .len()
        );
    }
}