-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
4332 lines (3723 loc) · 153 KB
/
Copy pathapp.py
File metadata and controls
4332 lines (3723 loc) · 153 KB
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
from __future__ import annotations
# ---------------------------------------------------------------------------
# AccessAtlas single-file quick-start application
# ---------------------------------------------------------------------------
#
# GENERATED FILE — DO NOT EDIT AS THE ENGINEERING SOURCE OF TRUTH.
#
# Canonical source:
# modular/app.py
# modular/accessatlas/
#
# Rebuild after changing canonical source:
# python tools/build_single_file.py
#
# Verify the committed quick-start file is current:
# python tools/build_single_file.py --check
#
# This generated distribution publishes the clean starter runtime as one
# directly editable Streamlit file for quick-start adopters.
# Hosted demo controls remain only in modular/demo_app.py and demo_runtime.py.
# ---------------------------------------------------------------------------
# === Shared module: accessatlas/config.py ===
from pathlib import Path
def _find_project_root():
"""Find the nearest parent containing the shared AccessAtlas data directory."""
current_path = Path(__file__).resolve().parent
for candidate in (current_path, *current_path.parents):
if (candidate / "data").is_dir():
return candidate
return Path.cwd()
PROJECT_ROOT = _find_project_root()
DATA_DIR = PROJECT_ROOT / "data"
ANNUAL_TRAINING_VALID_YEARS = 1
BIENNIAL_TRAINING_VALID_YEARS = 2
EXPIRING_SOON_DAYS = 30
RECONCILIATION_KEY_COLUMNS = [
"user_id",
"system_id",
"resource_type",
"resource_name",
"permission_name",
]
RECONCILIATION_REQUIRED_COLUMNS = RECONCILIATION_KEY_COLUMNS + ["access_status"]
TRAINING_RECONCILIATION_DATE_COLUMNS = [
"annual_training_date",
"biennial_training_date",
"access_agreement_date",
]
TRAINING_RECONCILIATION_REQUIRED_COLUMNS = ["user_id"] + TRAINING_RECONCILIATION_DATE_COLUMNS
ROLE_VISIBLE_TABS = {
"User": ["My Access"],
"Manager": ["Dashboard", "My Access", "Manage Access", "Access Reconciliation"],
"System Administrator": [
"Dashboard",
"My Access",
"Manage Access",
"Access Reconciliation",
],
"Super Administrator": [
"Dashboard",
"My Access",
"Manage Access",
"Access Reconciliation",
"AccessAtlas App Admin",
],
}
TAB_LABELS = [
"Dashboard",
"My Access",
"Manage Access",
"Access Reconciliation",
"AccessAtlas App Admin",
]
TAB_DISPLAY_LABELS = {
"Dashboard": "🏠 Dashboard",
"My Access": "👤 My Access",
"Manage Access": "🛠️ Manage Access",
"Access Reconciliation": "🔄 Access Reconciliation",
"AccessAtlas App Admin": "⚙️ AccessAtlas App Admin",
}
USER_DISPLAY_COLUMNS = [
"user_id",
"display_name",
"email",
"application_role",
"manager_user_id",
"department",
"user_type",
"record_status",
"compliance_status",
]
COMPLIANCE_COLUMNS = [
"user_id",
"display_name",
"email",
"department",
"user_type",
"record_status",
"annual_training_date",
"annual_training_expiration",
"biennial_training_date",
"biennial_training_expiration",
"access_agreement_date",
"compliance_status",
]
COLUMN_LABELS = {
"access_agreement_date": "Access Agreement Date",
"access_id": "Access ID",
"access_model": "Access Model",
"access_records": "Access Records",
"access_status": "Access Status",
"admin_assignment_count": "Admin Assignments",
"admin_group": "Admin Group",
"admin_role": "Admin Role",
"annual_training_date": "Annual Training Date",
"annual_training_expiration": "Annual Training Expiration",
"application_role": "Application Role",
"assignment_source": "Assignment Source",
"assignment_status": "Assignment Status",
"assigned_by": "Assigned By",
"assigned_users": "Assigned Users",
"audit_event_id": "Audit Event ID",
"biennial_training_date": "Biennial Training Date",
"biennial_training_expiration": "Biennial Training Expiration",
"change_type": "Change Type",
"changes_identified": "Changes Identified",
"changes_made": "Changes Made",
"compliance_status": "Compliance Status",
"current_access_agreement_date": "Current Access Agreement Date",
"current_access_status": "Current Access Status",
"current_annual_training_date": "Current Annual Training Date",
"current_biennial_training_date": "Current Biennial Training Date",
"current_record_status": "Current Record Status",
"department": "Department",
"display_name": "Display Name",
"email": "Email",
"expiration_date": "Expiration Date",
"expiration_status": "Expiration Status",
"first_name": "First Name",
"granted_date": "Granted Date",
"last_name": "Last Name",
"manager_user_id": "Manager User ID",
"notes": "Notes",
"permission_name": "Permission",
"record_status": "Record Status",
"record_type": "Record Type",
"recommended_action": "Recommended Action",
"resource_name": "Resource Name",
"resource_scope": "Resource Scope",
"resource_type": "Resource Type",
"revoked_date": "Revoked Date",
"source": "Source",
"source_system_record_id": "Source Record ID",
"system_category": "System Category",
"system_id": "System ID",
"system_name": "System Name",
"system_owner": "System Owner",
"system_type": "System Type",
"tracking_method": "Tracking Method",
"uploaded_access_agreement_date": "Uploaded Access Agreement Date",
"uploaded_access_status": "Uploaded Access Status",
"uploaded_annual_training_date": "Uploaded Annual Training Date",
"uploaded_biennial_training_date": "Uploaded Biennial Training Date",
"user_id": "User ID",
"user_type": "User Type",
"users": "Users",
}
# === Shared module: accessatlas/logging_config.py ===
import json
import logging
import os
import sys
from contextvars import ContextVar
from datetime import datetime, timezone
from typing import Any, Mapping
LOG_LEVEL_ENV = "ACCESSATLAS_LOG_LEVEL"
LOG_FORMAT_ENV = "ACCESSATLAS_LOG_FORMAT"
DEFAULT_LOG_LEVEL = "INFO"
DEFAULT_LOG_FORMAT = "json"
LOGGER_NAMESPACE = "accessatlas"
_runtime_name: ContextVar[str] = ContextVar("accessatlas_runtime_name", default="unresolved")
_application_role: ContextVar[str] = ContextVar(
"accessatlas_application_role", default="unresolved"
)
_RESERVED_RECORD_FIELDS = set(logging.makeLogRecord({}).__dict__) | {
"message",
"asctime",
}
def _normalize_log_level(value: str | None) -> int:
"""Return a valid logging level from configuration."""
normalized = (value or DEFAULT_LOG_LEVEL).strip().upper()
level = logging.getLevelName(normalized)
return level if isinstance(level, int) else logging.INFO
def _normalize_log_format(value: str | None) -> str:
"""Return a supported output format."""
normalized = (value or DEFAULT_LOG_FORMAT).strip().lower()
return normalized if normalized in {"json", "text"} else DEFAULT_LOG_FORMAT
def _json_safe(value: Any) -> Any:
"""Return a JSON-serializable representation of a log field."""
if value is None or isinstance(value, (str, int, float, bool)):
return value
if isinstance(value, Mapping):
return {str(key): _json_safe(item) for key, item in value.items()}
if isinstance(value, (list, tuple, set)):
return [_json_safe(item) for item in value]
return str(value)
class AccessAtlasContextFilter(logging.Filter):
"""Attach runtime context to every AccessAtlas application log record."""
def filter(self, record: logging.LogRecord) -> bool:
record.runtime_name = _runtime_name.get()
record.application_role = _application_role.get()
return True
class JsonFormatter(logging.Formatter):
"""Render AccessAtlas application logs as one JSON object per line."""
def format(self, record: logging.LogRecord) -> str:
payload = {
"timestamp": datetime.fromtimestamp(
record.created,
tz=timezone.utc,
).isoformat(),
"level": record.levelname,
"logger": record.name,
"event": getattr(record, "event_name", "application_log"),
"message": record.getMessage(),
"runtime": getattr(record, "runtime_name", "unresolved"),
"application_role": getattr(record, "application_role", "unresolved"),
}
event_fields = getattr(record, "event_fields", {})
if event_fields:
payload["fields"] = _json_safe(event_fields)
if record.exc_info:
payload["exception"] = self.formatException(record.exc_info)
return json.dumps(payload, separators=(",", ":"), sort_keys=True)
class TextFormatter(logging.Formatter):
"""Render readable local-development application logs."""
def format(self, record: logging.LogRecord) -> str:
event_name = getattr(record, "event_name", "application_log")
event_fields = getattr(record, "event_fields", {})
fields_text = ""
if event_fields:
fields_text = f" fields={json.dumps(_json_safe(event_fields), sort_keys=True)}"
message = (
f"{datetime.fromtimestamp(record.created, tz=timezone.utc).isoformat()} "
f"{record.levelname} {record.name} "
f"event={event_name} runtime={getattr(record, 'runtime_name', 'unresolved')} "
f"role={getattr(record, 'application_role', 'unresolved')} "
f"{record.getMessage()}{fields_text}"
)
if record.exc_info:
message = f"{message}\n{self.formatException(record.exc_info)}"
return message
def configure_logging(
*,
level: str | None = None,
output_format: str | None = None,
) -> logging.Logger:
"""Configure the AccessAtlas logger namespace once per Python process.
Repeated calls update the handler level and formatter without adding
duplicate handlers. This is important in Streamlit, where the app script
reruns during user interaction.
"""
logger = logging.getLogger(LOGGER_NAMESPACE)
logger.setLevel(_normalize_log_level(level or os.getenv(LOG_LEVEL_ENV)))
logger.propagate = False
selected_format = _normalize_log_format(output_format or os.getenv(LOG_FORMAT_ENV))
formatter: logging.Formatter = JsonFormatter() if selected_format == "json" else TextFormatter()
handler = next(
(
candidate
for candidate in logger.handlers
if getattr(candidate, "_accessatlas_handler", False)
),
None,
)
if handler is None:
handler = logging.StreamHandler(sys.stdout)
handler._accessatlas_handler = True # type: ignore[attr-defined]
handler.addFilter(AccessAtlasContextFilter())
logger.addHandler(handler)
handler.setLevel(logger.level)
handler.setFormatter(formatter)
return logger
def get_logger(name: str) -> logging.Logger:
"""Return a child logger inside the AccessAtlas application namespace."""
if name == LOGGER_NAMESPACE or name.startswith(f"{LOGGER_NAMESPACE}."):
logger_name = name
else:
logger_name = f"{LOGGER_NAMESPACE}.{name}"
return logging.getLogger(logger_name)
def set_runtime_log_context(
*,
runtime_name: str,
application_role: str,
) -> None:
"""Set low-cardinality runtime context for subsequent application logs."""
_runtime_name.set(runtime_name)
_application_role.set(application_role)
def reset_runtime_log_context() -> None:
"""Reset runtime context to its unresolved startup state."""
_runtime_name.set("unresolved")
_application_role.set("unresolved")
def log_event(
logger: logging.Logger,
level: int,
event_name: str,
message: str,
**fields: Any,
) -> None:
"""Write one structured application event."""
logger.log(
level,
message,
extra={
"event_name": event_name,
"event_fields": fields,
},
)
def log_exception(
logger: logging.Logger,
event_name: str,
message: str,
**fields: Any,
) -> None:
"""Write one structured exception event with the active traceback."""
logger.exception(
message,
extra={
"event_name": event_name,
"event_fields": fields,
},
)
# === Shared module: accessatlas/audit.py ===
import json
from contextvars import ContextVar
from dataclasses import asdict, dataclass
from datetime import datetime, timezone
from typing import Any, Protocol
from uuid import uuid4
import pandas as pd
_AUDIT_STATE_KEY = "governance_audit_events"
_AUDIT_ACTOR_USER_ID: ContextVar[str] = ContextVar(
"accessatlas_audit_actor_user_id",
default="",
)
_AUDIT_ACTOR_ROLE: ContextVar[str] = ContextVar(
"accessatlas_audit_actor_role",
default="",
)
_AUDIT_RUNTIME: ContextVar[str] = ContextVar(
"accessatlas_audit_runtime",
default="unknown",
)
@dataclass(frozen=True)
class AuditEvent:
"""One immutable governance action record."""
audit_event_id: str
occurred_at: str
event_type: str
action: str
actor_user_id: str
actor_role: str
runtime: str
entity_type: str
entity_id: str
target_user_id: str
system_id: str
outcome: str
source: str
summary: str
changes_json: str
def to_record(self) -> dict[str, str]:
"""Return a tabular event record."""
return asdict(self)
class AuditStore(Protocol):
"""Storage contract for append-oriented governance audit events."""
def append(self, event: AuditEvent) -> None:
"""Append one immutable audit event."""
def list_events(self) -> list[AuditEvent]:
"""Return audit events in append order."""
class SessionAuditStore:
"""Streamlit session-backed reference audit store.
A state mapping may be injected for tests or alternative session containers.
When omitted, the store resolves Streamlit session state lazily.
"""
def __init__(
self,
state_key: str = _AUDIT_STATE_KEY,
state: dict[str, Any] | None = None,
):
self.state_key = state_key
self._state = state
def _state_mapping(self):
if self._state is not None:
return self._state
import streamlit as st
return st.session_state
def _initialize(self) -> None:
state = self._state_mapping()
if self.state_key not in state:
state[self.state_key] = []
def append(self, event: AuditEvent) -> None:
self._initialize()
self._state_mapping()[self.state_key].append(event.to_record())
def list_events(self) -> list[AuditEvent]:
self._initialize()
return [AuditEvent(**record) for record in self._state_mapping()[self.state_key]]
def set_audit_actor_context(
actor_user_id: str,
actor_role: str,
runtime: str,
) -> None:
"""Set actor and runtime context used by subsequent governance events."""
_AUDIT_ACTOR_USER_ID.set(str(actor_user_id or ""))
_AUDIT_ACTOR_ROLE.set(str(actor_role or ""))
_AUDIT_RUNTIME.set(str(runtime or "unknown"))
def reset_audit_actor_context() -> None:
"""Reset governance audit actor context."""
_AUDIT_ACTOR_USER_ID.set("")
_AUDIT_ACTOR_ROLE.set("")
_AUDIT_RUNTIME.set("unknown")
def _safe_json(value: Any) -> str:
"""Serialize audit change details predictably."""
return json.dumps(
value or {},
default=str,
sort_keys=True,
separators=(",", ":"),
)
def create_audit_event(
*,
event_type: str,
action: str,
entity_type: str,
entity_id: str = "",
target_user_id: str = "",
system_id: str = "",
outcome: str = "success",
source: str = "AccessAtlas",
summary: str,
changes: dict[str, Any] | None = None,
) -> AuditEvent:
"""Create one governance audit event from the active actor context."""
occurred_at = datetime.now(timezone.utc).isoformat()
event_id = f"AUD-{datetime.now(timezone.utc).year}-{uuid4().hex[:12].upper()}"
return AuditEvent(
audit_event_id=event_id,
occurred_at=occurred_at,
event_type=str(event_type),
action=str(action),
actor_user_id=_AUDIT_ACTOR_USER_ID.get(),
actor_role=_AUDIT_ACTOR_ROLE.get(),
runtime=_AUDIT_RUNTIME.get(),
entity_type=str(entity_type),
entity_id=str(entity_id or ""),
target_user_id=str(target_user_id or ""),
system_id=str(system_id or ""),
outcome=str(outcome),
source=str(source),
summary=str(summary),
changes_json=_safe_json(changes),
)
def record_audit_event(
*,
event_type: str,
action: str,
entity_type: str,
entity_id: str = "",
target_user_id: str = "",
system_id: str = "",
outcome: str = "success",
source: str = "AccessAtlas",
summary: str,
changes: dict[str, Any] | None = None,
store: AuditStore | None = None,
) -> AuditEvent:
"""Create and append one governance audit event."""
audit_store = store or SessionAuditStore()
event = create_audit_event(
event_type=event_type,
action=action,
entity_type=entity_type,
entity_id=entity_id,
target_user_id=target_user_id,
system_id=system_id,
outcome=outcome,
source=source,
summary=summary,
changes=changes,
)
audit_store.append(event)
return event
def get_audit_events(store: AuditStore | None = None) -> pd.DataFrame:
"""Return governance audit history as a display/export-ready dataframe."""
audit_store = store or SessionAuditStore()
records = [event.to_record() for event in audit_store.list_events()]
columns = [
"audit_event_id",
"occurred_at",
"event_type",
"action",
"actor_user_id",
"actor_role",
"runtime",
"entity_type",
"entity_id",
"target_user_id",
"system_id",
"outcome",
"source",
"summary",
"changes_json",
]
if not records:
return pd.DataFrame(columns=columns)
return pd.DataFrame(records, columns=columns)
# === Shared module: accessatlas/compliance.py ===
from datetime import date
import pandas as pd
def compliance_status(row):
"""Return compliance status based on training expiration rules."""
today_ts = pd.Timestamp(date.today())
annual_exp = row["annual_training_date"] + pd.DateOffset(years=ANNUAL_TRAINING_VALID_YEARS)
biennial_exp = row["biennial_training_date"] + pd.DateOffset(
years=BIENNIAL_TRAINING_VALID_YEARS
)
if annual_exp < today_ts or biennial_exp < today_ts:
return "Expired"
warning_date = today_ts + pd.Timedelta(days=EXPIRING_SOON_DAYS)
if annual_exp <= warning_date or biennial_exp <= warning_date:
return "Expiring Soon"
return "Current"
def add_expirations(users):
"""Add expiration dates and compliance status fields to the user dataset."""
users = users.copy()
users["annual_training_expiration"] = users["annual_training_date"] + pd.DateOffset(
years=ANNUAL_TRAINING_VALID_YEARS
)
users["biennial_training_expiration"] = users["biennial_training_date"] + pd.DateOffset(
years=BIENNIAL_TRAINING_VALID_YEARS
)
users["compliance_status"] = users.apply(compliance_status, axis=1)
return users
def get_expired_follow_up_records(user_records):
"""Return individual expired compliance records needing follow-up."""
follow_up_rows = []
today_ts = pd.Timestamp(date.today())
for _, user_row in user_records.iterrows():
checks = [
("Annual Training", user_row.get("annual_training_expiration")),
("Biennial Training", user_row.get("biennial_training_expiration")),
]
for record_type, expiration_date in checks:
if pd.isna(expiration_date):
continue
expiration_ts = pd.to_datetime(expiration_date)
if expiration_ts < today_ts:
follow_up_rows.append(
{
"user_id": user_row.get("user_id"),
"display_name": user_row.get("display_name"),
"email": user_row.get("email"),
"record_type": record_type,
"expiration_date": expiration_ts.date(),
"expiration_status": "Expired",
}
)
return pd.DataFrame(follow_up_rows)
def normalize_date_value(value):
"""Return a normalized date string for comparison and display."""
if pd.isna(value) or value == "":
return ""
return str(pd.to_datetime(value).date())
def uploaded_dates_compliance_status(uploaded_values):
"""Return compliance status based on uploaded training and agreement dates."""
today_ts = pd.Timestamp(date.today())
annual_date = pd.to_datetime(uploaded_values.get("annual_training_date", ""))
biennial_date = pd.to_datetime(uploaded_values.get("biennial_training_date", ""))
if pd.isna(annual_date) or pd.isna(biennial_date):
return "Expired"
annual_exp = annual_date + pd.DateOffset(years=ANNUAL_TRAINING_VALID_YEARS)
biennial_exp = biennial_date + pd.DateOffset(years=BIENNIAL_TRAINING_VALID_YEARS)
if annual_exp < today_ts or biennial_exp < today_ts:
return "Expired"
warning_date = today_ts + pd.Timedelta(days=EXPIRING_SOON_DAYS)
if annual_exp <= warning_date or biennial_exp <= warning_date:
return "Expiring Soon"
return "Current"
# === Shared module: accessatlas/exports.py ===
import re
from dataclasses import dataclass
from typing import Iterable
import pandas as pd
logger = get_logger(__name__)
_FORMULA_PREFIXES = ("=", "+", "-", "@")
@dataclass(frozen=True)
class CsvExportArtifact:
"""Prepared CSV download artifact."""
export_name: str
filename: str
data: bytes
mime_type: str
record_count: int
column_count: int
def _safe_export_name(export_name: str) -> str:
"""Return a filesystem-friendly export name."""
normalized = re.sub(r"[^A-Za-z0-9_-]+", "_", str(export_name).strip())
normalized = normalized.strip("_")
return normalized or "accessatlas_export"
def _sanitize_csv_value(value):
"""Protect spreadsheet consumers from formula-style CSV cell execution."""
if not isinstance(value, str):
return value
stripped = value.lstrip()
if stripped.startswith(_FORMULA_PREFIXES):
return "'" + value
return value
def prepare_export_dataframe(
dataframe: pd.DataFrame,
*,
columns: Iterable[str] | None = None,
sort_by: Iterable[str] | None = None,
) -> pd.DataFrame:
"""Return a stable, sanitized dataframe for CSV export."""
export_frame = dataframe.copy()
if columns is not None:
requested_columns = list(columns)
missing_columns = [
column for column in requested_columns if column not in export_frame.columns
]
if missing_columns:
raise ValueError(
"Export columns are missing from the dataframe: " + ", ".join(missing_columns)
)
export_frame = export_frame[requested_columns]
if sort_by is not None:
sort_columns = [column for column in sort_by if column in export_frame.columns]
if sort_columns:
export_frame = export_frame.sort_values(
sort_columns,
kind="stable",
)
object_columns = export_frame.select_dtypes(include=["object", "string"]).columns
for column in object_columns:
export_frame[column] = export_frame[column].map(_sanitize_csv_value)
return export_frame.reset_index(drop=True)
def prepare_csv_export(
dataframe: pd.DataFrame,
*,
export_name: str,
columns: Iterable[str] | None = None,
sort_by: Iterable[str] | None = None,
) -> CsvExportArtifact:
"""Prepare one portable UTF-8 CSV download artifact."""
try:
export_frame = prepare_export_dataframe(
dataframe,
columns=columns,
sort_by=sort_by,
)
safe_name = _safe_export_name(export_name)
csv_text = export_frame.to_csv(
index=False,
lineterminator="\n",
)
return CsvExportArtifact(
export_name=safe_name,
filename=f"{safe_name}.csv",
data=csv_text.encode("utf-8-sig"),
mime_type="text/csv",
record_count=len(export_frame),
column_count=len(export_frame.columns),
)
except Exception:
log_exception(
logger,
"export_preparation_failed",
"CSV export preparation failed.",
export_name=export_name,
)
raise
# === Shared module: accessatlas/data.py ===
import logging
import pandas as pd
import streamlit as st
logger = get_logger(__name__)
@st.cache_data
def load_csv(filename, date_columns=None):
"""Load a CSV file from the data directory with optional date parsing."""
source_path = DATA_DIR / filename
try:
dataframe = pd.read_csv(
source_path,
parse_dates=date_columns or [],
)
except Exception:
log_exception(
logger,
"data_load_failed",
"Reference dataset could not be loaded.",
dataset=filename,
source_path=str(source_path),
)
raise
log_event(
logger,
logging.INFO,
"data_loaded",
"Reference dataset loaded.",
dataset=filename,
record_count=len(dataframe),
column_count=len(dataframe.columns),
)
return dataframe
@st.cache_data
def load_data():
"""Load all reference datasets used by the application."""
users = load_csv(
"users.csv",
[
"annual_training_date",
"biennial_training_date",
"access_agreement_date",
"created_date",
"updated_date",
],
)
systems = load_csv("systems.csv")
access_assignments = load_csv(
"access_assignments.csv",
["granted_date", "revoked_date"],
)
system_admin_assignments = load_csv(
"system_admin_assignments.csv",
["granted_date", "revoked_date"],
)
datasets = {
"users": users,
"systems": systems,
"access_assignments": access_assignments,
"system_admin_assignments": system_admin_assignments,
}
log_event(
logger,
logging.INFO,
"reference_data_ready",
"Reference datasets are ready for the application.",
dataset_counts={name: len(dataframe) for name, dataframe in datasets.items()},
)
return datasets
# === Shared module: accessatlas/navigation.py ===
def section_label(tab_name):
"""Return the display label for a top-level section."""
return TAB_DISPLAY_LABELS.get(tab_name, tab_name)
def section_name_from_label(display_label):
"""Return the internal section name for a top-level display label."""
reverse_labels = {
display_value: internal_name for internal_name, display_value in TAB_DISPLAY_LABELS.items()
}
return reverse_labels.get(display_label, display_label)
def get_visible_tabs(application_role):
"""Return the tab labels visible to the selected demo role."""
return ROLE_VISIBLE_TABS.get(application_role, ["Overview"])
def is_tab_visible(tab_name, visible_tabs):
"""Return whether a tab should be rendered for the selected demo role."""
return tab_name in visible_tabs
# === Shared module: accessatlas/presentation.py ===
import pandas as pd
import streamlit as st
def section_caption(text):
"""Render standard section-level instruction text."""
st.caption(text)
def filter_caption(text):
"""Render standard filter instruction text."""
st.caption(text)
def apply_multiselect_filter(dataframe, column_name, selected_values):
"""Filter a DataFrame by selected values from a multiselect widget."""
if not selected_values:
return dataframe
return dataframe[dataframe[column_name].isin(selected_values)]
def count_by(dataframe, columns, count_name="records"):
"""Return grouped counts for one or more columns."""
if isinstance(columns, str):
columns = [columns]
return dataframe.groupby(columns).size().reset_index(name=count_name)
def display_table(dataframe):
"""Return a copy of a dataframe with user-friendly column labels."""
return dataframe.rename(columns=COLUMN_LABELS)
def show_dataframe(dataframe, **kwargs):
"""Render a dataframe with user-friendly column labels and clean defaults."""
kwargs.setdefault("hide_index", True)
kwargs.setdefault("width", "stretch")
st.dataframe(
display_table(dataframe),
**kwargs,
)
def get_display_name(users, user_id):
"""Return a display name for a user ID when available."""
if pd.isna(user_id) or user_id == "":
return "Not assigned"
match = users[users["user_id"] == user_id]
if match.empty:
return "Not assigned"
return match.iloc[0]["display_name"]
def user_profile_markdown(selected_user, manager_name):
"""Build the selected user profile markdown block."""
return f"""
**User ID:** {selected_user["user_id"]}
**Email:** {selected_user["email"]}
**Department:** {selected_user["department"]}
**User Type:** {selected_user["user_type"]}
**Application Role:** {selected_user["application_role"]}