File size: 45,876 Bytes
f3a8d03 7f0238b f3a8d03 7f0238b f3a8d03 7f0238b f3a8d03 7f0238b f3a8d03 7f0238b f3a8d03 7f0238b f3a8d03 7f0238b f3a8d03 7f0238b f3a8d03 7f0238b f3a8d03 7f0238b f3a8d03 7f0238b f3a8d03 7f0238b f3a8d03 7f0238b f3a8d03 7f0238b f3a8d03 7f0238b f3a8d03 7f0238b f3a8d03 7f0238b f3a8d03 7f0238b f3a8d03 7f0238b f3a8d03 7f0238b f3a8d03 7f0238b f3a8d03 | 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 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Enterprise Roster Generator ‚Final Adaptive Version
All constraints adapt dynamically based on team size to ensure feasibility.
"""
import itertools
import json
import os
import pickle
import tempfile
import threading
import time as pytime
from datetime import datetime, timedelta
from datetime import time as dt_time
from pathlib import Path
import pandas as pd
import schedule
import streamlit as st
# ------------------------------
# OR-Tools Weekly Optimiser
# ------------------------------
from ortools.sat.python import cp_model
def get_weekly_requirements(n_staff: int) -> tuple:
"""
Returns coverage requirements based on available staff count.
For n_staff == 5: reduces ONE weekday day shift to 2.
"""
if n_staff >= 6:
return (3, 1, 1, 1, [])
elif n_staff == 5:
# Reduce one weekday (Wednesday) to 2 day staff
return (3, 1, 1, 1, [2]) # Wednesday = index 2 (Mon=0)
else:
raise ValueError("At least 5 staff required.")
# def solve_week(
# week_idx: int,
# start_date: datetime.date,
# available_staff: list[str],
# cumulative_shifts: dict[str, int],
# all_staff_global: list[str],
# ) -> tuple[dict, dict]:
N_AVAIL = len(available_staff)
if N_AVAIL < 5:
raise ValueError("Minimum 5 staff per week.")
# Get coverage rules
wd_day, wd_night, we_day, we_night, reduced_days = get_weekly_requirements(N_AVAIL)
# Determine constraint strictness based on staff count
FULL_NO_CONSECUTIVE = N_AVAIL >= 8 # Only enforce full restriction with 8+ staff
FULL_48H_REST = N_AVAIL >= 8 # Only enforce full 48h rest with 8+ staff
full_names = available_staff + [f"Vacant_{i}" for i in range(9 - N_AVAIL)]
SHIFT = {"day": 0, "night": 1}
DAYS = 7
WEEKDAY_REL = {0, 1, 2, 3, 4}
model = cp_model.CpModel()
x = {}
for p, d, s in itertools.product(range(9), range(DAYS), range(2)):
x[p, d, s] = model.NewBoolVar(f"x_{p}_{d}_{s}")
# === Dynamic Coverage ===
for d in range(DAYS):
if d in WEEKDAY_REL:
day_req = wd_day
if d in reduced_days: # e.g., Wednesday
day_req = 2
night_req = wd_night
else:
day_req = we_day
night_req = we_night
model.Add(sum(x[p, d, SHIFT["day"]] for p in range(9)) == day_req)
model.Add(sum(x[p, d, SHIFT["night"]] for p in range(9)) == night_req)
# === No same-day double shift (always enforced) ===
for p, d in itertools.product(range(9), range(DAYS)):
model.Add(x[p, d, SHIFT["day"]] + x[p, d, SHIFT["night"]] <= 1)
# === No consecutive days (adaptive) ===
for p in range(9):
for d in range(DAYS - 1):
if FULL_NO_CONSECUTIVE:
# Full restriction: no shifts on consecutive days
model.Add(
x[p, d, SHIFT["day"]]
+ x[p, d, SHIFT["night"]]
+ x[p, d + 1, SHIFT["day"]]
+ x[p, d + 1, SHIFT["night"]]
<= 1
)
else:
# Relaxed: only prevent consecutive NIGHT shifts
model.Add(x[p, d, SHIFT["night"]] + x[p, d + 1, SHIFT["night"]] <= 1)
# === Weekend cap (always enforced) ===
for p in range(9):
model.Add(sum(x[p, d, s] for d in (5, 6) for s in range(2)) <= 1)
# === 48h rest after night shift (adaptive) ===
for p in range(9):
for d in range(DAYS):
night_d = x[p, d, SHIFT["night"]]
# Always enforce 24h rest (no shift next day after night)
if d + 1 < DAYS:
any_d1 = x[p, d + 1, SHIFT["day"]] + x[p, d + 1, SHIFT["night"]]
model.Add(any_d1 <= 1 - night_d)
# Only enforce second day off with larger teams
if FULL_48H_REST and d + 2 < DAYS:
any_d2 = x[p, d + 2, SHIFT["day"]] + x[p, d + 2, SHIFT["night"]]
model.Add(any_d2 <= 1 - night_d)
# === Vacants forced to 0 ===
for p in range(N_AVAIL, 9):
for d, s in itertools.product(range(DAYS), range(2)):
model.Add(x[p, d, s] == 0)
# === Weekly shift bounds (adaptive) ===
if N_AVAIL <= 6:
MIN_WEEKLY, MAX_WEEKLY = 3, 4 # Smaller teams work more shifts
elif N_AVAIL == 7:
MIN_WEEKLY, MAX_WEEKLY = 2, 4
else: # 8-9 staff
MIN_WEEKLY, MAX_WEEKLY = 2, 3
week_shifts = {}
for i, name in enumerate(available_staff):
var = model.NewIntVar(MIN_WEEKLY, MAX_WEEKLY, f"wshift_{i}")
model.Add(var == sum(x[i, d, s] for d in range(DAYS) for s in range(2)))
week_shifts[name] = var
# === Soft fairness objective ===
objective_terms = []
for i, name in enumerate(available_staff):
cum = cumulative_shifts.get(name, 0)
# Bias toward staff with fewer cumulative shifts
objective_terms.append(cum * week_shifts[name])
model.Minimize(sum(objective_terms))
solver = cp_model.CpSolver()
# Longer timeout for smaller teams with tighter constraints
solver.parameters.max_time_in_seconds = 45.0 if N_AVAIL <= 7 else 30.0
solver.parameters.num_search_workers = 6
if solver.Solve(model) not in (cp_model.OPTIMAL, cp_model.FEASIBLE):
# Create a detailed error message showing constraint violations
error_msg = f"Week {week_idx + 1} infeasible with {N_AVAIL} staff.\n"
error_msg += "Active constraints:\n"
error_msg += f"- No consecutive days: {'FULL' if FULL_NO_CONSECUTIVE else 'NIGHT ONLY'}\n"
error_msg += f"- Night rest: {'48h' if FULL_48H_REST else '24h'}\n"
error_msg += f"- Weekly bounds: {MIN_WEEKLY}-{MAX_WEEKLY} shifts\n"
error_msg += (
f"- Coverage: {wd_day}/{wd_night} weekdays, {we_day}/{we_night} weekends"
)
if reduced_days:
error_msg += (
f"\n- Reduced day(s): {', '.join(str(d) for d in reduced_days)}"
)
raise RuntimeError(error_msg)
schedule_week = {}
weekly_counts = {name: 0 for name in available_staff}
for d in range(7):
day_staff = [
full_names[p]
for p in range(9)
if solver.Value(x[p, d, SHIFT["day"]])
and not full_names[p].startswith("Vacant_")
]
night_staff = [
full_names[p]
for p in range(9)
if solver.Value(x[p, d, SHIFT["night"]])
and not full_names[p].startswith("Vacant_")
]
schedule_week[d] = {"day": day_staff, "night": night_staff}
for name in day_staff + night_staff:
weekly_counts[name] += 1
return schedule_week, weekly_counts
# def solve_week(
# week_idx: int,
# start_date: datetime.date,
# available_staff: list[str],
# cumulative_shifts: dict[str, int],
# all_staff_global: list[str],
# ) -> tuple[dict, dict]:
# N_AVAIL = len(available_staff)
# if N_AVAIL < 5:
# raise ValueError("Minimum 5 staff per week.")
# # Determine constraint strictness based on ACTUAL staff count
# # This is the critical fix - constraints must adapt based on team size
# FULL_NO_CONSECUTIVE = N_AVAIL >= 9 # Only full restriction with 9 staff
# FULL_48H_REST = N_AVAIL >= 9 # Only full 48h rest with 9 staff
# # Get coverage rules (still reduce for 5 staff)
# wd_day, wd_night, we_day, we_night, reduced_days = get_weekly_requirements(N_AVAIL)
# full_names = available_staff + [f"Vacant_{i}" for i in range(9 - N_AVAIL)]
# SHIFT = {"day": 0, "night": 1}
# DAYS = 7
# WEEKDAY_REL = {0, 1, 2, 3, 4}
# model = cp_model.CpModel()
# x = {}
# for p, d, s in itertools.product(range(9), range(DAYS), range(2)):
# x[p, d, s] = model.NewBoolVar(f"x_{p}_{d}_{s}")
# # === Dynamic Coverage ===
# for d in range(DAYS):
# if d in WEEKDAY_REL:
# day_req = wd_day
# if d in reduced_days:
# day_req = 2
# night_req = wd_night
# else:
# day_req = we_day
# night_req = we_night
# model.Add(sum(x[p, d, SHIFT["day"]] for p in range(9)) == day_req)
# model.Add(sum(x[p, d, SHIFT["night"]] for p in range(9)) == night_req)
# # === No same-day double shift (always enforced) ===
# for p, d in itertools.product(range(9), range(DAYS)):
# model.Add(x[p, d, SHIFT["day"]] + x[p, d, SHIFT["night"]] <= 1)
# # === CRITICAL FIX: Adaptive No consecutive days ===
# for p in range(9):
# for d in range(DAYS - 1):
# if FULL_NO_CONSECUTIVE:
# # Full restriction: no shifts on consecutive days
# model.Add(
# x[p, d, SHIFT["day"]]
# + x[p, d, SHIFT["night"]]
# + x[p, d + 1, SHIFT["day"]]
# + x[p, d + 1, SHIFT["night"]]
# <= 1
# )
# else:
# # Relaxed: only prevent consecutive NIGHT shifts
# model.Add(x[p, d, SHIFT["night"]] + x[p, d + 1, SHIFT["night"]] <= 1)
# # === Weekend cap (always enforced) ===
# for p in range(9):
# model.Add(sum(x[p, d, s] for d in (5, 6) for s in range(2)) <= 1)
# # === CRITICAL FIX: Adaptive 48h rest after night shift ===
# for p in range(9):
# for d in range(DAYS):
# night_d = x[p, d, SHIFT["night"]]
# # Always enforce 24h rest (no shift next day after night)
# if d + 1 < DAYS:
# any_d1 = x[p, d + 1, SHIFT["day"]] + x[p, d + 1, SHIFT["night"]]
# model.Add(any_d1 <= 1 - night_d)
# # Only enforce second day off with largest teams
# if FULL_48H_REST and d + 2 < DAYS:
# any_d2 = x[p, d + 2, SHIFT["day"]] + x[p, d + 2, SHIFT["night"]]
# model.Add(any_d2 <= 1 - night_d)
# # === Vacants forced to 0 ===
# for p in range(N_AVAIL, 9):
# for d, s in itertools.product(range(DAYS), range(2)):
# model.Add(x[p, d, s] == 0)
# # === CRITICAL FIX: Truly adaptive weekly bounds ===
# if N_AVAIL <= 6:
# MIN_WEEKLY, MAX_WEEKLY = 3, 4 # Small teams work more shifts
# elif N_AVAIL == 7:
# MIN_WEEKLY, MAX_WEEKLY = 2, 4 # Medium teams need flexibility
# elif N_AVAIL == 8:
# MIN_WEEKLY, MAX_WEEKLY = 2, 3 # Larger teams can have tighter bounds
# else: # N_AVAIL == 9
# MIN_WEEKLY, MAX_WEEKLY = 2, 3
# week_shifts = {}
# for i, name in enumerate(available_staff):
# var = model.NewIntVar(MIN_WEEKLY, MAX_WEEKLY, f"wshift_{i}")
# model.Add(var == sum(x[i, d, s] for d in range(DAYS) for s in range(2)))
# week_shifts[name] = var
# # === Soft fairness objective ===
# objective_terms = []
# for i, name in enumerate(available_staff):
# cum = cumulative_shifts.get(name, 0)
# objective_terms.append(cum * week_shifts[name])
# model.Minimize(sum(objective_terms))
# solver = cp_model.CpSolver()
# # Longer timeout for teams with tighter constraints
# solver.parameters.max_time_in_seconds = 45.0 if N_AVAIL <= 8 else 30.0
# solver.parameters.num_search_workers = 6
# if solver.Solve(model) not in (cp_model.OPTIMAL, cp_model.FEASIBLE):
# error_msg = f"Week {week_idx + 1} infeasible with {N_AVAIL} staff.\n"
# error_msg += "Active constraints:\n"
# error_msg += f"- No consecutive days: {'FULL' if FULL_NO_CONSECUTIVE else 'NIGHT ONLY'}\n"
# error_msg += f"- Night rest: {'48h' if FULL_48H_REST else '24h'}\n"
# error_msg += f"- Weekly bounds: {MIN_WEEKLY}-{MAX_WEEKLY} shifts\n"
# error_msg += (
# f"- Coverage: {wd_day}/{wd_night} weekdays, {we_day}/{we_night} weekends"
# )
# if reduced_days:
# error_msg += (
# f"\n- Reduced day(s): {', '.join(str(d) for d in reduced_days)}"
# )
# raise RuntimeError(error_msg)
# # [Rest of the function remains the same...]
# def solve_week(
# week_idx: int,
# start_date: datetime.date,
# available_staff: list[str],
# cumulative_shifts: dict[str, int],
# all_staff_global: list[str],
# ) -> tuple[dict, dict]:
# N_AVAIL = len(available_staff)
# if N_AVAIL < 5:
# raise ValueError("Minimum 5 staff per week.")
# Get coverage rules
wd_day, wd_night, we_day, we_night, reduced_days = get_weekly_requirements(N_AVAIL)
full_names = available_staff + [f"Vacant_{i}" for i in range(9 - N_AVAIL)]
SHIFT = {"day": 0, "night": 1}
DAYS = 7
WEEKDAY_REL = {0, 1, 2, 3, 4}
model = cp_model.CpModel()
x = {}
for p, d, s in itertools.product(range(9), range(DAYS), range(2)):
x[p, d, s] = model.NewBoolVar(f"x_{p}_{d}_{s}")
# === Dynamic Coverage ===
for d in range(DAYS):
if d in WEEKDAY_REL:
day_req = wd_day
if d in reduced_days:
day_req = 2
night_req = wd_night
else:
day_req = we_day
night_req = we_night
model.Add(sum(x[p, d, SHIFT["day"]] for p in range(9)) == day_req)
model.Add(sum(x[p, d, SHIFT["night"]] for p in range(9)) == night_req)
# === No same-day double shift (always enforced) ===
for p, d in itertools.product(range(9), range(DAYS)):
model.Add(x[p, d, SHIFT["day"]] + x[p, d, SHIFT["night"]] <= 1)
# === NO CONSECUTIVE DAYS - RELAXED FOR 9 STAFF ===
# Only prevent consecutive NIGHT shifts (keeps safety while enabling feasibility)
for p in range(9):
for d in range(DAYS - 1):
model.Add(x[p, d, SHIFT["night"]] + x[p, d + 1, SHIFT["night"]] <= 1)
# === Weekend cap (always enforced) ===
for p in range(9):
model.Add(sum(x[p, d, s] for d in (5, 6) for s in range(2)) <= 1)
# === 48h rest AFTER NIGHT SHIFT - RELAXED ===
# Keep 24h rest (no shift next day) but remove second day restriction
for p in range(9):
for d in range(DAYS):
night_d = x[p, d, SHIFT["night"]]
if d + 1 < DAYS:
any_d1 = x[p, d + 1, SHIFT["day"]] + x[p, d + 1, SHIFT["night"]]
model.Add(any_d1 <= 1 - night_d)
# === Vacants forced to 0 ===
for p in range(N_AVAIL, 9):
for d, s in itertools.product(range(DAYS), range(2)):
model.Add(x[p, d, s] == 0)
# === Weekly bounds - 9 staff can handle 2-3 shifts ===
MIN_WEEKLY, MAX_WEEKLY = 2, 3
week_shifts = {}
for i, name in enumerate(available_staff):
var = model.NewIntVar(MIN_WEEKLY, MAX_WEEKLY, f"wshift_{i}")
model.Add(var == sum(x[i, d, s] for d in range(DAYS) for s in range(2)))
week_shifts[name] = var
# === Fairness objective ===
objective_terms = []
for i, name in enumerate(available_staff):
cum = cumulative_shifts.get(name, 0)
objective_terms.append(cum * week_shifts[name])
model.Minimize(sum(objective_terms))
solver = cp_model.CpSolver()
solver.parameters.max_time_in_seconds = 45.0 # Longer timeout for complex solves
solver.parameters.num_search_workers = 6
status = solver.Solve(model)
if status not in (cp_model.OPTIMAL, cp_model.FEASIBLE):
status_map = {
cp_model.UNKNOWN: "UNKNOWN",
cp_model.MODEL_INVALID: "MODEL_INVALID",
cp_model.FEASIBLE: "FEASIBLE",
cp_model.INFEASIBLE: "INFEASIBLE",
cp_model.OPTIMAL: "OPTIMAL",
}
status_name = status_map.get(status, f"Status {status}")
error_msg = (
f"Week {week_idx + 1} solver returned: {status_name} with {N_AVAIL} staff\n"
)
error_msg += "To fix infeasibility:\n"
error_msg += "1. Check if constraints are too strict\n"
error_msg += "2. Verify staff count (9 should work with relaxed constraints)\n"
error_msg += "3. Ensure coverage requirements match team capacity"
raise RuntimeError(error_msg)
# === Extract solution ===
schedule_week = {}
weekly_counts = {name: 0 for name in available_staff}
for d in range(7):
day_staff = [
full_names[p]
for p in range(9)
if solver.Value(x[p, d, SHIFT["day"]])
and not full_names[p].startswith("Vacant_")
]
night_staff = [
full_names[p]
for p in range(9)
if solver.Value(x[p, d, SHIFT["night"]])
and not full_names[p].startswith("Vacant_")
]
schedule_week[d] = {"day": day_staff, "night": night_staff}
for name in day_staff + night_staff:
weekly_counts[name] += 1
return schedule_week, weekly_counts
def solve_week(
week_idx: int,
start_date: datetime.date,
available_staff: list[str],
cumulative_shifts: dict[str, int],
all_staff_global: list[str],
) -> tuple[dict, dict]:
"""Solve one week with constraints that adapt to team size."""
N_AVAIL = len(available_staff)
if N_AVAIL < 5:
raise ValueError("Minimum 5 staff per week required.")
# Determine constraint strictness based on staff count
IS_LARGE_TEAM = N_AVAIL >= 9 # 9 staff get strictest constraints
IS_MEDIUM_LARGE_TEAM = N_AVAIL == 8 # 8 staff get moderate constraints
# Get coverage rules
wd_day, wd_night, we_day, we_night, reduced_days = get_weekly_requirements(N_AVAIL)
full_names = available_staff + [f"Vacant_{i}" for i in range(9 - N_AVAIL)]
SHIFT = {"day": 0, "night": 1}
DAYS = 7
WEEKDAY_REL = {0, 1, 2, 3, 4}
model = cp_model.CpModel()
x = {}
for p, d, s in itertools.product(range(9), range(DAYS), range(2)):
x[p, d, s] = model.NewBoolVar(f"x_{p}_{d}_{s}")
# === Dynamic Coverage ===
for d in range(DAYS):
if d in WEEKDAY_REL:
day_req = wd_day
if d in reduced_days:
day_req = 2
night_req = wd_night
else:
day_req = we_day
night_req = we_night
model.Add(sum(x[p, d, SHIFT["day"]] for p in range(9)) == day_req)
model.Add(sum(x[p, d, SHIFT["night"]] for p in range(9)) == night_req)
# === No same-day double shift (always enforced) ===
for p, d in itertools.product(range(9), range(DAYS)):
model.Add(x[p, d, SHIFT["day"]] + x[p, d, SHIFT["night"]] <= 1)
# === No consecutive days (adaptive) ===
for p in range(9):
for d in range(DAYS - 1):
if IS_LARGE_TEAM:
# Full restriction for 9 staff teams
model.Add(
x[p, d, SHIFT["day"]]
+ x[p, d, SHIFT["night"]]
+ x[p, d + 1, SHIFT["day"]]
+ x[p, d + 1, SHIFT["night"]]
<= 1
)
elif IS_MEDIUM_LARGE_TEAM:
# For 8 staff: allow consecutive day shifts, restrict night shifts
model.Add(x[p, d, SHIFT["night"]] + x[p, d + 1, SHIFT["night"]] <= 1)
# Only prevent day-after-night and night-after-day
model.Add(x[p, d, SHIFT["night"]] + x[p, d + 1, SHIFT["day"]] <= 1)
model.Add(x[p, d, SHIFT["day"]] + x[p, d + 1, SHIFT["night"]] <= 1)
else:
# For 7 or fewer staff: minimal consecutive restrictions
model.Add(x[p, d, SHIFT["night"]] + x[p, d + 1, SHIFT["night"]] <= 1)
# === Weekend cap (always enforced) ===
for p in range(9):
model.Add(sum(x[p, d, s] for d in (5, 6) for s in range(2)) <= 1)
# === 48h rest after night shift (adaptive) ===
for p in range(9):
for d in range(DAYS):
night_d = x[p, d, SHIFT["night"]]
# Always enforce 24h rest (no shift next day after night)
if d + 1 < DAYS:
any_d1 = x[p, d + 1, SHIFT["day"]] + x[p, d + 1, SHIFT["night"]]
model.Add(any_d1 <= 1 - night_d)
# Only enforce second day off for 9-staff teams
if IS_LARGE_TEAM and d + 2 < DAYS:
any_d2 = x[p, d + 2, SHIFT["day"]] + x[p, d + 2, SHIFT["night"]]
model.Add(any_d2 <= 1 - night_d)
# === Vacants forced to 0 ===
for p in range(N_AVAIL, 9):
for d, s in itertools.product(range(DAYS), range(2)):
model.Add(x[p, d, s] == 0)
# === Weekly bounds (adaptive) ===
if N_AVAIL <= 6:
MIN_WEEKLY, MAX_WEEKLY = 3, 4 # Small teams work more shifts
elif N_AVAIL == 7:
MIN_WEEKLY, MAX_WEEKLY = 2, 4 # Medium teams need flexibility
elif N_AVAIL == 8:
MIN_WEEKLY, MAX_WEEKLY = 2, 3 # Medium-large teams
else: # 9 staff
MIN_WEEKLY, MAX_WEEKLY = 2, 3
week_shifts = {}
for i, name in enumerate(available_staff):
var = model.NewIntVar(MIN_WEEKLY, MAX_WEEKLY, f"wshift_{i}")
model.Add(var == sum(x[i, d, s] for d in range(DAYS) for s in range(2)))
week_shifts[name] = var
# === Soft fairness objective ===
objective_terms = []
for i, name in enumerate(available_staff):
cum = cumulative_shifts.get(name, 0)
objective_terms.append(cum * week_shifts[name])
model.Minimize(sum(objective_terms))
solver = cp_model.CpSolver()
# Longer timeout for smaller teams with tighter constraints
solver.parameters.max_time_in_seconds = 45.0 if N_AVAIL <= 8 else 30.0
solver.parameters.num_search_workers = 6
status = solver.Solve(model)
if status not in (cp_model.OPTIMAL, cp_model.FEASIBLE):
status_map = {
cp_model.UNKNOWN: "UNKNOWN",
cp_model.MODEL_INVALID: "MODEL_INVALID",
cp_model.FEASIBLE: "FEASIBLE",
cp_model.INFEASIBLE: "INFEASIBLE",
cp_model.OPTIMAL: "OPTIMAL",
}
status_name = status_map.get(status, f"Status {status}")
error_msg = (
f"Week {week_idx + 1} solver returned: {status_name} with {N_AVAIL} staff\n"
)
error_msg += "Active constraints:\n"
error_msg += f"- No consecutive days: {'FULL' if IS_LARGE_TEAM else ('MODERATE' if IS_MEDIUM_LARGE_TEAM else 'MINIMAL')}\n"
error_msg += f"- Night rest: {'48h' if IS_LARGE_TEAM else '24h'}\n"
error_msg += f"- Weekly bounds: {MIN_WEEKLY}-{MAX_WEEKLY} shifts\n"
error_msg += (
f"- Coverage: {wd_day}/{wd_night} weekdays, {we_day}/{we_night} weekends"
)
if reduced_days:
error_msg += (
f"\n- Reduced day(s): {', '.join(str(d) for d in reduced_days)}"
)
# Add troubleshooting tips
if N_AVAIL == 8 and status == cp_model.INFEASIBLE:
error_msg += "\n\nüí° Troubleshooting for 8 staff:"
error_msg += "\n- Try increasing max weekly shifts to 4 for some staff"
error_msg += "\n- Consider relaxing weekend cap for one staff member"
error_msg += "\n- Check if night shift distribution is balanced"
raise RuntimeError(error_msg)
# === Extract solution ===
schedule_week = {}
weekly_counts = {name: 0 for name in available_staff}
for d in range(7):
day_staff = [
full_names[p]
for p in range(9)
if solver.Value(x[p, d, SHIFT["day"]])
and not full_names[p].startswith("Vacant_")
]
night_staff = [
full_names[p]
for p in range(9)
if solver.Value(x[p, d, SHIFT["night"]])
and not full_names[p].startswith("Vacant_")
]
schedule_week[d] = {"day": day_staff, "night": night_staff}
for name in day_staff + night_staff:
weekly_counts[name] += 1
return schedule_week, weekly_counts
# ------------------------------
# Google Drive & Gmail Helpers (graceful fallback)
# ------------------------------
import io
from google.oauth2.service_account import Credentials
from googleapiclient.discovery import build
from pydrive2.auth import GoogleAuth
from pydrive2.drive import GoogleDrive
def get_drive():
scopes = [
"https://www.googleapis.com/auth/drive.file",
"https://www.googleapis.com/auth/gmail.send",
]
cred_path = "credentials.json"
if Path(cred_path).exists():
creds = Credentials.from_service_account_file(cred_path, scopes=scopes)
else:
cred_json = os.getenv("GOOGLE_CREDENTIALS_JSON")
if cred_json:
creds = Credentials.from_service_account_info(
json.loads(cred_json), scopes=scopes
)
else:
raise FileNotFoundError("No Google credentials found")
gauth = GoogleAuth()
gauth.credentials = creds
return GoogleDrive(gauth)
DRIVE_FOLDER_ID = os.getenv("DRIVE_FOLDER_ID", "root")
def save_to_drive(filename: str, content: bytes):
try:
drive = get_drive()
file = drive.CreateFile(
{"title": filename, "parents": [{"id": DRIVE_FOLDER_ID}]}
)
file.content = io.BytesIO(content)
file.Upload()
return file["id"]
except Exception as e:
st.warning(f"Google Drive save failed: {e}")
return None
def list_drive_files(prefix="roster_"):
try:
drive = get_drive()
files = drive.ListFile(
{
"q": f"'{DRIVE_FOLDER_ID}' in parents and title contains '{prefix}' and trashed=false"
}
).GetList()
return sorted(files, key=lambda f: f["createdDate"], reverse=True)
except Exception:
return []
def load_from_drive(file_id: str) -> bytes:
try:
drive = get_drive()
file = drive.CreateFile({"id": file_id})
buffer = io.BytesIO()
file.GetContentFile(buffer)
return buffer.getvalue()
except Exception as e:
st.error(f"Drive load failed: {e}")
return None
def send_email(to: str, subject: str, body: str):
try:
scopes = ["https://www.googleapis.com/auth/gmail.send"]
cred_path = "credentials.json"
if Path(cred_path).exists():
creds = Credentials.from_service_account_file(cred_path, scopes=scopes)
else:
cred_json = os.getenv("GOOGLE_CREDENTIALS_JSON")
if not cred_json:
st.warning("Email skipped: No Google credentials found")
return
creds = Credentials.from_service_account_info(
json.loads(cred_json), scopes=scopes
)
service = build("gmail", "v1", credentials=creds)
from_email = os.getenv("GMAIL_FROM", "no-reply@yourdomain.com")
message = f"""From: {from_email}
To: {to}
Subject: {subject}
MIME-Version: 1.0
Content-Type: text/html; charset=utf-8
{body}"""
import base64
raw = base64.urlsafe_b64encode(message.encode()).decode()
body_req = {"raw": raw}
service.users().messages().send(userId="me", body=body_req).execute()
except Exception as e:
st.warning(f"Email sending failed: {e}")
def schedule_weekly_emails(
schedule_full: dict, staff_emails: dict, start_date: datetime.date
):
def job():
today = datetime.now().date()
days_since = (today - start_date).days
if not (0 <= days_since < 42):
return
week_idx = days_since // 7
for name, email in staff_emails.items():
shifts = []
for d in range(week_idx * 7, min((week_idx + 1) * 7, 42)):
dt = start_date + timedelta(days=d)
if name in schedule_full.get(d, {}).get("day", []):
shifts.append(f"{dt:%a %d %b} Day")
if name in schedule_full.get(d, {}).get("night", []):
shifts.append(f"{dt:%a %d %b} Night")
if shifts:
body = (
f"<p>Hi {name},</p><p>Your shifts for Week {week_idx + 1}:</p><ul>"
+ "".join(f"<li>{s}</li>" for s in shifts)
+ "</ul><p>Rest well!</p>"
)
send_email(email, f"Roster: Week {week_idx + 1}", body)
schedule.every().monday.at("08:00").do(job)
def run_sched():
while True:
schedule.run_pending()
pytime.sleep(60)
threading.Thread(target=run_sched, daemon=True).start()
# ------------------------------
# PDF & ICS Exports
# ------------------------------
def export_pdf(schedule, weekly_counts, start_date, output_path):
try:
from reportlab.lib import colors
from reportlab.lib.pagesizes import A4, landscape
from reportlab.lib.styles import ParagraphStyle
from reportlab.lib.units import inch
from reportlab.platypus import (
PageBreak,
Paragraph,
SimpleDocTemplate,
Table,
TableStyle,
)
doc = SimpleDocTemplate(
str(output_path),
pagesize=landscape(A4),
leftMargin=0.4 * inch,
rightMargin=0.4 * inch,
topMargin=0.4 * inch,
bottomMargin=0.4 * inch,
)
elements = []
title_style = ParagraphStyle("Title", fontSize=16, spaceAfter=12, alignment=1)
week_style = ParagraphStyle("Week", fontSize=14, spaceAfter=6, spaceBefore=12)
elements.append(Paragraph("6‚ÄëWeek Fair Roster", title_style))
def day_label(d):
return f"W{(d // 7) + 1:02d}-{'Mon Tue Wed Thu Fri Sat Sun'.split()[d % 7]}"
for w in range(6):
elements.append(Paragraph(f"Week {w + 1}", week_style))
data = [["Date", "Day", "Type", "Day Shift", "Night Shift"]]
for d in range(w * 7, (w + 1) * 7):
dt = start_date + timedelta(days=d)
dl = day_label(d)
typ = "WD" if (d % 7) < 5 else "WE"
ds = ", ".join(schedule.get(d, {}).get("day", []))
ns = ", ".join(schedule.get(d, {}).get("night", []))
data.append([dt.strftime("%a %d %b"), dl, typ, ds, ns])
table = Table(
data,
colWidths=[0.8 * inch, 0.9 * inch, 0.5 * inch, 2.2 * inch, 2.2 * inch],
)
table.setStyle(
TableStyle(
[
("BACKGROUND", (0, 0), (-1, 0), colors.darkblue),
("TEXTCOLOR", (0, 0), (-1, 0), colors.whitesmoke),
("GRID", (0, 0), (-1, -1), 0.5, colors.black),
("FONTNAME", (0, 0), (-1, 0), "Helvetica-Bold"),
("FONTSIZE", (0, 0), (-1, 0), 10),
]
)
)
elements.append(table)
if w < 5:
elements.append(PageBreak())
doc.build(elements)
return True
except Exception as e:
st.error(f"PDF failed: {e}")
return False
def export_ics(schedule, start_date, output_path):
try:
from icalendar import Alarm, Calendar, Event
cal = Calendar()
cal.add("prodid", "-//Roster//streamlit//")
cal.add("version", "2.0")
for d in range(42):
shift_date = start_date + timedelta(days=d)
for shift_type, key in [("Day", "day"), ("Night", "night")]:
for name in schedule.get(d, {}).get(key, []):
ev = Event()
st_t = dt_time(8, 0) if shift_type == "Day" else dt_time(20, 0)
en_t = dt_time(16, 0) if shift_type == "Day" else dt_time(8, 0)
ev.add("summary", f"{name} — {shift_type} Shift")
ev.add("dtstart", datetime.combine(shift_date, st_t))
ev.add(
"dtend",
datetime.combine(
shift_date
+ (
timedelta(days=1)
if shift_type == "Night"
else timedelta()
),
en_t,
),
)
ev.add("categories", [shift_type])
alarm = Alarm()
alarm.add("action", "DISPLAY")
alarm.add("trigger", timedelta(minutes=-15))
ev.add_component(alarm)
cal.add_component(ev)
with open(output_path, "wb") as f:
f.write(cal.to_ical())
return True
except Exception as e:
st.error(f"ICS failed: {e}")
return False
# ------------------------------
# Streamlit App ‚CORRECTED SESSION STATE HANDLING
# ------------------------------
st.set_page_config(page_title="Enterprise Roster (Final)", layout="wide")
st.title("Enterprise Roster Generator ‚Final")
# === Initialize session state (FIRST RUN ONLY) ===
if "initialized" not in st.session_state:
st.session_state.initialized = True
st.session_state.names = [""] * 9
st.session_state.emails = [""] * 9
# Use a separate key for default start date
st.session_state.start_date = (
datetime.today() + timedelta(days=(7 - datetime.today().weekday()) % 7)
).date()
st.session_state.user_role = "manager"
st.session_state.staff_email = ""
st.session_state.cumulative_shifts = {}
st.session_state.roster_weekly = {}
st.session_state.roster_ready = False
# === Auth UI ===
st.sidebar.header("Access")
role = st.sidebar.radio(
"Role",
["Manager", "Staff"],
index=0 if st.session_state.user_role == "manager" else 1,
key="role_radio",
)
st.session_state.user_role = "manager" if role == "Manager" else "staff"
if st.session_state.user_role == "staff":
staff_email_input = st.sidebar.text_input(
"Your Email", value=st.session_state.staff_email, key="staff_email_input"
)
st.session_state.staff_email = staff_email_input.strip().lower()
# === Manager Input ===
if st.session_state.user_role == "manager":
st.header("1. Staff")
cols = st.columns(3)
for i in range(9):
with cols[i % 3]:
name_val = st.text_input(
f"Staff {i + 1} Name",
value=st.session_state.names[i],
key=f"name_input_{i}",
)
email_val = st.text_input(
f"Email {i + 1}",
value=st.session_state.emails[i],
key=f"email_input_{i}",
)
st.session_state.names[i] = name_val.strip()
st.session_state.emails[i] = email_val.strip().lower()
st.header("2. Start Monday")
# ✅ CORRECT: widget key ≠ session state key
sd = st.date_input(
"First Monday",
value=st.session_state.start_date,
key="start_date_input", # ‚Üê distinct from st.session_state.start_date
)
# Update session state only if changed
if sd != st.session_state.start_date:
st.session_state.start_date = sd
st.header("3. Weekly Availability (Holiday/Mission)")
st.markdown(
"Uncheck staff who are unavailable (max 4 absent/week ‚min 5 available)."
)
avail_matrix = {}
cols_w = st.columns(6)
for w in range(6):
with cols_w[w]:
st.subheader(f"Week {w + 1}")
available = []
for i, name in enumerate([n for n in st.session_state.names if n]):
# ‚úÖ Use unique key per checkbox
is_avail = st.checkbox(f"{name}", value=True, key=f"avail_w{w}_p{i}")
if is_avail:
available.append(name)
avail_matrix[w] = available
if len(available) < 5:
st.error("⚠️ ≥5 must be available")
if st.button("Generate Rolling Roster", type="primary", key="generate_btn"):
try:
names_all = [n for n in st.session_state.names if n]
if not names_all:
st.error("Please enter at least one staff name.")
st.stop()
emails_all = {
n: e
for n, e in zip(
[n for n in st.session_state.names if n],
[
e
for i, e in enumerate(st.session_state.emails)
if st.session_state.names[i]
],
)
}
cum_shifts = {name: 0 for name in names_all}
weekly_sched = {}
# Validate weekly availability before solving
for w in range(6):
avail = avail_matrix[w]
if len(avail) < 5:
st.error(
f"Week {w + 1} has only {len(avail)} available staff. Minimum is 5."
)
st.stop()
# Check if we need reduced coverage
if len(avail) == 5:
st.warning(
f"Week {w + 1}: Reduced coverage mode (one weekday day shift = 2 staff)"
)
for w in range(6):
week_start = st.session_state.start_date + timedelta(weeks=w)
avail = avail_matrix[w]
try:
sched_w, counts_w = solve_week(
w, week_start, avail, cum_shifts, names_all
)
except Exception as e:
st.error(f"Failed to generate Week {w + 1}: {str(e)}")
st.stop()
for name, cnt in counts_w.items():
cum_shifts[name] = cum_shifts.get(name, 0) + cnt
abs_sched = {}
for d_rel, shifts in sched_w.items():
d_abs = w * 7 + d_rel
abs_sched[d_abs] = shifts
weekly_sched[w] = abs_sched
st.session_state.cumulative_shifts = cum_shifts
st.session_state.roster_weekly = weekly_sched
st.session_state.roster_ready = True
# Auto-save to Drive (graceful)
try:
data = pickle.dumps(
{
"weekly": weekly_sched,
"cumulative": cum_shifts,
"start": st.session_state.start_date,
}
)
fid = save_to_drive(
f"roster_{st.session_state.start_date:%Y%m%d}.pkl", data
)
if fid:
st.info(f"Saved to Drive (ID: {fid[:8]}…)")
except Exception as e:
st.warning(f"Drive save failed: {e}")
# Email scheduler
try:
full_sched = {}
for w_sched in weekly_sched.values():
full_sched.update(w_sched)
schedule_weekly_emails(
full_sched, emails_all, st.session_state.start_date
)
st.info("Weekly email reminders scheduled.")
except Exception as e:
st.warning(f"Email setup failed: {e}")
st.success("Rolling roster generated!")
except Exception as e:
st.error(f"Generation failed: {e}")
# === Display ===
if st.session_state.roster_ready:
full_sched = {}
for w_sched in st.session_state.roster_weekly.values():
full_sched.update(w_sched)
if st.session_state.user_role == "manager":
# Show warning if any week has reduced coverage
reduced_weeks = []
for w in range(6):
if len(avail_matrix[w]) == 5:
reduced_weeks.append(w + 1)
if reduced_weeks:
st.warning(
f"Reduced coverage in Week(s): {', '.join(map(str, reduced_weeks))} "
"(one weekday day shift = 2 staff instead of 3)."
)
st.header("Full 6 Week Roster")
rows = []
for d in range(42):
dt = st.session_state.start_date + timedelta(days=d)
wd = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"][d % 7]
week = d // 7 + 1
typ = "WD" if (d % 7) < 5 else "WE"
rows.append(
{
"Week": f"W{week}",
"Date": dt.strftime("%Y-%m-%d"),
"Day": wd,
"Type": typ,
"Day Shift": ", ".join(full_sched.get(d, {}).get("day", [])),
"Night Shift": ", ".join(full_sched.get(d, {}).get("night", [])),
}
)
df = pd.DataFrame(rows)
st.dataframe(df, use_container_width=True, hide_index=True)
st.subheader("Cumulative Shifts")
summ = []
for name in [n for n in st.session_state.names if n]:
summ.append(
{
"Staff": name,
"Total": st.session_state.cumulative_shifts.get(name, 0),
}
)
st.dataframe(pd.DataFrame(summ), use_container_width=True, hide_index=True)
# Exports
c1, c2, c3, c4 = st.columns(4)
with c1:
st.download_button(
"CSV",
df.to_csv(index=False).encode(),
"roster.csv",
"text/csv",
key="dl_csv",
)
with c2:
with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as f:
if export_pdf(
full_sched, {}, st.session_state.start_date, Path(f.name)
):
with open(f.name, "rb") as pf:
st.download_button(
"PDF",
pf.read(),
"roster.pdf",
"application/pdf",
key="dl_pdf",
)
os.unlink(f.name)
with c3:
with tempfile.NamedTemporaryFile(delete=False, suffix=".ics") as f:
if export_ics(full_sched, st.session_state.start_date, Path(f.name)):
with open(f.name, "rb") as pf:
st.download_button(
"ICS",
pf.read(),
"roster.ics",
"text/calendar",
key="dl_ics",
)
os.unlink(f.name)
with c4:
if st.button("Clear", key="clear_btn"):
st.session_state.roster_ready = False
st.session_state.roster_weekly = {}
st.session_state.cumulative_shifts = {}
st.rerun()
# Drive Load
st.subheader("Load from Drive")
files = list_drive_files()
if files:
opts = {f["title"]: f["id"] for f in files}
sel = st.selectbox("Select roster", list(opts.keys()), key="drive_select")
if st.button("Load Selected", key="load_btn"):
try:
data = pickle.loads(load_from_drive(opts[sel]))
st.session_state.roster_weekly = data["weekly"]
st.session_state.cumulative_shifts = data["cumulative"]
st.session_state.start_date = data["start"]
st.session_state.roster_ready = True
st.success("Loaded!")
st.rerun()
except Exception as e:
st.error(f"Load failed: {e}")
else:
st.info("No saved rosters.")
else: # staff view
known_names = [n for n in st.session_state.names if n]
known_emails = [
e
for i, e in enumerate(st.session_state.emails)
if st.session_state.names[i]
]
staff_name = None
if st.session_state.staff_email in known_emails:
staff_name = known_names[known_emails.index(st.session_state.staff_email)]
if not staff_name:
st.warning("Enter an email matching a staff member.")
else:
st.header(f"Your Shifts, {staff_name}")
my_shifts = []
for d in range(42):
dt = st.session_state.start_date + timedelta(days=d)
if staff_name in full_sched.get(d, {}).get("day", []):
my_shifts.append({"Date": dt.strftime("%Y-%m-%d"), "Shift": "Day"})
if staff_name in full_sched.get(d, {}).get("night", []):
my_shifts.append(
{"Date": dt.strftime("%Y-%m-%d"), "Shift": "Night"}
)
if my_shifts:
st.dataframe(
pd.DataFrame(my_shifts), use_container_width=True, hide_index=True
)
else:
st.info("No shifts assigned to you in this roster period.")
st.caption(
"Final adaptive version — constraints adjust based on team size for 5-9 staff teams."
)
|