Spaces:
Sleeping
Sleeping
File size: 69,208 Bytes
64b6fa7 b03a18c 64b6fa7 b03a18c 64b6fa7 5f9023d b03a18c 5f9023d b03a18c 5f9023d b03a18c 5f9023d 64b6fa7 5f9023d b03a18c 64b6fa7 b03a18c 64b6fa7 5f9023d 64b6fa7 5f9023d 64b6fa7 b03a18c 5f9023d 64b6fa7 5f9023d b03a18c 5f9023d b03a18c 5f9023d b03a18c 5f9023d b03a18c e7e9868 d828bc9 b03a18c e7e9868 d828bc9 e7e9868 d828bc9 e7e9868 64b6fa7 5f9023d 64b6fa7 5f9023d 64b6fa7 b03a18c 64b6fa7 b03a18c 64b6fa7 b03a18c 64b6fa7 b03a18c 64b6fa7 b03a18c 64b6fa7 b03a18c 64b6fa7 b03a18c 64b6fa7 b03a18c 64b6fa7 5f9023d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 |
import streamlit as st
import json
import os
import yaml
from datetime import datetime, date, timedelta
import pandas as pd
from yaml.loader import SafeLoader
import streamlit_authenticator as stauth
from config_manager import ConfigManager
from dashboard import Dashboard
from tasks import TasksManager
from guests import GuestManager
from wedding_party import WeddingPartyManager
from vendors import VendorManager
# Page configuration
st.set_page_config(
page_title="Wedding Planner",
page_icon="π",
layout="wide",
initial_sidebar_state="expanded"
)
# Custom CSS for green/Adirondack theme
st.markdown("""
<style>
.main-header {
background: linear-gradient(90deg, #2d5016, #4a7c59);
color: white;
padding: 1rem;
border-radius: 10px;
text-align: center;
margin-bottom: 2rem;
}
.main-header h1, .main-header h2, .main-header h3, .main-header p {
color: white !important;
}
.main-header * {
color: white !important;
}
/* Ensure green background elements always have white text regardless of theme */
.main-header, .main-header * {
color: white !important;
}
.metric-card, .metric-card * {
color: white !important;
}
.metric-card {
background: linear-gradient(135deg, #4a7c59, #6b8e6b) !important;
color: white !important;
padding: 1rem;
border-radius: 10px;
text-align: center;
margin: 0.5rem;
height: 150px;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
.metric-card h1, .metric-card h2, .metric-card h3, .metric-card p {
color: white !important;
background: transparent !important;
}
.metric-card * {
color: white !important;
background: transparent !important;
}
/* Override Streamlit's default styling for elements inside metric cards */
.metric-card .stMarkdown {
background: transparent !important;
}
.metric-card .stMarkdown * {
color: white !important;
background: transparent !important;
}
/* Additional overrides for Streamlit elements */
div[data-testid="stMarkdownContainer"] {
background: transparent !important;
}
.metric-card div[data-testid="stMarkdownContainer"] {
background: transparent !important;
}
.metric-card div[data-testid="stMarkdownContainer"] * {
color: white !important;
background: transparent !important;
}
/* Fix text color for dashboard metrics below cards - use dark text for better visibility */
.main .block-container h1,
.main .block-container h2,
.main .block-container h3,
.main .block-container h4,
.main .block-container h5,
.main .block-container h6 {
color: #262730 !important;
}
.main .block-container p,
.main .block-container div,
.main .block-container span {
color: #262730 !important;
}
/* Specific styling for dashboard content */
.main .block-container .stMarkdown {
color: #262730 !important;
}
.main .block-container .stMarkdown * {
color: #262730 !important;
}
/* Override for dark mode */
@media (prefers-color-scheme: dark) {
.main .block-container h1,
.main .block-container h2,
.main .block-container h3,
.main .block-container h4,
.main .block-container h5,
.main .block-container h6 {
color: #fafafa !important;
}
.main .block-container p,
.main .block-container div,
.main .block-container span {
color: #fafafa !important;
}
.main .block-container .stMarkdown {
color: #fafafa !important;
}
.main .block-container .stMarkdown * {
color: #fafafa !important;
}
/* But keep green background elements white even in dark mode */
.main-header, .main-header * {
color: white !important;
}
.metric-card, .metric-card * {
color: white !important;
}
}
.sidebar .sidebar-content {
background: linear-gradient(180deg, #2d5016, #4a7c59);
}
.stButton > button {
background: linear-gradient(90deg, #4a7c59, #6b8e6b);
color: white;
border: none;
border-radius: 5px;
padding: 0.5rem 1rem;
}
.stButton > button:hover {
background: linear-gradient(90deg, #2d5016, #4a7c59);
color: white;
}
.task-card {
background: #f8f9fa;
border-left: 4px solid #4a7c59;
padding: 1rem;
margin: 0.5rem 0;
border-radius: 5px;
}
.guest-card {
background: #f8f9fa;
border: 1px solid #4a7c59;
padding: 1rem;
margin: 0.5rem 0;
border-radius: 5px;
}
</style>
""", unsafe_allow_html=True)
def load_auth_config():
"""Load authentication configuration from Google Drive"""
try:
config_manager = st.session_state.config_manager
# Try to load config.yaml from Google Drive root
if config_manager.google_drive_enabled:
config_content = config_manager.drive_manager.download_file('config.yaml')
if config_content:
# Parse YAML content
config = yaml.load(config_content, Loader=SafeLoader)
return config
# Fallback to local config.yaml if Google Drive fails
if os.path.exists('config.yaml'):
with open('config.yaml') as file:
config = yaml.load(file, Loader=SafeLoader)
return config
st.error("β No auth config found")
return None
except Exception as e:
st.error(f"Error loading authentication config: {e}")
return None
def get_user_folder_from_username(username):
"""Get the user folder based on username using wedding mappings"""
try:
# Load auth config to get wedding mappings
auth_config = st.session_state.get('auth_config')
if not auth_config:
# Fallback to loading config directly
auth_config = load_auth_config()
if auth_config and 'wedding_mappings' in auth_config:
wedding_mappings = auth_config['wedding_mappings']
# Search through all wedding mappings to find the user
for wedding_name, wedding_info in wedding_mappings.items():
if 'users' in wedding_info and username in wedding_info['users']:
return wedding_info['folder']
# Fallback to old hardcoded logic for backward compatibility
if username == 'demo':
return 'demo_data'
elif username == 'laraandumang':
return 'laraandumang'
else:
return 'demo_data' # Default fallback
except Exception as e:
st.error(f"Error getting user folder for {username}: {e}")
# Fallback to demo_data on error
return 'demo_data'
def get_wedding_info_for_user(username):
"""Get wedding information for a specific user"""
try:
auth_config = st.session_state.get('auth_config')
if not auth_config:
auth_config = load_auth_config()
if auth_config and 'wedding_mappings' in auth_config:
wedding_mappings = auth_config['wedding_mappings']
for wedding_name, wedding_info in wedding_mappings.items():
if 'users' in wedding_info and username in wedding_info['users']:
return {
'wedding_name': wedding_name,
'folder': wedding_info['folder'],
'users': wedding_info['users'],
'display_name': wedding_info.get('wedding_name', wedding_name)
}
return None
except Exception as e:
st.error(f"Error getting wedding info for {username}: {e}")
return None
def main():
# Initialize session state
if 'config_manager' not in st.session_state:
st.session_state.config_manager = ConfigManager()
# Load authentication configuration
if 'auth_config' not in st.session_state:
st.session_state.auth_config = load_auth_config()
if st.session_state.auth_config is None:
st.error("Failed to load authentication configuration. Please check your Google Drive setup.")
st.stop()
# Create authenticator (auto_hash=True by default, so passwords will be hashed automatically)
authenticator = stauth.Authenticate(
st.session_state.auth_config['credentials'],
st.session_state.auth_config['cookie']['name'],
st.session_state.auth_config['cookie']['key'],
st.session_state.auth_config['cookie']['expiry_days']
)
# Check authentication status
if 'authentication_status' not in st.session_state:
st.session_state.authentication_status = None
# Check if user is already authenticated
if st.session_state.get('authentication_status'):
# User is authenticated, show main app
show_main_app(authenticator)
else:
# Show login page and handle authentication
show_login_page(authenticator)
def show_login_page(authenticator):
"""Show the login page"""
# Hero Section
st.markdown("""
<div style="
background: linear-gradient(135deg, #2d5016, #4a7c59, #6b8e6b);
color: white;
padding: 4rem 2rem;
text-align: center;
border-radius: 15px;
margin-bottom: 3rem;
box-shadow: 0 10px 30px rgba(0,0,0,0.2);
">
<h1 style="font-size: 3.5rem; margin-bottom: 1rem; font-weight: 700;">π Wedding Planner</h1>
<h2 style="font-size: 1.8rem; margin-bottom: 2rem; font-weight: 300; opacity: 0.9;">
Your Complete Wedding Planning Solution
</h2>
<p style="font-size: 1.2rem; max-width: 600px; margin: 0 auto; line-height: 1.6;">
Organize your special day with our comprehensive wedding planning tool.
Manage guests, track tasks, coordinate vendors, and create unforgettable memories.
</p>
</div>
""", unsafe_allow_html=True)
# Features Section
st.markdown("## β¨ What You Can Do")
col1, col2, col3 = st.columns(3)
with col1:
st.markdown("""
<div style="
background: #f8f9fa;
padding: 2rem;
border-radius: 10px;
border-left: 4px solid #4a7c59;
margin-bottom: 2rem;
box-shadow: 0 4px 6px rgba(0,0,0,0.1);
">
<h3 style="color: #2d5016; margin-bottom: 1rem;">π₯ Guest Management</h3>
<ul style="color: #666; line-height: 1.8;">
<li>Organize guest lists by groups</li>
<li>Track RSVP responses</li>
<li>Manage meal preferences</li>
<li>Send invitations</li>
</ul>
</div>
""", unsafe_allow_html=True)
with col2:
st.markdown("""
<div style="
background: #f8f9fa;
padding: 2rem;
border-radius: 10px;
border-left: 4px solid #4a7c59;
margin-bottom: 2rem;
box-shadow: 0 4px 6px rgba(0,0,0,0.1);
">
<h3 style="color: #2d5016; margin-bottom: 1rem;">π Task Tracking</h3>
<ul style="color: #666; line-height: 1.8;">
<li>Create and assign tasks</li>
<li>Set deadlines and priorities</li>
<li>Track progress</li>
<li>Organize by categories</li>
</ul>
</div>
""", unsafe_allow_html=True)
with col3:
st.markdown("""
<div style="
background: #f8f9fa;
padding: 2rem;
border-radius: 10px;
border-left: 4px solid #4a7c59;
margin-bottom: 2rem;
box-shadow: 0 4px 6px rgba(0,0,0,0.1);
">
<h3 style="color: #2d5016; margin-bottom: 1rem;">π’ Vendor Management</h3>
<ul style="color: #666; line-height: 1.8;">
<li>Track vendor contacts</li>
<li>Manage payment schedules</li>
<li>Store contracts</li>
<li>Monitor bookings</li>
</ul>
</div>
""", unsafe_allow_html=True)
# Additional Features
col4, col5, col6 = st.columns(3)
with col4:
st.markdown("""
<div style="
background: #f8f9fa;
padding: 2rem;
border-radius: 10px;
border-left: 4px solid #4a7c59;
margin-bottom: 2rem;
box-shadow: 0 4px 6px rgba(0,0,0,0.1);
">
<h3 style="color: #2d5016; margin-bottom: 1rem;">π° Wedding Party</h3>
<ul style="color: #666; line-height: 1.8;">
<li>Manage bridal party</li>
<li>Track responsibilities</li>
<li>Coordinate schedules</li>
<li>Store contact info</li>
</ul>
</div>
""", unsafe_allow_html=True)
with col5:
st.markdown("""
<div style="
background: #f8f9fa;
padding: 2rem;
border-radius: 10px;
border-left: 4px solid #4a7c59;
margin-bottom: 2rem;
box-shadow: 0 4px 6px rgba(0,0,0,0.1);
">
<h3 style="color: #2d5016; margin-bottom: 1rem;">π Dashboard</h3>
<ul style="color: #666; line-height: 1.8;">
<li>Visual progress tracking</li>
<li>Key metrics overview</li>
<li>Timeline management</li>
<li>Quick insights</li>
</ul>
</div>
""", unsafe_allow_html=True)
with col6:
st.markdown("""
<div style="
background: #f8f9fa;
padding: 2rem;
border-radius: 10px;
border-left: 4px solid #4a7c59;
margin-bottom: 2rem;
box-shadow: 0 4px 6px rgba(0,0,0,0.1);
">
<h3 style="color: #2d5016; margin-bottom: 1rem;">βοΈ Cloud Sync</h3>
<ul style="color: #666; line-height: 1.8;">
<li>Google Drive integration</li>
<li>Automatic backups</li>
<li>Multi-device access</li>
<li>Real-time updates</li>
</ul>
</div>
""", unsafe_allow_html=True)
st.markdown("---")
# Login Section
st.markdown("## π Login to Your Wedding Planner")
# Login form
try:
authenticator.login(location='main')
except Exception as e:
st.error(f"Login error: {e}")
# Check authentication status and show appropriate message
if st.session_state.get('authentication_status') is False:
st.error("β Invalid username or password")
elif st.session_state.get('authentication_status') is None:
st.info("π Please enter your username and password")
elif st.session_state.get('authentication_status'):
st.success(f"β
Welcome, {st.session_state.get('name', 'User')}!")
st.rerun() # Refresh to show main app
def show_wedding_setup_form():
"""Show the wedding setup form for creating a new wedding"""
st.markdown("### π Create Your Wedding Configuration")
# Initialize session state for events and form data if not exists
if 'setup_events' not in st.session_state:
st.session_state.setup_events = []
if 'setup_form_data' not in st.session_state:
st.session_state.setup_form_data = {
'partner1_name': '',
'partner2_name': '',
'venue_city': '',
'wedding_start_date': date.today(),
'wedding_end_date': date.today(),
'custom_tags': '',
'task_assignees': ''
}
# Basic wedding information form
with st.form("wedding_setup"):
st.markdown("#### Basic Wedding Information")
col1, col2 = st.columns(2)
with col1:
partner1_name = st.text_input("Partner 1 Name", value=st.session_state.setup_form_data['partner1_name'], placeholder="Enter first partner's name")
partner2_name = st.text_input("Partner 2 Name", value=st.session_state.setup_form_data['partner2_name'], placeholder="Enter second partner's name")
venue_city = st.text_input("City", value=st.session_state.setup_form_data['venue_city'], placeholder="Enter city")
with col2:
st.markdown("**Wedding Date Range**")
wedding_start_date = st.date_input("Start Date", value=st.session_state.setup_form_data['wedding_start_date'])
wedding_end_date = st.date_input("End Date", value=st.session_state.setup_form_data['wedding_end_date'])
if wedding_end_date < wedding_start_date:
st.error("End date must be after start date")
wedding_end_date = wedding_start_date
st.markdown("#### Task Organization")
st.info("Tasks will be automatically grouped by your wedding events.")
st.markdown("#### Custom Tags")
st.markdown("Enter custom tags (one per line):")
custom_tags = st.text_area("Custom Tags", value=st.session_state.setup_form_data['custom_tags'], placeholder="e.g.,\nUrgent\nHigh Priority\nDeposit Required\nResearch Needed")
st.markdown("#### Task Assignees")
st.markdown("Enter people who will regularly be assigned tasks (one per line):")
task_assignees = st.text_area("Task Assignees", value=st.session_state.setup_form_data['task_assignees'], placeholder="e.g.,\nMom\nDad\nWedding Planner\nBest Friend\nCoordinator")
form_submitted = st.form_submit_button("Update Wedding Information")
if form_submitted:
# Update session state with form data
st.session_state.setup_form_data = {
'partner1_name': partner1_name,
'partner2_name': partner2_name,
'venue_city': venue_city,
'wedding_start_date': wedding_start_date,
'wedding_end_date': wedding_end_date,
'custom_tags': custom_tags,
'task_assignees': task_assignees
}
st.success("Wedding information updated!")
st.rerun()
# Event management section (outside form)
st.markdown("#### Wedding Events")
st.markdown("Define all your wedding events with their details:")
# Add/Remove event buttons
col1, col2 = st.columns(2)
with col1:
if st.button("β Add Event"):
# Set default date to wedding start date
wedding_start = st.session_state.setup_form_data['wedding_start_date']
st.session_state.setup_events.append({
"name": "New Event",
"description": "",
"date_offset": 0,
"requires_meal_choice": False,
"meal_options": [],
"location": "",
"address": ""
})
st.rerun()
with col2:
if len(st.session_state.setup_events) > 0 and st.button("β Remove Last Event"):
st.session_state.setup_events.pop()
st.rerun()
# Display events
if st.session_state.setup_events:
for i, event in enumerate(st.session_state.setup_events):
with st.expander(f"Event {i+1}: {event['name']}", expanded=True):
col1, col2 = st.columns(2)
with col1:
event_name = st.text_input("Event Name", value=event['name'], key=f"event_name_{i}")
event_description = st.text_input("Time", value=event['description'], placeholder="e.g., 2:00 PM, 6:30 PM", key=f"event_desc_{i}")
event_location = st.text_input("Location Name", value=event.get('location', ''), placeholder="e.g., Central Park, Grand Ballroom", key=f"event_location_{i}")
with col2:
# Get wedding date range
wedding_start = st.session_state.setup_form_data['wedding_start_date']
wedding_end = st.session_state.setup_form_data['wedding_end_date']
# Calculate current event date from date_offset
current_event_date = wedding_start + timedelta(days=event['date_offset'])
# Use date input without constraints - allow any date
event_date = st.date_input(
"Event Date",
value=current_event_date,
key=f"event_date_{i}",
help="Select any date for this event"
)
# Show warning if date is outside wedding range
if event_date < wedding_start or event_date > wedding_end:
st.warning(f"β οΈ Selected date is outside your wedding date range ({wedding_start.strftime('%B %d, %Y')} - {wedding_end.strftime('%B %d, %Y')})")
requires_meal_choice = st.checkbox("Requires Meal Choice", value=event['requires_meal_choice'], key=f"event_meal_{i}")
# Meal options section (only show if meal choice is required)
if requires_meal_choice:
st.markdown("**Meal Options**")
st.markdown("Enter meal options (one per line):")
current_meal_options = event.get('meal_options', [])
meal_options_text = '\n'.join(current_meal_options) if current_meal_options else ''
meal_options = st.text_area("Meal Options", value=meal_options_text, placeholder="e.g.,\nDuck\nSurf & Turf\nRisotto (vegetarian)\nStuffed Squash (vegetarian)", key=f"event_meal_options_{i}", height=100)
else:
meal_options = ""
event_address = st.text_area("Address", value=event.get('address', ''), placeholder="Enter full address (street, city, state, zip code)", key=f"event_address_{i}", height=80)
# Calculate date_offset from the selected date
date_offset = (event_date - wedding_start).days
# Parse meal options
meal_options_list = []
if requires_meal_choice and meal_options:
meal_options_list = [option.strip() for option in meal_options.split('\n') if option.strip()]
# Update session state
st.session_state.setup_events[i] = {
"name": event_name,
"description": event_description,
"date_offset": date_offset,
"requires_meal_choice": requires_meal_choice,
"meal_options": meal_options_list,
"location": event_location,
"address": event_address
}
else:
st.info("No events added yet. Click 'Add Event' to get started!")
# Save configuration button (after event management)
st.markdown("---")
if st.button("Save Configuration", type="primary"):
# Get form values from session state
form_data = st.session_state.setup_form_data
if form_data['partner1_name'] and form_data['partner2_name'] and form_data['wedding_start_date'] and form_data['wedding_end_date']:
# Parse tags (task groups will be auto-generated from events)
custom_tags_list = [tag.strip() for tag in form_data['custom_tags'].split('\n') if tag.strip()]
task_assignees_list = [assignee.strip() for assignee in form_data['task_assignees'].split('\n') if assignee.strip()]
# Create configuration
config = {
'wedding_info': {
'partner1_name': form_data['partner1_name'],
'partner2_name': form_data['partner2_name'],
'wedding_start_date': form_data['wedding_start_date'].isoformat(),
'wedding_end_date': form_data['wedding_end_date'].isoformat(),
'venue_city': form_data['venue_city']
},
'custom_settings': {
'custom_tags': custom_tags_list,
'task_assignees': task_assignees_list
},
'wedding_events': st.session_state.setup_events
}
# Save configuration
st.session_state.config_manager.save_config(config)
# Clear setup session state
if 'setup_events' in st.session_state:
del st.session_state.setup_events
if 'setup_form_data' in st.session_state:
del st.session_state.setup_form_data
if 'show_setup_form' in st.session_state:
del st.session_state.show_setup_form
st.success("Configuration saved successfully!")
st.rerun()
else:
st.error("Please fill in at least the partner names and wedding date range in the form above.")
def show_main_app(authenticator):
# Get current user from session state (set by authenticator.login)
username = st.session_state.get('username')
name = st.session_state.get('name')
if not username or not name:
st.error("Authentication error: Missing user information")
return
# Set user folder based on username
user_folder = get_user_folder_from_username(username)
# Get wedding info for the user (for future use)
wedding_info = get_wedding_info_for_user(username)
# Update config manager to use the correct user folder
config_manager = st.session_state.config_manager
config_manager.set_user_folder(user_folder)
# Check if we need to load data (either not initialized or user changed)
current_user_folder = config_manager.get_current_user_folder()
user_changed = st.session_state.get('last_user_folder') != user_folder
if not st.session_state.get('app_initialized', False) or user_changed:
with st.spinner(f"Loading {name}'s wedding data..."):
if user_folder == 'demo_data':
if config_manager.load_demo_data_from_drive():
st.session_state.app_initialized = True
st.session_state.last_user_folder = user_folder
st.success("β
Demo data loaded successfully!")
else:
st.error("Failed to load demo data.")
return
else:
if config_manager.load_existing_data_from_drive():
st.session_state.app_initialized = True
st.session_state.last_user_folder = user_folder
else:
st.error("Failed to load wedding data.")
return
# Load config
config = st.session_state.config_manager.load_config()
wedding_info = config.get('wedding_info', {})
# Check demo mode status
is_demo_mode = st.session_state.config_manager.is_demo_mode()
# Header
partner1 = wedding_info.get('partner1_name', 'Partner 1')
partner2 = wedding_info.get('partner2_name', 'Partner 2')
venue_city = wedding_info.get('venue_city', '')
wedding_start_str = wedding_info.get('wedding_start_date', '')
wedding_end_str = wedding_info.get('wedding_end_date', '')
# Build base header text with location
if venue_city:
header_text = f"{partner1} & {partner2}'s Wedding Planner - {venue_city} \n"
else:
header_text = f"{partner1} & {partner2}'s Wedding Planner \n"
# Add wedding mapping info if available
user_wedding_info = get_wedding_info_for_user(username)
# Add demo mode indicator
if is_demo_mode:
header_text += "π DEMO MODE - Sample Data"
if wedding_start_str and wedding_end_str:
try:
wedding_start = datetime.fromisoformat(wedding_start_str).date()
wedding_end = datetime.fromisoformat(wedding_end_str).date()
today = date.today()
if today < wedding_start:
days_until = (wedding_start - today).days
header_text += f"\n{days_until} days until wedding festivities begin!"
elif wedding_start <= today <= wedding_end:
header_text += " - Wedding festivities are happening now! π"
else:
days_since = (today - wedding_end).days
header_text += f" - {days_since} days since the wedding celebration ended!"
except:
pass # Keep the base header text if date parsing fails
st.markdown(f'<div class="main-header"><h1>{header_text}</h1></div>', unsafe_allow_html=True)
# Add Google Drive sync status and push button
show_google_drive_sync_status()
# Sidebar navigation
with st.sidebar:
# User info and logout
# Extract first name for a more friendly greeting
first_name = name.split()[0] if name else "User"
st.markdown(f"**Welcome, {first_name}!**")
if authenticator.logout(location='sidebar', key='logout_button'):
# Clear session state on logout
for key in list(st.session_state.keys()):
if key not in ['config_manager', 'auth_config']:
del st.session_state[key]
# Reset app initialization state
st.session_state.app_initialized = False
st.session_state.last_user_folder = None
# Reset config manager state
if 'config_manager' in st.session_state:
st.session_state.config_manager.reset_app_state()
st.session_state.config_manager.user_folder = None
st.rerun()
st.markdown("---")
st.markdown("### Navigation")
page = st.radio(
"Choose a page:",
["Dashboard", "Tasks", "Guest Management", "Wedding Party", "Wedding Overview", "Vendors & Purchases", "Settings"]
)
# Add Google Drive sync button in sidebar if enabled
config_manager = st.session_state.config_manager
drive_status = config_manager.get_google_drive_status()
if drive_status['enabled']:
st.markdown("---")
st.markdown("### βοΈ Google Drive")
modified_files = config_manager.get_modified_files()
# Always show push button
if modified_files:
st.warning(f"π {len(modified_files)} unsaved changes")
if st.button("π€ Push Changes", type="primary", help="Save changes to Google Drive", key="sidebar_push"):
with st.spinner("Pushing changes..."):
if config_manager.manual_sync_to_drive():
st.success("β
Changes saved!")
st.rerun()
else:
st.error("β Failed to save changes")
else:
st.success("β
All changes saved")
if st.button("π€ Push to Drive", help="Save current data to Google Drive", key="sidebar_push_all"):
with st.spinner("Pushing to Drive..."):
if config_manager.manual_sync_to_drive():
st.success("β
Data saved!")
st.rerun()
else:
st.error("β Failed to save")
# Always show pull button
if st.button("π Pull Latest", help="Get latest from Google Drive", key="sidebar_pull"):
with st.spinner("Pulling latest..."):
if config_manager.manual_sync_from_drive():
st.success("β
Latest loaded!")
st.rerun()
else:
st.error("β Failed to load changes")
# Route to appropriate page
if page == "Dashboard":
Dashboard().render(config)
elif page == "Tasks":
TasksManager().render(config)
elif page == "Guest Management":
GuestManager().render(config)
elif page == "Wedding Party":
WeddingPartyManager().render(config)
elif page == "Wedding Overview":
show_wedding_timeline_page(config)
elif page == "Vendors & Purchases":
VendorManager().render(config)
elif page == "Settings":
show_settings_page(config)
def show_wedding_timeline_page(config):
st.markdown("## π
Wedding Overview")
# Show wedding events directly without tabs
show_wedding_events_section(config)
def get_vendors_for_event(event_name, vendors_data):
"""Get vendors associated with a specific event, handling multiple categories per vendor"""
event_vendors = []
for vendor in vendors_data:
vendor_events = vendor.get('events', [])
if event_name in vendor_events:
# Get all categories for this vendor
categories = vendor.get('categories', [])
primary_category = vendor.get('category', '')
# If no categories array, use the primary category
if not categories and primary_category:
categories = [primary_category]
# If still no categories, use a default
if not categories:
categories = ['Vendor/Service']
# Create an entry for each category this vendor serves
for category in categories:
event_vendors.append({
'name': vendor.get('name', ''),
'category': category,
'status': vendor.get('status', ''),
'vendor_id': vendor.get('id', '') # Add ID to help identify duplicates
})
return event_vendors
def get_meal_choices_for_event(event_name, rsvp_data, meal_options):
"""Get meal choice counts for a specific event from RSVP data"""
meal_counts = {}
# Initialize counts for all meal options
for option in meal_options:
meal_counts[option] = 0
# Count meal choices from RSVP data
for group_code, group_data in rsvp_data.items():
event_responses = group_data.get('event_responses', {})
if event_name in event_responses:
event_data = event_responses[event_name]
meal_choices = event_data.get('meal_choice', {})
for attendee, choice in meal_choices.items():
if choice in meal_counts:
meal_counts[choice] += 1
return meal_counts
def show_wedding_events_section(config):
st.markdown("## π
Wedding Events")
wedding_events = config.get('wedding_events', [])
wedding_info = config.get('wedding_info', {})
if not wedding_events:
st.info("No events configured yet. Please complete the setup to define your wedding events.")
return
# Get wedding dates
wedding_start_str = wedding_info.get('wedding_start_date', '')
wedding_end_str = wedding_info.get('wedding_end_date', '')
if wedding_start_str and wedding_end_str:
try:
wedding_start = datetime.fromisoformat(wedding_start_str).date()
wedding_end = datetime.fromisoformat(wedding_end_str).date()
except:
st.error("Invalid wedding date format. Please check your settings.")
return
else:
st.warning("Wedding dates not set. Please complete the setup.")
return
# Load vendors and RSVP data
config_manager = ConfigManager()
vendors_data = config_manager.load_json_data('vendors.json')
rsvp_data = config_manager.load_json_data('rsvp_data.json')
# Display events
st.markdown(f"### Your Wedding Events ({len(wedding_events)} total)")
# Group events by day
events_by_day = {}
for event in wedding_events:
event_date = wedding_start + timedelta(days=event.get('date_offset', 0))
day_key = event_date.strftime('%Y-%m-%d')
if day_key not in events_by_day:
events_by_day[day_key] = []
events_by_day[day_key].append(event)
# Sort days
sorted_days = sorted(events_by_day.keys())
for day in sorted_days:
day_date = datetime.fromisoformat(day).date()
day_events = events_by_day[day]
# Determine day label
if day_date == wedding_start:
day_label = "Day 1 - Wedding Start"
elif day_date == wedding_end:
day_label = "Final Day - Wedding End"
else:
days_from_start = (day_date - wedding_start).days
day_label = f"Day {days_from_start + 1}"
st.markdown(f"#### {day_label} - {day_date.strftime('%B %d, %Y')}")
for event in day_events:
# Simple event display
time_info = event.get('description', '') or 'Time TBD'
location = event.get('location', '') or 'Location TBD'
address = event.get('address', '')
meal_required = event.get('requires_meal_choice', False)
event_name = event.get('name', 'Untitled Event')
st.markdown(f"**{event_name}**")
st.markdown(f"π **Time:** {time_info}")
st.markdown(f"π **Location:** {location}")
if address:
st.markdown(f"π **Address:** {address}")
st.markdown(f"π½οΈ **Meal Choice:** {'Required' if meal_required else 'Not Required'}")
# Display meal choices and counts if meal choice is required
if meal_required:
meal_options = event.get('meal_options', [])
if meal_options:
meal_counts = get_meal_choices_for_event(event_name, rsvp_data, meal_options)
st.markdown("π½οΈ **Meal Choices:**")
for option in meal_options:
count = meal_counts.get(option, 0)
st.markdown(f" β’ **{option}:** {count} orders")
else:
st.markdown("π½οΈ **Meal Choices:** No options configured")
# Display vendors for this event
event_vendors = get_vendors_for_event(event_name, vendors_data)
if event_vendors:
st.markdown("π’ **Vendors:**")
# Group vendors by name to handle multiple categories
vendors_by_name = {}
for vendor in event_vendors:
vendor_name = vendor['name']
if vendor_name not in vendors_by_name:
vendors_by_name[vendor_name] = {
'categories': [],
'status': vendor['status']
}
vendors_by_name[vendor_name]['categories'].append(vendor['category'])
# Display grouped vendors
for vendor_name, vendor_info in vendors_by_name.items():
status_emoji = "β
" if vendor_info['status'] == "Booked" else "β³" if vendor_info['status'] == "Researching" else "π"
categories_text = ", ".join(vendor_info['categories'])
st.markdown(f" β’ {status_emoji} **{categories_text}:** {vendor_name}")
else:
st.markdown("π’ **Vendors:** None assigned")
st.markdown("---")
# Event summary
st.markdown("### Event Summary")
col1, col2, col3 = st.columns(3)
with col1:
total_events = len(wedding_events)
st.metric("Total Events", total_events)
with col2:
meal_events = len([e for e in wedding_events if e.get('requires_meal_choice', False)])
st.metric("Events with Meals", meal_events)
with col3:
days_span = (wedding_end - wedding_start).days + 1
st.metric("Celebration Days", days_span)
def show_settings_page(config):
st.markdown("### Settings")
# Check demo mode status
is_demo_mode = st.session_state.config_manager.is_demo_mode()
# Demo mode toggle at the top
st.markdown("#### Demo Mode")
col1, col2 = st.columns([3, 1])
with col1:
if is_demo_mode:
st.info("π **Demo Mode is ON** - You are currently viewing sample data. This includes demo guests, vendors with complex payment schedules, tasks, and wedding party information.")
else:
st.info("π **Demo Mode is OFF** - You are viewing your actual wedding data.")
with col2:
if st.button("Toggle Demo Mode", type="secondary"):
if st.session_state.config_manager.toggle_demo_mode():
st.success("Demo mode toggled! Please refresh the page.")
st.rerun()
else:
st.error("Failed to toggle demo mode.")
# Create tabs for different settings
tab1, tab2, tab3, tab4, tab5, tab6 = st.tabs(["Edit Configuration", "Manage Events", "Google Drive", "Cache Management", "Current Configuration", "Reset"])
with tab1:
st.markdown("#### Edit Wedding Configuration")
# Initialize session state for editing if not exists
if 'edit_config' not in st.session_state:
st.session_state.edit_config = config.copy()
with st.form("edit_wedding_config"):
st.markdown("##### Basic Wedding Information")
col1, col2 = st.columns(2)
with col1:
partner1_name = st.text_input("Partner 1 Name", value=st.session_state.edit_config.get('wedding_info', {}).get('partner1_name', ''))
partner2_name = st.text_input("Partner 2 Name", value=st.session_state.edit_config.get('wedding_info', {}).get('partner2_name', ''))
venue_city = st.text_input("City", value=st.session_state.edit_config.get('wedding_info', {}).get('venue_city', ''))
with col2:
# Get current dates
wedding_start_str = st.session_state.edit_config.get('wedding_info', {}).get('wedding_start_date', '')
wedding_end_str = st.session_state.edit_config.get('wedding_info', {}).get('wedding_end_date', '')
try:
if wedding_start_str:
wedding_start = datetime.fromisoformat(wedding_start_str).date()
else:
wedding_start = date.today()
if wedding_end_str:
wedding_end = datetime.fromisoformat(wedding_end_str).date()
else:
wedding_end = date.today()
except:
wedding_start = date.today()
wedding_end = date.today()
wedding_start_date = st.date_input("Wedding Start Date", value=wedding_start)
wedding_end_date = st.date_input("Wedding End Date", value=wedding_end)
if wedding_end_date < wedding_start_date:
st.error("End date must be after start date")
wedding_end_date = wedding_start_date
st.markdown("##### Custom Tags")
current_tags = st.session_state.edit_config.get('custom_settings', {}).get('custom_tags', [])
custom_tags_text = '\n'.join(current_tags) if current_tags else ''
custom_tags = st.text_area("Custom Tags (one per line)", value=custom_tags_text, placeholder="e.g.,\nUrgent\nHigh Priority\nDeposit Required")
st.markdown("##### Task Assignees")
current_assignees = st.session_state.edit_config.get('custom_settings', {}).get('task_assignees', [])
task_assignees_text = '\n'.join(current_assignees) if current_assignees else ''
task_assignees = st.text_area("Task Assignees (one per line)", value=task_assignees_text, placeholder="e.g.,\nMom\nDad\nWedding Planner\nBest Friend\nCoordinator")
submitted = st.form_submit_button("Save Changes", type="primary")
if submitted:
# Update the configuration
updated_config = st.session_state.edit_config.copy()
updated_config['wedding_info'] = {
'partner1_name': partner1_name,
'partner2_name': partner2_name,
'venue_city': venue_city,
'wedding_start_date': wedding_start_date.isoformat(),
'wedding_end_date': wedding_end_date.isoformat()
}
# Parse custom tags and task assignees
custom_tags_list = [tag.strip() for tag in custom_tags.split('\n') if tag.strip()]
task_assignees_list = [assignee.strip() for assignee in task_assignees.split('\n') if assignee.strip()]
updated_config['custom_settings'] = {
'custom_tags': custom_tags_list,
'task_assignees': task_assignees_list
}
# Save the updated configuration
st.session_state.config_manager.save_config(updated_config)
st.success("Configuration updated successfully!")
st.rerun()
with tab2:
show_event_management_section(config)
with tab3:
show_google_drive_section()
with tab4:
show_cache_management_section()
with tab5:
st.markdown("#### Current Configuration")
st.json(config)
with tab6:
st.markdown("#### Reset Configuration")
st.warning("β οΈ This will permanently delete all your wedding configuration data. This action cannot be undone.")
if st.button("Reset Configuration", type="secondary"):
if st.session_state.config_manager.reset_config():
st.success("Configuration reset! Please refresh the page.")
st.rerun()
def show_cache_management_section():
"""Show cache management section in settings"""
st.markdown("#### Cache Management")
config_manager = st.session_state.config_manager
# Get cache status
cache_status = config_manager.get_cache_status()
st.markdown("**Current Cache Status:**")
col1, col2 = st.columns(2)
with col1:
st.metric("Total Cached Items", cache_status['total_cached'])
if cache_status['config_cached']:
st.success("β
Wedding configuration cached")
else:
st.info("βΉοΈ Wedding configuration not cached")
with col2:
if cache_status['cached_data_files']:
st.success(f"β
{len(cache_status['cached_data_files'])} data files cached")
with st.expander("View cached files"):
for filename in cache_status['cached_data_files']:
st.markdown(f"β’ {filename}")
else:
st.info("βΉοΈ No data files cached")
st.markdown("---")
# Cache management buttons
st.markdown("**Cache Actions:**")
col1, col2, col3 = st.columns(3)
with col1:
if st.button("ποΈ Clear All Cache", help="Clear all cached data to force reload from source"):
config_manager.clear_cache()
st.success("Cache cleared! Data will be reloaded from source on next access.")
st.rerun()
with col2:
if st.button("π Refresh Cache", help="Reload all data from Google Drive and update cache"):
if config_manager.google_drive_enabled:
with st.spinner("Refreshing cache from Google Drive..."):
if config_manager.manual_sync_from_drive():
st.success("Cache refreshed from Google Drive!")
st.rerun()
else:
st.error("Failed to refresh cache from Google Drive")
else:
st.warning("Google Drive not enabled. Cannot refresh from Drive.")
with col3:
if st.button("βΉοΈ Cache Info", help="Show detailed cache information"):
st.info("Cache helps improve performance by storing data in memory. Data is automatically cached when first loaded and updated when modified.")
def show_google_drive_status_setup():
"""Show Google Drive status on the setup page"""
config_manager = st.session_state.config_manager
drive_status = config_manager.get_google_drive_status()
# Create an expander for Google Drive status
with st.expander("π Google Drive Connection Status", expanded=False):
# Status display
if drive_status['enabled']:
if drive_status['status'] == 'Online':
st.success(f"β
{drive_status['message']}")
elif drive_status['status'] == 'Offline':
st.warning(f"β οΈ {drive_status['message']}")
else:
st.error(f"β {drive_status['message']}")
else:
st.info(f"βΉοΈ {drive_status['message']}")
# Show files if available
if drive_status['enabled'] and 'files' in drive_status:
st.markdown("**Files found in Google Drive:**")
for file_name in drive_status['files']:
friendly_name = get_friendly_file_name(file_name)
st.markdown(f"β’ {friendly_name}")
# Manual sync buttons (if enabled) - only show pull and load options
if drive_status['enabled']:
st.markdown("**Manual Sync:**")
col1, col2 = st.columns(2)
with col1:
if st.button("π₯ Sync from Google Drive", help="Download latest data from Google Drive", key="setup_sync_from"):
with st.spinner("Syncing from Google Drive..."):
if config_manager.manual_sync_from_drive():
st.success("Successfully synced from Google Drive!")
st.rerun()
else:
st.error("Failed to sync from Google Drive")
with col2:
if st.button("π Load Existing Data", help="Load existing wedding data from Google Drive", key="setup_load_existing"):
with st.spinner("Loading existing data from Google Drive..."):
if config_manager.load_existing_data_from_drive():
st.success("Successfully loaded existing data from Google Drive!")
st.info("Your wedding data has been loaded. The page will refresh to show your wedding planner.")
st.rerun()
else:
st.error("Failed to load existing data from Google Drive")
# Configuration help
if not drive_status['enabled']:
st.markdown("**To enable Google Drive integration:**")
st.markdown("Set the following **secrets** in your Hugging Face Space settings:")
st.code("""
GOOGLE_DRIVE_FOLDER_ID=your_folder_id
GOOGLE_PROJECT_ID=your_project_id
GOOGLE_PRIVATE_KEY_ID=your_private_key_id
GOOGLE_PRIVATE_KEY=your_private_key
GOOGLE_CLIENT_EMAIL=your_client_email
GOOGLE_CLIENT_ID=your_client_id
""")
# Debug information
st.markdown("**Debug Information:**")
folder_id = os.getenv('GOOGLE_DRIVE_FOLDER_ID')
if folder_id:
st.success(f"β
GOOGLE_DRIVE_FOLDER_ID found: {folder_id[:10]}...")
else:
st.error("β GOOGLE_DRIVE_FOLDER_ID not found")
# Check other variables
project_id = os.getenv('GOOGLE_PROJECT_ID')
client_email = os.getenv('GOOGLE_CLIENT_EMAIL')
private_key_id = os.getenv('GOOGLE_PRIVATE_KEY_ID')
private_key = os.getenv('GOOGLE_PRIVATE_KEY')
client_id = os.getenv('GOOGLE_CLIENT_ID')
if project_id:
st.success(f"β
GOOGLE_PROJECT_ID found: {project_id[:10]}...")
else:
st.error("β GOOGLE_PROJECT_ID not found")
if client_email:
st.success(f"β
GOOGLE_CLIENT_EMAIL found: {client_email}")
else:
st.error("β GOOGLE_CLIENT_EMAIL not found")
if private_key_id:
st.success(f"β
GOOGLE_PRIVATE_KEY_ID found: {private_key_id[:10]}...")
else:
st.error("β GOOGLE_PRIVATE_KEY_ID not found")
if private_key:
st.success(f"β
GOOGLE_PRIVATE_KEY found: {len(private_key)} characters")
else:
st.error("β GOOGLE_PRIVATE_KEY not found")
if client_id:
st.success(f"β
GOOGLE_CLIENT_ID found: {client_id[:10]}...")
else:
st.error("β GOOGLE_CLIENT_ID not found")
# Check if all required variables are present
all_required = all([folder_id, project_id, private_key_id, private_key, client_email, client_id])
if all_required:
st.success("π All required secrets are present!")
st.info("If Google Drive is still not working, there might be an authentication issue. Try restarting your Space.")
# Test file writing permissions
st.markdown("**Testing file permissions:**")
try:
test_file = "/tmp/test_write.txt"
with open(test_file, 'w') as f:
f.write("test")
st.success("β
Can write to /tmp directory")
os.remove(test_file)
except Exception as e:
st.error(f"β Cannot write to /tmp directory: {e}")
try:
test_dir = "wedding_data"
os.makedirs(test_dir, exist_ok=True)
test_file = os.path.join(test_dir, "test.txt")
with open(test_file, 'w') as f:
f.write("test")
st.success("β
Can write to wedding_data directory")
os.remove(test_file)
except Exception as e:
st.error(f"β Cannot write to wedding_data directory: {e}")
else:
st.warning("β οΈ Some required secrets are missing. Please add all secrets and restart your Space.")
def get_friendly_file_name(filename):
"""Convert technical file names to user-friendly names"""
friendly_names = {
'wedding_config.json': 'Wedding Configuration',
'guest_list_data.json': 'Guest List',
'rsvp_data.json': 'RSVP Responses',
'tasks.json': 'Tasks',
'vendors.json': 'Vendors',
'wedding_party.json': 'Wedding Party'
}
return friendly_names.get(filename, filename)
def show_google_drive_sync_status():
"""Show Google Drive sync status and push button prominently in main app"""
config_manager = st.session_state.config_manager
drive_status = config_manager.get_google_drive_status()
# Only show if Google Drive is enabled
if not drive_status['enabled']:
return
# Get modified files
modified_files = config_manager.get_modified_files()
# Create a prominent status bar with always-visible push button
col1, col2, col3 = st.columns([2, 1, 1])
with col1:
if modified_files:
friendly_names = [get_friendly_file_name(f) for f in modified_files]
st.warning(f"π **{len(modified_files)} unsaved changes** - {', '.join(friendly_names)}")
else:
st.success("β
**All changes saved** - Your data is up to date with Google Drive")
with col2:
# Always show push button - it will sync all current data
if modified_files:
button_text = f"π€ Push {len(modified_files)} Changes"
button_help = f"Save {len(modified_files)} modified files to Google Drive"
else:
button_text = "π€ Push to Drive"
button_help = "Save current data to Google Drive"
if st.button(button_text, type="primary", help=button_help):
with st.spinner("Pushing changes to Google Drive..."):
if config_manager.manual_sync_to_drive():
st.success("β
Changes saved to Google Drive!")
st.rerun()
else:
st.error("β Failed to save changes to Google Drive")
with col3:
if st.button("π Pull Latest", help="Get latest changes from Google Drive"):
with st.spinner("Pulling latest changes from Google Drive..."):
if config_manager.manual_sync_from_drive():
st.success("β
Latest changes loaded from Google Drive!")
st.rerun()
else:
st.error("β Failed to load changes from Google Drive")
# Add a small separator
st.markdown("---")
def show_google_drive_section():
st.markdown("#### Google Drive Integration")
config_manager = st.session_state.config_manager
drive_status = config_manager.get_google_drive_status()
# Status display
if drive_status['enabled']:
if drive_status['status'] == 'Online':
st.success(f"β
{drive_status['message']}")
elif drive_status['status'] == 'Offline':
st.warning(f"β οΈ {drive_status['message']}")
else:
st.error(f"β {drive_status['message']}")
else:
st.info(f"βΉοΈ {drive_status['message']}")
# Show files if available
if drive_status['enabled'] and 'files' in drive_status:
st.markdown("**Files in Google Drive:**")
for file_name in drive_status['files']:
friendly_name = get_friendly_file_name(file_name)
st.markdown(f"β’ {friendly_name}")
# Show modified files status
if drive_status['enabled']:
modified_files = config_manager.get_modified_files()
if modified_files:
st.markdown("#### π Modified Files (Not Synced)")
st.warning(f"The following files have been modified and need to be synced to Google Drive:")
for file_name in modified_files:
friendly_name = get_friendly_file_name(file_name)
st.markdown(f"β’ {friendly_name}")
else:
st.markdown("#### β
All Files Synced")
st.success("All your data is up to date with Google Drive.")
# Manual sync buttons
if drive_status['enabled']:
st.markdown("#### Manual Sync")
col1, col2 = st.columns(2)
with col1:
if st.button("π₯ Sync from Google Drive", help="Download latest data from Google Drive"):
with st.spinner("Syncing from Google Drive..."):
if config_manager.manual_sync_from_drive():
st.success("Successfully synced from Google Drive!")
st.rerun()
else:
st.error("Failed to sync from Google Drive")
with col2:
# Show different button text based on whether there are modified files
modified_files = config_manager.get_modified_files()
if modified_files:
button_text = f"π€ Sync {len(modified_files)} Modified Files to Drive"
button_help = f"Upload {len(modified_files)} modified files to Google Drive"
else:
button_text = "π€ Sync to Google Drive"
button_help = "Upload current data to Google Drive (no changes to sync)"
if st.button(button_text, help=button_help, disabled=not modified_files):
with st.spinner("Syncing to Google Drive..."):
if config_manager.manual_sync_to_drive():
st.success("Successfully synced to Google Drive!")
st.rerun()
else:
st.error("Failed to sync to Google Drive")
# Configuration info
st.markdown("#### Configuration")
st.markdown("To enable Google Drive integration, set the following environment variables:")
st.code("""
GOOGLE_DRIVE_FOLDER_ID=your_folder_id
GOOGLE_PROJECT_ID=your_project_id
GOOGLE_PRIVATE_KEY_ID=your_private_key_id
GOOGLE_PRIVATE_KEY=your_private_key
GOOGLE_CLIENT_EMAIL=your_client_email
GOOGLE_CLIENT_ID=your_client_id
""")
st.markdown("**Note:** Google Drive integration is automatically enabled when running on Hugging Face Spaces with proper credentials configured.")
def show_event_management_section(config):
st.markdown("#### Manage Wedding Events")
# Initialize session state for event editing if not exists
if 'edit_events' not in st.session_state:
st.session_state.edit_events = config.get('wedding_events', []).copy()
wedding_events = st.session_state.edit_events
wedding_info = config.get('wedding_info', {})
# Get wedding dates for date calculations
wedding_start_str = wedding_info.get('wedding_start_date', '')
wedding_end_str = wedding_info.get('wedding_end_date', '')
if not wedding_start_str or not wedding_end_str:
st.warning("Please set your wedding date range in the 'Edit Configuration' tab first.")
return
try:
wedding_start = datetime.fromisoformat(wedding_start_str).date()
wedding_end = datetime.fromisoformat(wedding_end_str).date()
except:
st.error("Invalid wedding date format. Please check your configuration.")
return
# Add event button
if st.button("β Add New Event"):
st.session_state.edit_events.append({
"name": "New Event",
"description": "",
"date_offset": 0,
"requires_meal_choice": False,
"meal_options": [],
"location": "",
"address": ""
})
st.rerun()
# Display events for editing
if st.session_state.edit_events:
st.markdown("##### Edit Events")
for i, event in enumerate(st.session_state.edit_events):
with st.expander(f"Event {i+1}: {event['name']}", expanded=True):
# Add delete button at the top right of each event
col_header1, col_header2 = st.columns([4, 1])
with col_header2:
if st.button("ποΈ Delete", key=f"delete_event_{i}", help="Delete this event"):
st.session_state.edit_events.pop(i)
st.rerun()
col1, col2 = st.columns(2)
with col1:
event_name = st.text_input("Event Name", value=event['name'], key=f"settings_event_name_{i}")
event_description = st.text_input("Time", value=event['description'], placeholder="e.g., 2:00 PM, 6:30 PM", key=f"settings_event_desc_{i}")
event_location = st.text_input("Location Name", value=event.get('location', ''), placeholder="e.g., Central Park, Grand Ballroom", key=f"settings_event_location_{i}")
with col2:
# Calculate current event date from date_offset
current_event_date = wedding_start + timedelta(days=event['date_offset'])
# Use date input without constraints - allow any date
event_date = st.date_input(
"Event Date",
value=current_event_date,
key=f"settings_event_date_{i}",
help="Select any date for this event"
)
# Show warning if date is outside wedding range
if event_date < wedding_start or event_date > wedding_end:
st.warning(f"β οΈ Selected date is outside your wedding date range ({wedding_start.strftime('%B %d, %Y')} - {wedding_end.strftime('%B %d, %Y')})")
requires_meal_choice = st.checkbox("Requires Meal Choice", value=event['requires_meal_choice'], key=f"settings_event_meal_{i}")
# Meal options section (only show if meal choice is required)
if requires_meal_choice:
st.markdown("**Meal Options**")
st.markdown("Enter meal options (one per line):")
current_meal_options = event.get('meal_options', [])
meal_options_text = '\n'.join(current_meal_options) if current_meal_options else ''
meal_options = st.text_area("Meal Options", value=meal_options_text, placeholder="e.g.,\nDuck\nSurf & Turf\nRisotto (vegetarian)\nStuffed Squash (vegetarian)", key=f"settings_event_meal_options_{i}", height=100)
else:
meal_options = ""
event_address = st.text_area("Address", value=event.get('address', ''), placeholder="Enter full address (street, city, state, zip code)", key=f"settings_event_address_{i}", height=80)
# Calculate date_offset from the selected date
date_offset = (event_date - wedding_start).days
# Parse meal options
meal_options_list = []
if requires_meal_choice and meal_options:
meal_options_list = [option.strip() for option in meal_options.split('\n') if option.strip()]
# Update session state
st.session_state.edit_events[i] = {
"name": event_name,
"description": event_description,
"date_offset": date_offset,
"requires_meal_choice": requires_meal_choice,
"meal_options": meal_options_list,
"location": event_location,
"address": event_address
}
# Save events button
st.markdown("---")
col1, col2, col3 = st.columns([1, 1, 1])
with col2:
if st.button("πΎ Save Event Changes", type="primary"):
# Update the configuration with edited events
updated_config = config.copy()
updated_config['wedding_events'] = st.session_state.edit_events
# Save the updated configuration
st.session_state.config_manager.save_config(updated_config)
st.success("Event changes saved successfully!")
st.rerun()
else:
st.info("No events added yet. Click 'Add New Event' to get started!")
# Event summary
if st.session_state.edit_events:
st.markdown("##### Event Summary")
col1, col2, col3 = st.columns(3)
with col1:
total_events = len(st.session_state.edit_events)
st.metric("Total Events", total_events)
with col2:
meal_events = len([e for e in st.session_state.edit_events if e.get('requires_meal_choice', False)])
st.metric("Events with Meals", meal_events)
with col3:
days_span = (wedding_end - wedding_start).days + 1
st.metric("Celebration Days", days_span)
if __name__ == "__main__":
main() |