-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp_workflows.py
More file actions
5453 lines (4778 loc) · 225 KB
/
app_workflows.py
File metadata and controls
5453 lines (4778 loc) · 225 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
import streamlit as st
import pandas as pd
import os
import pickle
from graphviz import Digraph
import xml.etree.ElementTree as ET
from xml.dom import minidom
import streamlit.components.v1 as components
import hashlib
from collections import defaultdict
import re
import json
import base64
# Global debug variable
DEBUG_OUTPUT_DATAFRAMES = False
def initialize_state():
# Create workflows directory if it doesn't exist
workflows_dir = os.path.join(st.session_state["cwd"], "data", "workflows")
os.makedirs(workflows_dir, exist_ok=True)
# Default user dictionary entry
default_user_dict = {
"3639e0c9-14a3-4021-9d95-c5ea60d296b6": "FFOG",
"43b07445-67a7-4c1b-9f51-f91da288add9": "FFOE",
"bdb15dcd-1c1c-4e7c-8ffa-4654c3c3f9f1": "FFMG",
"ad319f3a-c5f8-4f3c-a737-63eec86ddf12": "PEMG",
"b1ad934c-7efb-4b82-aa20-5bfc555cdad8": "PEOG",
"f931b8d3-0d53-48cf-823f-76585736d041": "SB",
"96a9a6a3-91e3-46f6-8da6-3d85173c2a98": "SGP",
"ca278b77-7de4-42f5-afa9-3d1e802dfa72": "SGÜP",
"fff9f05c-55c8-4778-ae13-e9782f684b86": "ZREG",
"402b1d27-2c02-41a5-bf37-77ba2a74ae1a": "ÜGFOA",
}
# Create legend dictionary
default_user_legend = {
"FFOE": "Federführende Organisationseinheit",
"FFMG": "Federführung mit Gruppenbeteiligung",
"FFOG": "Federführung ohne Gruppenbeteiligung",
"PEMG": "Prozesseigentümer mit Gruppe",
"PEOG": "Prozesseigentümer ohne Gruppe",
"SB": "Sicherheitsbeauftragter",
"SGP": "Stelle in der Gruppe des Prozesseigentümers",
"SGÜP": "Stelle in der übergeordneten Gruppe des Prozesseigentümers",
"ZREG": "Zuständige Registratur",
"ÜGFOA": "Übergeordnete Gruppe der federführenden Organisationseinheit des Aktivitätsobjekts",
}
default_standard_activities = ["DialogPortal", "Mdg", "Hintergrundaktivität"]
# Load existing dictionaries from the pickle file, if possible
pickle_path = os.path.join(workflows_dir, "user_dict.pickle")
loaded_dict = {}
loaded_legend = {}
loaded_template_dict = {}
loaded_standard_activities = None # None indicates not loaded yet
file_exists = os.path.exists(pickle_path)
if file_exists:
try:
with open(pickle_path, "rb") as f:
data = pickle.load(f)
loaded_dict = data.get("user_dict", {})
loaded_legend = data.get("user_legend", {})
loaded_template_dict = data.get("template_dict", {})
loaded_standard_activities = data.get("standard_activities", None)
except Exception as e:
st.error(f"Benutzerliste konnte nicht geladen werden: {str(e)}")
# Always update the dictionaries with the default entries
loaded_dict.update(default_user_dict)
loaded_legend.update(default_user_legend)
# For standard_activities, use loaded data if available, otherwise use defaults
if loaded_standard_activities is None:
loaded_standard_activities = default_standard_activities.copy()
st.session_state["user_dict"] = loaded_dict
st.session_state["user_legend"] = loaded_legend
st.session_state["template_dict"] = loaded_template_dict
st.session_state["standard_activities"] = loaded_standard_activities
# Save the updated dictionaries
with open(pickle_path, "wb") as f:
pickle.dump(
{
"user_dict": loaded_dict,
"user_legend": loaded_legend,
"template_dict": loaded_template_dict,
"standard_activities": loaded_standard_activities,
},
f,
)
def upload_user_list():
uploaded_files = st.file_uploader(
"Upload exported list for Benutzer / Gruppen / Stellen / Ausgangsvorlagen",
type=["xlsx"],
accept_multiple_files=True,
)
if uploaded_files:
try:
# Initialize dictionaries if they don't exist
if "user_dict" not in st.session_state:
st.session_state["user_dict"] = {}
if "user_legend" not in st.session_state:
st.session_state["user_legend"] = {}
if "template_dict" not in st.session_state:
st.session_state["template_dict"] = {}
# Track processed files to avoid duplicates
if "processed_files" not in st.session_state:
st.session_state["processed_files"] = set()
# Track template processing results
total_templates_added = 0
# Process each uploaded file
for uploaded_file in uploaded_files:
# Skip if we've already processed this file
file_hash = hashlib.md5(uploaded_file.getvalue()).hexdigest()
if file_hash in st.session_state["processed_files"]:
continue
st.session_state["processed_files"].add(file_hash)
# Check for template file and process it
templates_added = process_template_file(uploaded_file)
total_templates_added += templates_added
# If this was a template file, skip the user processing
if templates_added > 0:
continue
# Read the second sheet of the Excel file
df = pd.read_excel(uploaded_file, sheet_name=1, header=0)
# Get the actual column names
transport_id_col = get_column_name(df.columns, "TransportID")
vorname_col = get_column_name(df.columns, "Vorname")
nachname_col = get_column_name(df.columns, "Nachname")
name_de_col = get_column_name(df.columns, "Name:de")
name_abbreviation_col = get_column_name(
df.columns, "Erweiterte Einstellungen.Zeichen"
)
kurzbezeichnung_col = get_column_name(df.columns, "Kurzbezeichnung:de")
# Check if TransportID is found
if not transport_id_col:
st.error(
f"Could not find column starting with: TransportID in {uploaded_file.name}"
)
continue
# Determine how to create user names
use_names = vorname_col and nachname_col
use_kurzbezeichnung = kurzbezeichnung_col is not None
use_name_de = name_de_col is not None
if not (use_names or use_kurzbezeichnung or use_name_de):
st.error(
f"Could not find either (Vorname and Nachname), Kurzbezeichnung:de, or Name:de columns in {uploaded_file.name}"
)
continue
# Load existing dictionaries from session state
user_dict = st.session_state.get("user_dict", {}).copy()
user_legend = st.session_state.get("user_legend", {}).copy()
# Create reverse lookup for name combinations to abbreviations
name_to_abbr = {v: k for k, v in user_legend.items()}
# Add new entries to user_dict and user_legend
for _, row in df.iterrows():
transport_id = row[transport_id_col]
# Skip rows with missing TransportID
if pd.isna(transport_id):
continue
transport_id = str(transport_id)
# Skip if this TransportID already exists
if transport_id in user_dict:
continue
# Get the full name (for legend)
full_name = None
if (
use_names
and pd.notna(row[vorname_col])
and pd.notna(row[nachname_col])
):
full_name = f"{row[vorname_col]} {row[nachname_col]}"
elif use_kurzbezeichnung and pd.notna(row[kurzbezeichnung_col]):
full_name = row[kurzbezeichnung_col]
elif use_name_de and pd.notna(row[name_de_col]):
full_name = row[name_de_col]
# Skip if we can't determine a name
if not full_name:
continue
# Case 1: We have Vorname/Nachname (need abbreviation)
if (
use_names
and pd.notna(row[vorname_col])
and pd.notna(row[nachname_col])
):
# Check if we already have an abbreviation for this name
if full_name in name_to_abbr:
user_dict[transport_id] = name_to_abbr[full_name]
continue
# Get or generate the abbreviation
abbreviation = None
if name_abbreviation_col and pd.notna(
row.get(name_abbreviation_col)
):
abbreviation = str(row[name_abbreviation_col]).strip()
# Generate abbreviation if not provided or empty
if not abbreviation:
# First two letters of last name + first letter of first name
last_part = (
row[nachname_col][:2].upper()
if pd.notna(row[nachname_col])
else ""
)
first_part = (
row[vorname_col][:1].upper()
if pd.notna(row[vorname_col])
else ""
)
base_abbr = f"{last_part}{first_part}".lower()
# Handle duplicates
if base_abbr in user_legend:
counter = 1
while f"{base_abbr}{counter}" in user_legend:
counter += 1
abbreviation = f"{base_abbr}{counter}"
else:
abbreviation = base_abbr
# Update dictionaries
if abbreviation:
user_dict[transport_id] = abbreviation
user_legend[abbreviation] = full_name
name_to_abbr[full_name] = abbreviation
# Case 2: Use Kurzbezeichnung:de if available
elif use_kurzbezeichnung and pd.notna(row[kurzbezeichnung_col]):
user_dict[transport_id] = full_name
# Case 3: Fallback to Name:de (use directly without abbreviation)
elif use_name_de and pd.notna(row[name_de_col]):
user_dict[transport_id] = full_name
# Update session state with new entries
st.session_state["user_dict"].update(user_dict)
st.session_state["user_legend"].update(user_legend)
# Save to pickle file after processing all files
workflows_dir = os.path.join(st.session_state["cwd"], "data", "workflows")
pickle_path = os.path.join(workflows_dir, "user_dict.pickle")
with open(pickle_path, "wb") as f:
pickle.dump(
{
"user_dict": st.session_state["user_dict"],
"user_legend": st.session_state["user_legend"],
"template_dict": st.session_state.get("template_dict", {}),
},
f,
)
# Show success message for templates
if total_templates_added > 0:
st.success(
f"Successfully added {total_templates_added} template entries."
)
except Exception as e:
st.error(f"Error processing files: {str(e)}")
st.exception(e)
def modify_user_entries():
"""Handles displaying and editing user entries in the User Management section."""
st.subheader("Current Entries")
if st.session_state["user_dict"] or st.session_state["user_legend"]:
# Create a DataFrame for display
entries = []
for transport_id, abbr in st.session_state["user_dict"].items():
full_name = st.session_state["user_legend"].get(abbr, "")
entries.append(
{
"Transport ID": transport_id,
"Display Name": abbr,
"Full Name": full_name,
}
)
df = pd.DataFrame(entries)
st.dataframe(df)
# Allow editing
st.subheader("Edit Entries")
col1, col2, col3 = st.columns(3)
with col1:
selected_id = st.selectbox(
"Select ID to Edit",
options=list(st.session_state["user_dict"].keys()),
key="edit_id",
)
with col2:
new_abbr = st.text_input(
"New Display Name",
value=st.session_state["user_dict"].get(selected_id, ""),
key="edit_abbr",
)
with col3:
new_full_name = st.text_input(
"New Full Name (Optional, for Legend)",
value=st.session_state["user_legend"].get(
st.session_state["user_dict"].get(selected_id, ""), ""
),
key="edit_full_name",
)
if st.button("Save Changes"):
# Update session state
old_abbr = st.session_state["user_dict"][selected_id]
st.session_state["user_dict"][selected_id] = new_abbr
if old_abbr in st.session_state["user_legend"]:
del st.session_state["user_legend"][old_abbr]
if new_full_name:
st.session_state["user_legend"][new_abbr] = new_full_name
# Save to pickle
workflows_dir = os.path.join(st.session_state["cwd"], "data", "workflows")
pickle_path = os.path.join(workflows_dir, "user_dict.pickle")
with open(pickle_path, "wb") as f:
pickle.dump(
{
"user_dict": st.session_state["user_dict"],
"user_legend": st.session_state["user_legend"],
},
f,
)
st.success("Changes saved successfully!")
# Add new entries
st.subheader("Add New Entry")
new_id = st.text_input("Transport ID", key="new_id")
new_abbr = st.text_input("Display Name", key="new_abbr")
new_full_name = st.text_input("Full Name", key="new_full_name")
if st.button("Add Entry"):
if new_id and new_abbr:
st.session_state["user_dict"][new_id] = new_abbr
if new_full_name:
st.session_state["user_legend"][new_abbr] = new_full_name
# Save to pickle
workflows_dir = os.path.join(st.session_state["cwd"], "data", "workflows")
pickle_path = os.path.join(workflows_dir, "user_dict.pickle")
with open(pickle_path, "wb") as f:
pickle.dump(
{
"user_dict": st.session_state["user_dict"],
"user_legend": st.session_state["user_legend"],
"template_dict": st.session_state.get("template_dict", {}),
},
f,
)
st.success("New entry added successfully!")
else:
st.error("Transport ID and Display Name are required!")
if st.button("⚠️ Reset Benutzerliste", type="primary"):
# Reset session state
st.session_state["user_dict"] = {}
st.session_state["user_legend"] = {}
st.session_state["template_dict"] = {}
# Delete the pickle file if it exists
workflows_dir = os.path.join(st.session_state["cwd"], "data", "workflows")
pickle_path = os.path.join(workflows_dir, "user_dict.pickle")
try:
if os.path.exists(pickle_path):
os.remove(pickle_path)
st.success("User list and pickle file successfully reset")
else:
st.info("No pickle file found to delete")
except Exception as e:
st.error(f"Error deleting pickle file: {str(e)}")
else:
st.info("User list has been reset")
def upload_dossier():
uploaded_file = st.file_uploader("Excel File with Process Export", type=["xlsx"])
if uploaded_file is not None:
xls = pd.ExcelFile(uploaded_file)
st.session_state["dossier_filename"] = uploaded_file.name.split(".")[0]
return xls
# --- Helper Functions ---
def extract_id(parent_str):
"""
Extract the ID portion from a string by removing suffixes that start with ":" or "+".
Args:
parent_str: String potentially containing ID with suffixes
Returns:
Cleaned ID string or None if input is NaN
"""
if pd.isna(parent_str):
return None
# First, strip suffix that starts with ":"
result = parent_str.split(":", 1)[0]
# Then, strip suffix that starts with "+"
if "+" in result:
result = result.split("+", 1)[0]
return result.strip()
def get_column_name(columns, starts_with):
"""Helper function to find column that starts with given string"""
matching_cols = [col for col in columns if col.startswith(starts_with)]
if matching_cols:
# Strip any leading/trailing whitespace characters from the column names
return matching_cols[0].strip()
return None
def process_template_file(uploaded_file):
"""
Process template file containing Ausgangsvorlage sheet.
Returns number of templates processed, or 0 if no templates found.
"""
try:
# Check if the file has "Ausgangsvorlage" sheet
excel_file = pd.ExcelFile(uploaded_file)
if "Ausgangsvorlage" not in excel_file.sheet_names:
return 0
# Also check if required sheets exist
if "Dokumentvorlage" not in excel_file.sheet_names:
st.error(
f"Template file {uploaded_file.name} is missing 'Dokumentvorlage' sheet"
)
return 0
if "Vorlagenordner" not in excel_file.sheet_names:
st.error(
f"Template file {uploaded_file.name} is missing 'Vorlagenordner' sheet"
)
return 0
# Initialize template_dict if it doesn't exist
if "template_dict" not in st.session_state:
st.session_state["template_dict"] = {}
template_dict = st.session_state.get("template_dict", {}).copy()
# Read the Dokumentvorlage sheet
dokument_df = pd.read_excel(
uploaded_file, sheet_name="Dokumentvorlage", header=0
)
# Get column names using helper function - need to be more specific for complex column names
transport_id_col = get_column_name(dokument_df.columns, "TransportID")
# Look for the specific "Name" column (not "Name des neuen Objekts")
name_col = None
for col in dokument_df.columns:
if col.startswith("Name\n") and "Rubicon.Dms.DocumentMixin.Name" in col:
name_col = col
break
# Look for the specific "Vorlage" column (not "Vorlage für Expertensuche")
vorlage_col = None
for col in dokument_df.columns:
if col.startswith("Vorlage\n") and "MailItemClassName" in col:
vorlage_col = col
break
ordner_col = get_column_name(dokument_df.columns, "Ordner")
# Check if required columns are found
if not all([transport_id_col, name_col, vorlage_col, ordner_col]):
missing_cols = []
if not transport_id_col:
missing_cols.append("TransportID")
if not name_col:
missing_cols.append("Name")
if not vorlage_col:
missing_cols.append("Vorlage")
if not ordner_col:
missing_cols.append("Ordner")
st.error(
f"Could not find required columns in Dokumentvorlage sheet: {', '.join(missing_cols)}"
)
return 0
# Read the Vorlagenordner sheet
try:
ordner_df = pd.read_excel(
uploaded_file, sheet_name="Vorlagenordner", header=0
)
ordner_transport_id_col = get_column_name(ordner_df.columns, "TransportID")
ordner_bezeichnung_col = get_column_name(ordner_df.columns, "Bezeichnung")
if not all([ordner_transport_id_col, ordner_bezeichnung_col]):
missing_cols = []
if not ordner_transport_id_col:
missing_cols.append("TransportID")
if not ordner_bezeichnung_col:
missing_cols.append("Bezeichnung")
st.error(
f"Could not find required columns in Vorlagenordner sheet: {', '.join(missing_cols)}"
)
return 0
# Create lookup dictionary for Vorlagenordner
ordner_lookup = {}
for _, row in ordner_df.iterrows():
ordner_transport_id = row[ordner_transport_id_col]
if pd.notna(ordner_transport_id):
ordner_transport_id = str(ordner_transport_id)
bezeichnung = (
row[ordner_bezeichnung_col]
if pd.notna(row[ordner_bezeichnung_col])
else ""
)
ordner_lookup[ordner_transport_id] = bezeichnung
except Exception as e:
st.error(f"Error reading Vorlagenordner sheet: {str(e)}")
return 0
# Process each row in Dokumentvorlage
templates_added = 0
skipped_rows = 0
for idx, row in dokument_df.iterrows():
transport_id = row[transport_id_col]
# Skip rows with missing TransportID
if pd.isna(transport_id):
skipped_rows += 1
continue
transport_id = str(transport_id)
# Get values for constructing the template description
name_value = row[name_col] if name_col and pd.notna(row[name_col]) else ""
vorlage_value = (
row[vorlage_col] if vorlage_col and pd.notna(row[vorlage_col]) else ""
)
ordner_value = row[ordner_col] if pd.notna(row[ordner_col]) else ""
# For templates, we need at least the Name field. Vorlage can be empty.
if not name_value:
skipped_rows += 1
continue
# Construct the base description: Name, Vorlage, Bezeichnung (comma-separated)
template_description = name_value
if vorlage_value:
template_description += f", {vorlage_value}"
# Look up the Ordner information if available
if ordner_value:
# Extract ID using the extract_id helper function
ordner_id = extract_id(ordner_value)
if ordner_id and ordner_id in ordner_lookup:
bezeichnung = ordner_lookup[ordner_id]
if bezeichnung:
template_description += f", {bezeichnung}"
# Add to template dictionary (overwrite existing entries)
template_dict[transport_id] = template_description
templates_added += 1
# Now process the Ausgangsvorlage sheet with the same logic
ausgangs_df = pd.read_excel(
uploaded_file, sheet_name="Ausgangsvorlage", header=0
)
# Get column names using the same logic as Dokumentvorlage
ausgangs_transport_id_col = get_column_name(ausgangs_df.columns, "TransportID")
# Look for the specific "Name" column (not "Name des neuen Objekts")
ausgangs_name_col = None
for col in ausgangs_df.columns:
if col.startswith("Name\n") and "Rubicon.Dms.DocumentMixin.Name" in col:
ausgangs_name_col = col
break
# Look for the specific "Vorlage" column (not "Vorlage für Expertensuche")
ausgangs_vorlage_col = None
for col in ausgangs_df.columns:
if col.startswith("Vorlage\n") and "MailItemClassName" in col:
ausgangs_vorlage_col = col
break
ausgangs_ordner_col = get_column_name(ausgangs_df.columns, "Ordner")
# Check if required columns are found
if not all([ausgangs_transport_id_col, ausgangs_name_col, ausgangs_ordner_col]):
missing_cols = []
if not ausgangs_transport_id_col:
missing_cols.append("TransportID")
if not ausgangs_name_col:
missing_cols.append("Name")
if not ausgangs_ordner_col:
missing_cols.append("Ordner")
st.error(
f"Could not find required columns in Ausgangsvorlage sheet: {', '.join(missing_cols)}"
)
else:
# Process each row in Ausgangsvorlage
ausgangs_skipped_rows = 0
for idx, row in ausgangs_df.iterrows():
ausgangs_transport_id = row[ausgangs_transport_id_col]
# Skip rows with missing TransportID
if pd.isna(ausgangs_transport_id):
ausgangs_skipped_rows += 1
continue
ausgangs_transport_id = str(ausgangs_transport_id)
# Get values for constructing the template description
ausgangs_name_value = (
row[ausgangs_name_col]
if ausgangs_name_col and pd.notna(row[ausgangs_name_col])
else ""
)
ausgangs_vorlage_value = (
row[ausgangs_vorlage_col]
if ausgangs_vorlage_col and pd.notna(row[ausgangs_vorlage_col])
else ""
)
ausgangs_ordner_value = (
row[ausgangs_ordner_col]
if pd.notna(row[ausgangs_ordner_col])
else ""
)
# For templates, we need at least the Name field. Vorlage can be empty.
if not ausgangs_name_value:
ausgangs_skipped_rows += 1
continue
# Construct the base description: Name, Vorlage, Bezeichnung (comma-separated)
ausgangs_template_description = ausgangs_name_value
if ausgangs_vorlage_value:
ausgangs_template_description += f", {ausgangs_vorlage_value}"
# Look up the Ordner information if available
if ausgangs_ordner_value:
# Extract ID using the extract_id helper function
ausgangs_ordner_id = extract_id(ausgangs_ordner_value)
if ausgangs_ordner_id and ausgangs_ordner_id in ordner_lookup:
bezeichnung = ordner_lookup[ausgangs_ordner_id]
if bezeichnung:
ausgangs_template_description += f", {bezeichnung}"
# Add to template dictionary (overwrite existing entries)
template_dict[ausgangs_transport_id] = ausgangs_template_description
templates_added += 1
# Update session state
st.session_state["template_dict"] = template_dict
return templates_added
except Exception as e:
st.error(f"Error processing template file {uploaded_file.name}: {str(e)}")
return 0
def resolve_empfaenger(xls, empfaenger_id):
"""
Resolves an Empfänger ID to its actual value by looking it up in the "Empfänger" sheet.
Args:
xls: Excel file containing the "Empfänger" sheet
empfaenger_id: The TransportID to look up
Returns:
Resolved empfänger value or the original ID if not found
"""
if pd.isna(empfaenger_id):
return None
# Check if the "Empfänger" sheet exists
if "Empfänger" not in xls.sheet_names:
# Skip to final lookup in user_dict
resolved_id = empfaenger_id
else:
# Read the Empfänger sheet
empfaenger_df = pd.read_excel(xls, sheet_name="Empfänger")
# Get the TransportID column
transport_id_col = get_column_name(empfaenger_df.columns, "TransportID")
if transport_id_col is None:
# Skip to final lookup in user_dict
resolved_id = empfaenger_id
else:
# Look for the row with matching TransportID
matching_rows = empfaenger_df[
empfaenger_df[transport_id_col] == empfaenger_id
]
if matching_rows.empty:
# Skip to final lookup in user_dict
resolved_id = empfaenger_id
else:
# Potential recipient columns to check
recipient_cols = [
"Benutzer",
"Stelle",
"Gruppe",
"Verteiler",
"DynamicRecipientIdentifier",
]
# Track if we found a value
found_value = False
# Look through all columns to find a non-empty value
for col_pattern in recipient_cols:
col_name = get_column_name(empfaenger_df.columns, col_pattern)
if col_name is not None:
value = matching_rows[col_name].iloc[0]
if pd.notna(value):
# Clean the value by applying extract_id
resolved_id = extract_id(value)
found_value = True
break
# If no value found in specified columns, check all columns
if not found_value:
for col in empfaenger_df.columns:
if col != transport_id_col: # Skip the TransportID column
value = matching_rows[col].iloc[0]
if pd.notna(value):
# Clean the value by applying extract_id
resolved_id = extract_id(value)
found_value = True
break
# If no matching non-empty value found, use the original ID
if not found_value:
resolved_id = empfaenger_id
# FINAL STEP: Check if the ID exists in the user dictionary
if "user_dict" in st.session_state and resolved_id in st.session_state["user_dict"]:
return st.session_state["user_dict"][resolved_id]
# If we get here, return the resolved_id (which might be the original ID if no match was found)
return resolved_id
# --- Generating Workflow Tables ---
def process_befehl_with_templates(befehl_value, parameter_value):
"""
Process befehl and parameter values, replacing template IDs with template names
when CreateSettlement or CreateDocument commands are detected.
Args:
befehl_value: Value from the Befehl column
parameter_value: Value from the Parameter column
Returns:
str or None: Processed befehl string with template names, or None if invalid
"""
# Check if befehl_value is valid
if pd.isna(befehl_value):
return None
befehl_str = str(befehl_value)
# If parameter is missing, just return the befehl value
if pd.isna(parameter_value):
return befehl_str
parameter_str = str(parameter_value)
# Check if befehl contains CreateSettlement or CreateDocument
if "CreateSettlement" in befehl_str or "CreateDocument" in befehl_str:
# Look for UIDs in the parameter string using regex
# UUID pattern: 8-4-4-4-12 hexadecimal characters separated by hyphens
uid_pattern = r"[A-Fa-f0-9]{8}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{12}"
def replace_uid(match):
uid = match.group(0)
template_dict = st.session_state.get("template_dict", {})
if uid in template_dict:
# Return the UID followed by comma, template name, and newline
return f"{uid}, {template_dict[uid]}\n"
else:
# Show warning for unknown template
st.warning(f"Unknown Dokumentvorlage: {uid}")
return uid
# Replace all UIDs in the parameter string
processed_parameter = re.sub(uid_pattern, replace_uid, parameter_str)
# Format the final befehl string
return f"{befehl_str}:\n{processed_parameter}"
else:
# Standard formatting for non-template commands
return f"{befehl_str}:\n{parameter_str}"
def build_activities_table(xls):
"""
Builds an activities table from an Excel file by combining data from specified sheets.
Returns:
- pd.DataFrame: A DataFrame containing the activities table.
"""
# Step 2: Define the common columns and activity types
common_column_patterns = [
"TransportID",
"Name:de",
"ParentActivity",
"SequenceNumber",
]
activity_types = {"Aktivität": "manual", "Befehlsaktivität": "system"}
# Step 3: Identify sheets based on standard_activities
standard_activities_sheets = [
sheet
for sheet in xls.sheet_names
if any(
sheet.startswith(activity)
for activity in st.session_state["standard_activities"]
)
]
# Step 4: Initialize a list to collect DataFrames from each sheet
activities_list = []
# Step 5: Process each relevant sheet
for sheet_name in xls.sheet_names:
# Check if the sheet is relevant
if sheet_name in activity_types or sheet_name in standard_activities_sheets:
# Read the sheet data
df = pd.read_excel(xls, sheet_name=sheet_name)
# Determine the activity type
activity_type = activity_types.get(
sheet_name, "script"
) # "script" for standard activity sheets
# Map column patterns to actual column names in the dataframe
column_mapping = {
pattern: get_column_name(df.columns, pattern)
for pattern in common_column_patterns
}
# Verify that all common columns exist in the sheet
missing_cols = [
pattern for pattern, col in column_mapping.items() if col is None
]
if missing_cols:
print(
f"Warning: Sheet '{sheet_name}' is missing columns: {missing_cols}"
)
continue # Skip this sheet if critical columns are missing
# Extract common columns
temp_df = df[
[column_mapping[pattern] for pattern in common_column_patterns]
].copy()
# Rename columns to standard names
temp_df.columns = ["TransportID", "name", "parent", "SequenceNumber"]
# Clean the parent column by applying extract_id to remove suffixes
temp_df["parent"] = temp_df["parent"].apply(extract_id)
# Add the activity type
temp_df["type"] = activity_type
# Add "Empfänger" for manual activities; set to None for others
empfaenger_col = get_column_name(df.columns, "Empfänger")
if sheet_name == "Aktivität" and empfaenger_col is not None:
# Get the raw Empfänger IDs
raw_empfaenger = df[empfaenger_col].apply(extract_id)
# Resolve each Empfänger ID to its actual value
temp_df["Empfänger"] = raw_empfaenger.apply(
lambda x: resolve_empfaenger(xls, x)
)
else:
temp_df["Empfänger"] = None
# Add "label" and "befehl" for Befehlsaktivität; set to None for others
if sheet_name == "Befehlsaktivität":
befehl_col = get_column_name(df.columns, "Befehl")
parameter_col = get_column_name(df.columns, "Parameter")
if befehl_col is not None:
# Raw Befehl value goes to label column
temp_df["label"] = df[befehl_col]
else:
temp_df["label"] = None
if parameter_col is not None:
# Process parameter column for template replacement and put in befehl column
def process_parameter_only(row):
if pd.isna(row[parameter_col]):
return None
parameter_str = str(row[parameter_col])
befehl_value = row[befehl_col] if befehl_col is not None else ""
# Check if befehl contains CreateSettlement or CreateDocument for template processing
if befehl_col is not None and not pd.isna(befehl_value):
befehl_str = str(befehl_value)
if (
"CreateSettlement" in befehl_str
or "CreateDocument" in befehl_str
):
# Look for UIDs in the parameter string using regex
uid_pattern = r"[A-Fa-f0-9]{8}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{12}"
def replace_uid(match):
uid = match.group(0)
template_dict = st.session_state.get(
"template_dict", {}
)
if uid in template_dict:
return f"{uid}, {template_dict[uid]}\n"
else:
st.warning(f"Unknown Dokumentvorlage: {uid}")
return uid
# Replace all UIDs in the parameter string
return re.sub(uid_pattern, replace_uid, parameter_str)
# Return parameter as-is for non-template commands
return parameter_str
temp_df["befehl"] = df.apply(process_parameter_only, axis=1)
else:
temp_df["befehl"] = None
else:
temp_df["label"] = None
temp_df["befehl"] = None
# Append to the list
activities_list.append(temp_df)
# Step 6: Combine all DataFrames into one
if not activities_list:
raise ValueError("No valid activity data found in the Excel file.")
activities_df = pd.concat(activities_list, ignore_index=True)
# Step 7: Check for duplicate TransportIDs
if activities_df["TransportID"].duplicated().any():
print("Warning: Duplicate TransportIDs found in the activities table.")
else:
# print("All TransportIDs are unique.")
pass
# Step 7.5: Add substeps from "Manueller Arbeitsschritt" sheet
activities_df["substeps"] = None # Initialize the substeps column as None
# Check if the "Manueller Arbeitsschritt" sheet exists
if "Manueller Arbeitsschritt" in xls.sheet_names:
# Read the sheet
manual_steps_df = pd.read_excel(xls, sheet_name="Manueller Arbeitsschritt")
# Get the column names using get_column_name
activity_col = get_column_name(manual_steps_df.columns, "Activity")
name_col = get_column_name(manual_steps_df.columns, "Name")
# Check if both required columns exist
if activity_col is not None and name_col is not None:
# Clean the Activity column by applying extract_id to remove suffixes