import streamlit as st
import pandas as pd
import numpy as np
import io
import re
import math
import time
import json
import os
import requests
import pydeck as pdk
import openpyxl
import difflib
import datetime
import sqlite3
from sklearn.cluster import KMeans
from ortools.constraint_solver import routing_enums_pb2
from ortools.constraint_solver import pywrapcp
# --- PAGE SETUP & THEME ---
st.set_page_config(page_title="Repsly Command Center", page_icon="β‘", layout="wide")
st.markdown("""
""", unsafe_allow_html=True)
# ==============================================================================
# π§ UNIVERSAL SECRET READER
# ==============================================================================
def get_secret(key, default=None):
"""Try every method HF Spaces / Streamlit uses to store secrets."""
# Method 1: direct st.secrets
try:
val = st.secrets[key]
if val is not None and str(val).strip():
return str(val).strip()
except Exception:
pass
# Method 2: nested under DEFAULT
try:
val = st.secrets["DEFAULT"][key]
if val is not None and str(val).strip():
return str(val).strip()
except Exception:
pass
# Method 3: environment variable
val = os.environ.get(key, "").strip()
if val:
return val
# Method 4: SECRET_ prefixed
val = os.environ.get(f"SECRET_{key}", "").strip()
if val:
return val
return default
# ==============================================================================
# π SECURE LOGIN GATEWAY
# ==============================================================================
if "authenticated" not in st.session_state:
st.session_state.authenticated = False
_secrets_ok = bool(get_secret("APP_USER")) and bool(get_secret("APP_PASS"))
_api_ok = bool(get_secret("REPSLY_API_USER")) and bool(get_secret("REPSLY_API_KEY"))
if not _secrets_ok or not _api_ok:
st.title("π Repsly Command Center β Setup Required")
st.error("β οΈ **Cannot start:** One or more secrets are missing.")
missing = [k for k in ["APP_USER", "APP_PASS", "REPSLY_API_USER", "REPSLY_API_KEY"] if not get_secret(k)]
st.warning(f"**Missing:** `{'`, `'.join(missing)}`")
st.write("Create `.streamlit/secrets.toml` in your repo:")
st.code(
'APP_USER = "your_username"\nAPP_PASS = "your_password"\n'
'REPSLY_API_USER = "your_api_user"\nREPSLY_API_KEY = "your_api_key"',
language="toml"
)
st.stop()
elif not st.session_state.authenticated:
st.title("π Repsly Command Center")
st.write("Authorized personnel only. Please log in to access the routing engine.")
col1, col2, col3 = st.columns([1, 2, 1])
with col2:
with st.form("login_form"):
user_input = st.text_input("Username")
pass_input = st.text_input("Password", type="password")
if st.form_submit_button("Log In", use_container_width=True):
if user_input.strip() == get_secret("APP_USER") and pass_input == get_secret("APP_PASS"):
st.session_state.authenticated = True
st.rerun()
else:
st.error("β Invalid username or password.")
APP_READY = st.session_state.authenticated and _secrets_ok and _api_ok
if not APP_READY:
st.stop()
API_USERNAME = get_secret("REPSLY_API_USER", "")
API_PASSWORD = get_secret("REPSLY_API_KEY", "")
# ==============================================================================
# πΎ LOCAL DATABASE CACHE SETTINGS
# ==============================================================================
CLIENTS_CACHE_FILE = "repsly_clients_cache.json"
FORMS_CACHE_FILE = "repsly_forms_cache.json"
VISITS_CACHE_FILE = "repsly_visits_cache.json"
META_CACHE_FILE = "repsly_meta_cache.json"
def check_cache_freshness():
needed = [CLIENTS_CACHE_FILE, FORMS_CACHE_FILE, META_CACHE_FILE, VISITS_CACHE_FILE]
if not all(os.path.exists(f) for f in needed):
return False
try:
with open(META_CACHE_FILE, 'r') as f:
return json.load(f).get("last_sync_date") == str(datetime.date.today())
except Exception:
return False
def load_from_cache():
with open(CLIENTS_CACHE_FILE, 'r') as f:
clients = json.load(f)
with open(FORMS_CACHE_FILE, 'r') as f:
forms = json.load(f)
with open(VISITS_CACHE_FILE, 'r') as f:
visits = json.load(f)
with open(META_CACHE_FILE, 'r') as f:
meta = json.load(f)
return clients, forms, visits, meta.get("reps", [])
def save_to_cache(clients, forms, visits, reps):
with open(CLIENTS_CACHE_FILE, 'w') as f:
json.dump(clients, f)
with open(FORMS_CACHE_FILE, 'w') as f:
json.dump(forms, f)
with open(VISITS_CACHE_FILE, 'w') as f:
json.dump(visits, f)
with open(META_CACHE_FILE, 'w') as f:
json.dump({"last_sync_date": str(datetime.date.today()), "reps": reps}, f)
# ==============================================================================
# ποΈ SQLITE DATABASE ENGINE (Mode 2 Persistent Storage)
# ==============================================================================
DB_PATH = "repsly_command_center.db"
def get_db():
"""Get a database connection with WAL mode for performance."""
conn = sqlite3.connect(DB_PATH)
conn.execute("PRAGMA journal_mode=WAL")
conn.execute("PRAGMA synchronous=NORMAL")
conn.row_factory = sqlite3.Row
return conn
def init_database():
"""Create all tables if they don't exist. Safe to call repeatedly."""
conn = get_db()
conn.executescript("""
CREATE TABLE IF NOT EXISTS clients (
client_code TEXT PRIMARY KEY,
name TEXT,
rep_name TEXT,
active INTEGER DEFAULT 1,
lat REAL DEFAULT 0.0,
lon REAL DEFAULT 0.0,
street_address TEXT,
city TEXT,
state TEXT,
zip TEXT,
tag TEXT,
territory TEXT,
raw_json TEXT,
updated_at TEXT
);
CREATE TABLE IF NOT EXISTS forms (
form_id TEXT PRIMARY KEY,
rep_name TEXT,
client_code TEXT,
form_name TEXT,
cases INTEGER DEFAULT 0,
record_timestamp INTEGER,
visit_date TEXT,
is_order INTEGER DEFAULT 0
);
CREATE TABLE IF NOT EXISTS sync_meta (
key TEXT PRIMARY KEY,
value TEXT
);
CREATE TABLE IF NOT EXISTS reps (
name TEXT PRIMARY KEY
);
CREATE TABLE IF NOT EXISTS generated_routes (
id INTEGER PRIMARY KEY AUTOINCREMENT,
rep_name TEXT,
day_name TEXT,
generated_at TEXT,
total_stops INTEGER,
stops_json TEXT
);
CREATE INDEX IF NOT EXISTS idx_forms_rep ON forms(rep_name);
CREATE INDEX IF NOT EXISTS idx_forms_client ON forms(client_code);
CREATE INDEX IF NOT EXISTS idx_forms_visit ON forms(rep_name, client_code, visit_date);
CREATE INDEX IF NOT EXISTS idx_clients_rep ON clients(rep_name);
""")
conn.commit()
conn.close()
# Initialize on startup
init_database()
def db_get_meta(key, default=None):
"""Read a value from the sync_meta table."""
conn = get_db()
row = conn.execute("SELECT value FROM sync_meta WHERE key = ?", (key,)).fetchone()
conn.close()
return row["value"] if row else default
def db_set_meta(key, value):
"""Write a value to the sync_meta table."""
conn = get_db()
conn.execute(
"INSERT OR REPLACE INTO sync_meta (key, value) VALUES (?, ?)",
(key, str(value))
)
conn.commit()
conn.close()
def db_upsert_clients(clients_list, status_placeholder=None):
"""Bulk upsert client records into SQLite."""
conn = get_db()
now = str(datetime.datetime.now())
batch = []
for client in clients_list:
code = _extract_client_code(client)
if not code:
continue
rep_name = _extract_rep_name(client)
active_val = client.get("Active")
active = 0 if (active_val is not None and str(active_val).lower() in ("false", "0", "no")) else 1
lat_raw = client.get("GPSLatitude") or client.get("Latitude")
lon_raw = client.get("GPSLongitude") or client.get("Longitude")
try:
lat = float(lat_raw) if lat_raw else 0.0
lon = float(lon_raw) if lon_raw else 0.0
except (ValueError, TypeError):
lat, lon = 0.0, 0.0
batch.append((
code,
str(client.get("Name") or "Unknown"),
rep_name,
active,
lat, lon,
str(client.get("StreetAddress", "")).strip(),
str(client.get("City", "")).strip(),
str(client.get("State", "")).strip(),
str(client.get("ZIP", "")).strip(),
str(client.get("Tag") or "").strip(),
str(client.get("Territory") or "").strip(),
json.dumps(client),
now,
))
conn.executemany("""
INSERT OR REPLACE INTO clients
(client_code, name, rep_name, active, lat, lon, street_address, city, state, zip, tag, territory, raw_json, updated_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""", batch)
conn.commit()
if status_placeholder:
status_placeholder.info(f"πΎ Saved {len(batch):,} accounts to database.")
conn.close()
return len(batch)
def db_upsert_forms(forms_batch, status_placeholder=None):
"""
Process raw API form records into the forms table.
Uses INSERT OR IGNORE for speed β no individual SELECT checks.
Tracks ALL form types as visits, flags orders separately for case counting.
"""
conn = get_db()
sql_batch = []
for form in forms_batch:
form_id = _safe_str(
form.get("FormID") or form.get("FormResultID")
or form.get("formResultId") or form.get("ID")
)
if not form_id:
continue
rep_name = str(form.get("RepresentativeName", "")).strip()
form_name = str(form.get("FormName", "")).lower()
client_code = str(form.get("ClientCode", "")).strip()
record_ts = _parse_form_timestamp(form)
visit_date = None
if record_ts is not None:
visit_date = datetime.datetime.utcfromtimestamp(record_ts).strftime("%Y-%m-%d")
# Flag order forms for case counting
is_order = 1 if "order" in form_name else 0
case_count = 0
if is_order:
for item in form.get("Items", []):
title = str(item.get("Title", "")).lower()
if "case" in title:
try:
case_count += int(re.search(r'\d+', str(item.get("Value", "0"))).group())
except (AttributeError, ValueError):
pass
sql_batch.append((
form_id, rep_name, client_code, form_name,
case_count, record_ts, visit_date, is_order
))
new_count = 0
if sql_batch:
# INSERT OR IGNORE skips duplicates automatically β no slow individual checks
cursor = conn.executemany("""
INSERT OR IGNORE INTO forms
(form_id, rep_name, client_code, form_name, cases, record_timestamp, visit_date, is_order)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
""", sql_batch)
conn.commit()
new_count = conn.execute("SELECT changes()").fetchone()[0]
if status_placeholder:
status_placeholder.info(f"πΎ Processed {len(sql_batch):,} forms, {new_count:,} new.")
conn.close()
return new_count
def db_upsert_reps(reps_list):
"""Store the list of rep names."""
conn = get_db()
conn.executemany(
"INSERT OR IGNORE INTO reps (name) VALUES (?)",
[(r,) for r in reps_list]
)
conn.commit()
conn.close()
def db_get_reps():
"""Get sorted list of all rep names."""
conn = get_db()
rows = conn.execute("SELECT name FROM reps ORDER BY name").fetchall()
conn.close()
return [r["name"] for r in rows]
def db_get_rep_accounts(rep_name, include_inactive=False):
"""Get all routable accounts for a rep. Only includes accounts with a valid
Customer ID (2-letter + 4-digit code like NC1234) in their name or code."""
conn = get_db()
rep_lower = rep_name.lower().strip()
customer_id_pattern = re.compile(r'[A-Za-z]{2}\d{4}')
query = """
SELECT client_code, name, lat, lon, active,
street_address, city, state, zip, tag, territory, rep_name
FROM clients
WHERE LOWER(rep_name) LIKE ?
AND lat != 0.0 AND lon != 0.0
"""
params = [f"%{rep_lower}%"]
if not include_inactive:
query += " AND active = 1"
rows = conn.execute(query, params).fetchall()
conn.close()
accounts = []
for r in rows:
# CHECK: Must have a valid Customer ID (XX0000 pattern) in name or code
combined = f"{r['client_code']} {r['name']}"
id_match = customer_id_pattern.search(combined)
if not id_match:
continue # Not a serviced account β skip
customer_id = id_match.group(0).upper()
addr_parts = [r["street_address"], r["city"], r["state"], r["zip"]]
address = ", ".join(p for p in addr_parts if p and p.lower() != "none")
# Clean store name β remove the ID from the display name
clean_name = r["name"]
if customer_id in clean_name:
clean_name = clean_name.replace(customer_id, "").replace("-", "").strip()
if not clean_name:
clean_name = r["name"]
accounts.append({
"code": customer_id,
"name": clean_name,
"addr": address or "No address",
"lat": r["lat"],
"lon": r["lon"],
"tag": r["tag"] or r["territory"] or "Untagged",
"active": r["active"],
"raw_client_code": r["client_code"],
})
return accounts
def db_get_order_volume(rep_name, client_codes=None):
"""Get order counts and total cases per client.
Searches by rep name AND optionally by client code list for completeness."""
conn = get_db()
rep_lower = rep_name.lower().strip()
# Get orders by rep name match
rows = conn.execute("""
SELECT client_code,
COUNT(*) as order_count,
SUM(cases) as total_cases
FROM forms
WHERE LOWER(rep_name) LIKE ? AND is_order = 1
GROUP BY client_code
""", (f"%{rep_lower}%",)).fetchall()
result = {r["client_code"]: {"orders": r["order_count"], "cases": r["total_cases"]} for r in rows}
# Also check by client_code directly (catches forms filed by other reps for same account)
if client_codes:
placeholders = ",".join(["?"] * len(client_codes))
extra_rows = conn.execute(f"""
SELECT client_code,
COUNT(*) as order_count,
SUM(cases) as total_cases
FROM forms
WHERE client_code IN ({placeholders}) AND is_order = 1
GROUP BY client_code
""", client_codes).fetchall()
for r in extra_rows:
cc = r["client_code"]
if cc not in result:
result[cc] = {"orders": r["order_count"], "cases": r["total_cases"]}
else:
# Use the higher count (in case rep match and code match overlap)
result[cc]["orders"] = max(result[cc]["orders"], r["order_count"])
result[cc]["cases"] = max(result[cc]["cases"], r["total_cases"])
conn.close()
return result
def db_get_last_visits(rep_name, client_codes=None):
"""Get most recent visit date per client.
Checks ALL form types (not just orders) since any form submission = a visit.
Searches by both rep name AND client code for maximum coverage."""
conn = get_db()
rep_lower = rep_name.lower().strip()
# Method 1: Forms filed by this rep
rows = conn.execute("""
SELECT client_code, MAX(visit_date) as last_visit
FROM forms
WHERE LOWER(rep_name) LIKE ? AND visit_date IS NOT NULL
GROUP BY client_code
""", (f"%{rep_lower}%",)).fetchall()
result = {r["client_code"]: r["last_visit"] for r in rows}
# Method 2: Also check by client code directly (any rep's visit counts)
if client_codes:
placeholders = ",".join(["?"] * len(client_codes))
extra_rows = conn.execute(f"""
SELECT client_code, MAX(visit_date) as last_visit
FROM forms
WHERE client_code IN ({placeholders}) AND visit_date IS NOT NULL
GROUP BY client_code
""", client_codes).fetchall()
for r in extra_rows:
cc = r["client_code"]
if cc not in result or (r["last_visit"] and r["last_visit"] > result.get(cc, "")):
result[cc] = r["last_visit"]
conn.close()
return result
def db_get_form_date_range():
"""Get the earliest and latest form dates in the database."""
conn = get_db()
row = conn.execute("""
SELECT MIN(visit_date) as earliest, MAX(visit_date) as latest, COUNT(*) as total
FROM forms WHERE visit_date IS NOT NULL
""").fetchone()
conn.close()
return row["earliest"], row["latest"], row["total"]
def db_get_client_count():
"""Get total number of clients in database."""
conn = get_db()
row = conn.execute("SELECT COUNT(*) as cnt FROM clients").fetchone()
conn.close()
return row["cnt"]
def db_get_form_count():
"""Get total number of forms in database."""
conn = get_db()
row = conn.execute("SELECT COUNT(*) as cnt FROM forms").fetchone()
conn.close()
return row["cnt"]
def db_save_generated_route(rep_name, day_name, stops_data):
"""Save a generated route for accountability tracking."""
conn = get_db()
conn.execute("""
INSERT INTO generated_routes (rep_name, day_name, generated_at, total_stops, stops_json)
VALUES (?, ?, ?, ?, ?)
""", (
rep_name, day_name, str(datetime.datetime.now()),
len(stops_data), json.dumps(stops_data)
))
conn.commit()
conn.close()
def db_get_route_history(rep_name, limit=10):
"""Get recent generated routes for a rep."""
conn = get_db()
rows = conn.execute("""
SELECT day_name, generated_at, total_stops
FROM generated_routes
WHERE rep_name = ?
ORDER BY generated_at DESC
LIMIT ?
""", (rep_name, limit)).fetchall()
conn.close()
return [dict(r) for r in rows]
# ==============================================================================
# INCREMENTAL SYNC FUNCTIONS (the key speed improvement)
# ==============================================================================
def sync_clients_to_db(api_user, api_pass, status_placeholder):
"""Full client sync β downloads all clients and upserts into SQLite."""
raw_clients = fetch_all_clients(api_user, api_pass, status_placeholder)
count = db_upsert_clients(raw_clients, status_placeholder)
db_set_meta("last_client_sync", str(datetime.datetime.now()))
return count
def sync_forms_incremental(api_user, api_pass, start_date, end_date, status_placeholder):
"""
Incremental form sync β only pulls forms newer than what's already in the DB.
On first run, does a full scan. On subsequent runs, starts from the last known form ID.
"""
# Get the last form ID we stored
last_form_id = db_get_meta("last_form_cursor", "0")
status_placeholder.info(f"π‘ **Incremental sync starting from cursor {last_form_id}β¦**")
# Use the existing pagination engine but feed results into SQL
seen_form_ids = set()
start_ts = int(datetime.datetime.combine(start_date, datetime.datetime.min.time()).timestamp())
end_ts = int(datetime.datetime.combine(end_date, datetime.datetime.max.time()).timestamp())
last_id = last_form_id
total_scanned = 0
total_new = 0
same_cursor = 0
page_count = 0
while page_count < MAX_PAGES:
page_count += 1
status_placeholder.info(
f"π‘ **Scanning Formsβ¦ ({total_scanned:,} scanned | "
f"{total_new:,} new | page {page_count})**"
)
url = f"https://api.repsly.com/v3/export/forms/{last_id}?count=200"
_, data = _get_with_retry(url, (api_user, api_pass), status_placeholder, f"forms page {page_count}")
if data is None:
break
batch = data.get("Forms", data.get("FormResults", []))
if not batch:
break
total_scanned += len(batch)
count_parseable = 0
count_future = 0
# Filter by date range
valid_forms = []
for form in batch:
form_id = _safe_str(
form.get("FormID") or form.get("FormResultID")
or form.get("formResultId") or form.get("ID")
)
if form_id and form_id in seen_form_ids:
continue
if form_id:
seen_form_ids.add(form_id)
record_ts = _parse_form_timestamp(form)
if record_ts is not None:
count_parseable += 1
if record_ts > end_ts:
count_future += 1
if record_ts is not None and (record_ts < start_ts or record_ts > end_ts):
continue
valid_forms.append(form)
# Batch insert into SQLite
if valid_forms:
new_count = db_upsert_forms(valid_forms)
total_new += new_count
if count_parseable > 0 and count_future == count_parseable:
break
new_id = extract_pagination_key(data, "lastid")
if not new_id or new_id == last_id:
same_cursor += 1
if same_cursor >= MAX_SAME_CURSOR:
break
else:
same_cursor = 0
last_id = new_id
# Save cursor for next incremental sync
db_set_meta("last_form_cursor", last_id)
db_set_meta("last_form_sync", str(datetime.datetime.now()))
status_placeholder.info(
f"β
**Sync complete.** Scanned {total_scanned:,} records, "
f"added {total_new:,} new forms to database."
)
return total_new
# ==============================================================================
# UTILITY FUNCTIONS
# ==============================================================================
def haversine_miles(lat1, lon1, lat2, lon2):
R = 3958.8
lat1, lon1, lat2, lon2 = map(math.radians, [lat1, lon1, lat2, lon2])
a = math.sin((lat2 - lat1) / 2) ** 2 + math.cos(lat1) * math.cos(lat2) * math.sin((lon2 - lon1) / 2) ** 2
return R * 2 * math.asin(math.sqrt(a))
def parse_single_time(time_str, default_val):
t_str = str(time_str).strip().lower()
if not t_str or t_str in ['nan', 'none', '']:
return default_val
try:
t = pd.to_datetime(t_str)
if pd.isna(t):
raise ValueError
return int(t.hour * 60 + t.minute)
except Exception:
pass
match = re.search(r'(\d{1,2}):?(\d{2})?\s*(am|pm)?', t_str)
if match:
hr = int(match.group(1))
mn = int(match.group(2) or 0)
ampm = match.group(3)
if ampm == 'pm' and hr < 12:
hr += 12
if ampm == 'am' and hr == 12:
hr = 0
total = hr * 60 + mn
return total if total <= 1439 else default_val
return default_val
def parse_time_window(time_str):
t = str(time_str).strip().lower().replace('.', '')
if t in ['nan', 'none', '']:
return (420, 2880)
parts = re.split(r'[-/]| to ', t)
start = parse_single_time(parts[0], 420)
end = parse_single_time(parts[1], 2880) if len(parts) > 1 and parts[1].strip() else 2880
if end < start:
end += 1440
return (start, end)
def format_time(minutes):
display_hour = (int(minutes) // 60) % 24
display_min = int(minutes) % 60
am_pm = "AM" if display_hour < 12 else "PM"
clock_hour = display_hour if display_hour <= 12 else display_hour - 12
if clock_hour == 0:
clock_hour = 12
return f"{clock_hour:02d}:{display_min:02d} {am_pm}"
# ==============================================================================
# π§ API ENGINE WITH RETRY LOGIC
# ==============================================================================
MAX_RETRIES = 5
RETRY_BACKOFF = [2, 4, 8, 15, 30]
MAX_SAME_CURSOR = 5
MAX_PAGES = 5000
def _safe_str(value):
if value is None:
return ""
s = str(value).strip()
return "" if s.lower() in ("none", "null", "") else s
def extract_pagination_key(data_dict, target_key):
"""Search for a pagination key in the API response."""
if not isinstance(data_dict, dict):
return ""
target_lower = target_key.lower()
# Check MetaCollectionResult first
meta_raw = data_dict.get("MetaCollectionResult") or data_dict.get("metaCollectionResult")
if isinstance(meta_raw, dict):
for k, v in meta_raw.items():
if str(k).lower() == target_lower:
return _safe_str(v)
# Check top-level
for k, v in data_dict.items():
if str(k).lower() == target_lower:
return _safe_str(v)
# Check one level nested
for k, v in data_dict.items():
if isinstance(v, dict):
for sub_k, sub_v in v.items():
if str(sub_k).lower() == target_lower:
return _safe_str(sub_v)
return ""
def _extract_total_count(data_dict):
if not isinstance(data_dict, dict):
return None
meta_raw = data_dict.get("MetaCollectionResult") or data_dict.get("metaCollectionResult")
if isinstance(meta_raw, dict):
for k, v in meta_raw.items():
if str(k).lower() == "totalcount":
try:
return int(v)
except (ValueError, TypeError):
pass
return None
def _parse_form_timestamp(form):
raw_ts = form.get("Timestamp") or form.get("timestamp")
if raw_ts is not None:
try:
return int(raw_ts)
except (ValueError, TypeError):
pass
for key in ("DateAndTime", "dateAndTime", "Date", "VisitStart", "visitStart"):
raw_dt = form.get(key)
if raw_dt:
try:
return int(pd.to_datetime(str(raw_dt), utc=True).timestamp())
except Exception:
pass
return None
def _get_with_retry(url, auth, status_placeholder, context_label):
for attempt in range(MAX_RETRIES):
try:
res = requests.get(url, auth=auth, timeout=45)
if res.status_code == 200:
try:
return res, res.json()
except ValueError:
if attempt < MAX_RETRIES - 1:
status_placeholder.warning(f"β οΈ Malformed JSON on {context_label} β Retryingβ¦")
time.sleep(RETRY_BACKOFF[attempt])
continue
if res.status_code == 429:
retry_after = max(int(res.headers.get("Retry-After", 60)), 10)
status_placeholder.warning(f"β³ Rate limited. Waiting {retry_after}sβ¦")
time.sleep(retry_after)
continue
if attempt < MAX_RETRIES - 1:
status_placeholder.warning(f"β οΈ HTTP {res.status_code} on {context_label} β Retryingβ¦")
time.sleep(RETRY_BACKOFF[attempt])
except requests.RequestException as e:
if attempt < MAX_RETRIES - 1:
status_placeholder.warning(f"β οΈ Network error: {type(e).__name__} β Retryingβ¦")
time.sleep(RETRY_BACKOFF[attempt])
return None, None
# ==============================================================================
# CLIENT & REP FIELD EXTRACTION
# ==============================================================================
_REP_FIELD_CANDIDATES = [
"RepresentativeName", "representativeName",
"Representative", "representative",
"RepresentativeCode", "representativeCode",
"Rep", "rep",
"AssignedTo", "assignedTo",
"SalesRep", "salesRep",
"Agent", "agent",
]
def _extract_rep_name(client_dict):
"""Try every known field name for the representative assignment."""
for field in _REP_FIELD_CANDIDATES:
val = client_dict.get(field)
if val is not None:
s = str(val).strip()
if s and s.lower() not in ("none", "null", ""):
return s
# Check nested Representative objects
rep_obj = client_dict.get("Representative") or client_dict.get("representative")
if isinstance(rep_obj, dict):
return str(rep_obj.get("Name", rep_obj.get("name", ""))).strip()
return ""
def _extract_client_code(client_dict):
"""Reliably extract a unique client identifier."""
for field in ["ClientCode", "clientCode", "Code", "code", "ClientID", "clientId", "ID", "id"]:
val = client_dict.get(field)
if val is not None:
s = str(val).strip()
if s and s.lower() not in ("none", "null", "", "unk"):
return s
return ""
# ==============================================================================
# CLIENT FETCHER
# ==============================================================================
def fetch_all_clients(api_user, api_pass, status_placeholder):
clients = []
seen = set()
last_id = "0"
same_cursor = 0
page_count = 0
total_count = None
while page_count < MAX_PAGES:
page_count += 1
prog = f"{len(clients):,}" + (f" / {total_count:,}" if total_count else "")
status_placeholder.info(f"π‘ **Downloading Accountsβ¦ ({prog} | page {page_count})**")
url = f"https://api.repsly.com/v3/export/clients/{last_id}?count=200"
_, data = _get_with_retry(url, (api_user, api_pass), status_placeholder, f"clients page {page_count}")
if data is None:
break
if total_count is None:
total_count = _extract_total_count(data)
batch = data.get("Clients", [])
if not batch:
break
for c in batch:
cid = _extract_client_code(c)
if cid and cid in seen:
continue
if cid:
seen.add(cid)
clients.append(c)
new_id = extract_pagination_key(data, "lasttimestamp") or extract_pagination_key(data, "lastid")
if not new_id or new_id == last_id:
same_cursor += 1
if same_cursor >= MAX_SAME_CURSOR:
break
else:
same_cursor = 0
last_id = new_id
return clients
# ==============================================================================
# FORMS FETCHER β TRACKS LAST VISIT DATES + ORDER VOLUMES
# ==============================================================================
def fetch_all_forms(api_user, api_pass, start_date, end_date, starting_id, status_placeholder):
"""
Returns: (order_forms, rep_client_map, last_visit_map)
- order_forms: list of order dicts with Rep, Client, Cases
- rep_client_map: {rep_lower: [client_codes]} from ALL form types
- last_visit_map: {rep_lower: {client_code: "YYYY-MM-DD"}}
"""
order_forms = []
rep_client_map = {}
last_visit_map = {}
seen_form_ids = set()
start_ts = int(datetime.datetime.combine(start_date, datetime.datetime.min.time()).timestamp())
end_ts = int(datetime.datetime.combine(end_date, datetime.datetime.max.time()).timestamp())
last_id = str(starting_id).strip() if starting_id else "0"
total_scanned = 0
same_cursor = 0
page_count = 0
while page_count < MAX_PAGES:
page_count += 1
status_placeholder.info(
f"π‘ **Scanning Formsβ¦ ({total_scanned:,} scanned | "
f"{len(order_forms):,} orders | page {page_count})**"
)
url = f"https://api.repsly.com/v3/export/forms/{last_id}?count=200"
_, data = _get_with_retry(url, (api_user, api_pass), status_placeholder, f"forms page {page_count}")
if data is None:
break
batch = data.get("Forms", data.get("FormResults", []))
if not batch:
break
total_scanned += len(batch)
count_parseable = 0
count_future = 0
for form in batch:
form_id = _safe_str(
form.get("FormID") or form.get("FormResultID")
or form.get("formResultId") or form.get("ID")
)
if form_id:
if form_id in seen_form_ids:
continue
seen_form_ids.add(form_id)
record_ts = _parse_form_timestamp(form)
if record_ts is not None:
count_parseable += 1
if record_ts > end_ts:
count_future += 1
if record_ts is not None and (record_ts < start_ts or record_ts > end_ts):
continue
rep_name = str(form.get("RepresentativeName", "")).strip()
form_name = str(form.get("FormName", "")).lower()
client_code = str(form.get("ClientCode", "")).strip()
# Track ALL client codes per rep (for territory mapping)
if rep_name and client_code:
rep_key = rep_name.lower().strip()
rep_client_map.setdefault(rep_key, set()).add(client_code)
# Track last visit date from ANY form type
if record_ts is not None:
visit_date = datetime.datetime.utcfromtimestamp(record_ts).strftime("%Y-%m-%d")
if rep_key not in last_visit_map:
last_visit_map[rep_key] = {}
existing = last_visit_map[rep_key].get(client_code, "1970-01-01")
if visit_date > existing:
last_visit_map[rep_key][client_code] = visit_date
# Separately track order forms for case counting
if "order" in form_name:
case_count = 0
for item in form.get("Items", []):
title = str(item.get("Title", "")).lower()
if "case" in title:
try:
case_count += int(re.search(r'\d+', str(item.get("Value", "0"))).group())
except (AttributeError, ValueError):
pass
order_forms.append({
"Rep": rep_name,
"Client": client_code,
"Cases": case_count,
"FormName": form_name,
})
if count_parseable > 0 and count_future == count_parseable:
break
new_id = extract_pagination_key(data, "lastid")
if not new_id or new_id == last_id:
same_cursor += 1
if same_cursor >= MAX_SAME_CURSOR:
break
else:
same_cursor = 0
last_id = new_id
# Convert sets to lists for JSON serialization
rep_client_map_out = {k: list(v) for k, v in rep_client_map.items()}
return order_forms, rep_client_map_out, last_visit_map
# ==============================================================================
# MAIN APP
# ==============================================================================
st.title("β‘ Repsly Operations Command Center")
app_mode = st.sidebar.radio(
"βοΈ Select Operating Mode",
["π Driver Dispatch (Warehouse)", "π€ Sales Territories (Field)"]
)
st.sidebar.divider()
# ==============================================================================
# MODE 1: DRIVER DISPATCH (THE GOLD STANDARD WAREHOUSE ROUTER)
# ==============================================================================
if app_mode == "π Driver Dispatch (Warehouse)":
st.subheader("Warehouse Delivery Routing")
st.write("Upload Repsly exports to build perfectly constrained truck routes and sync Excel Master Sheets.")
WAREHOUSES = {
"Greensboro (GSO)": {"address": "156 Industrial Ave, Greensboro, NC 27406", "lat": 36.046, "lon": -79.773},
"Wilmington (WILM)": {"address": "1536 Castle Hayne Rd, Wilmington, NC 28401", "lat": 34.269, "lon": -77.935},
"Sumter (SUMT)": {"address": "50 Commerce St, Sumter, SC 29150", "lat": 33.918, "lon": -80.328},
}
FALLBACK_DRIVE_TIME = 15
uploaded_file = st.file_uploader("Drop your Repsly CSV or Excel file here", type=["csv", "xlsx"])
if uploaded_file is not None:
try:
if uploaded_file.name.endswith('.xlsx'):
df = pd.read_excel(uploaded_file)
else:
df = pd.read_csv(uploaded_file, sep=';', encoding='utf-8')
except Exception:
uploaded_file.seek(0)
df = pd.read_csv(uploaded_file, sep=';', encoding='latin1')
# --- AUTO-DETECT COLUMNS ---
name_col = next((c for c in df.columns if ('store' in c.lower() or 'place' in c.lower() or 'name' in c.lower()) and 'rep' not in c.lower() and 'id' not in c.lower()), None)
street_col = next((c for c in df.columns if 'address' in c.lower() or 'street' in c.lower()), None)
city_col = next((c for c in df.columns if 'city' in c.lower()), None)
state_col = next((c for c in df.columns if 'state' in c.lower() or 'province' in c.lower()), None)
zip_col = next((c for c in df.columns if 'zip' in c.lower() or 'postal' in c.lower()), None)
rep_cols = [c for c in df.columns if 'rep' in c.lower()]
lat_col = next((c for c in df.columns if 'latitude' in c.lower()), None)
lon_col = next((c for c in df.columns if 'longitude' in c.lower()), None)
open_cols = [c for c in df.columns if ('hour' in c.lower() or 'operation' in c.lower() or 'open' in c.lower() or 'start' in c.lower()) and 'visit' not in c.lower() and 'http' not in c.lower()]
cases_col = next((c for c in df.columns if 'case' in c.lower()), None)
has_rec_col = next((c for c in df.columns if 'does this store have a receiving' in c.lower() or 'have a receiving' in c.lower()), None)
rec_window_col = next((c for c in df.columns if 'enter receiving window' in c.lower() or ('receiving window' in c.lower() and 'does' not in c.lower())), None)
rep_col = None
if rep_cols:
name_reps = [c for c in rep_cols if 'name' in c.lower()]
rep_col = name_reps[0] if name_reps else rep_cols[0]
date_col = next((c for c in df.columns if 'date' in c.lower() or 'scheduled' in c.lower()), None)
open_col = open_cols[0] if open_cols else 'Auto_Open'
if not open_cols:
df['Auto_Open'] = '07:00 AM'
id_pattern = re.compile(r'[A-Za-z]{2}\d{4}')
id_col_fallback = next((c for c in df.columns if 'place id' in c.lower() or 'customer id' in c.lower() or 'client id' in c.lower()), None)
if not id_col_fallback:
id_col_fallback = next((c for c in df.columns if 'id' == c.lower().strip() or ' id' in c.lower()), None)
if date_col:
df['Parsed_Date'] = pd.to_datetime(df[date_col], errors='coerce').dt.date
valid_dates = df['Parsed_Date'].dropna().unique()
else:
valid_dates = []
# --- DISPATCH CONTROL CENTER ---
st.divider()
st.subheader("π οΈ Dispatch Control Center")
all_reps = sorted(df[rep_col].dropna().astype(str).unique().tolist()) if rep_col else []
if "selected_reps" not in st.session_state:
st.session_state.selected_reps = all_reps
col_w, col_r, col_d = st.columns(3)
with col_w:
selected_warehouse_name = st.selectbox("π’ Starting Warehouse", list(WAREHOUSES.keys()))
START_ADDRESS = WAREHOUSES[selected_warehouse_name]["address"]
st.caption(f"π *{START_ADDRESS}*")
with col_r:
if all_reps:
r1, r2 = st.columns(2)
with r1:
if st.button("βοΈ Select All Reps", key="rep_all", use_container_width=True):
st.session_state.selected_reps = all_reps
with r2:
if st.button("β Clear Reps", key="rep_clear", use_container_width=True):
st.session_state.selected_reps = []
selected_reps = st.multiselect("π€ Filter by Representative", options=all_reps, key="selected_reps")
else:
selected_reps = []
st.info("No Representative column found.")
with col_d:
if len(valid_dates) > 0:
min_date, max_date = min(valid_dates), max(valid_dates)
selected_dates = st.date_input("π
Select Date Range", value=(min_date, min_date), min_value=min_date, max_value=max_date)
else:
selected_dates = []
st.info("No readable dates found.")
# --- FILTER DATA ---
df_filtered = df[df[rep_col].astype(str).isin(selected_reps)].copy() if selected_reps else df.iloc[0:0].copy()
if len(valid_dates) > 0 and not df_filtered.empty:
if isinstance(selected_dates, tuple) and len(selected_dates) == 2:
df_filtered = df_filtered[(df_filtered['Parsed_Date'] >= selected_dates[0]) & (df_filtered['Parsed_Date'] <= selected_dates[1])]
elif isinstance(selected_dates, tuple) and len(selected_dates) == 1:
df_filtered = df_filtered[df_filtered['Parsed_Date'] == selected_dates[0]]
elif not isinstance(selected_dates, tuple):
df_filtered = df_filtered[df_filtered['Parsed_Date'] == selected_dates]
# --- PARSE STORE DATA ---
clean_ids, clean_names, full_addresses = [], [], []
lats, lons, service_times, window_texts, final_time_windows = [], [], [], [], []
for _, row in df_filtered.iterrows():
raw_name = str(row[name_col]) if name_col and pd.notna(row[name_col]) else "Unknown Store"
match = id_pattern.search(" ".join(row.astype(str)))
c_id = match.group(0).upper() if match else (str(row[id_col_fallback]) if id_col_fallback and pd.notna(row[id_col_fallback]) else "N/A")
if c_id != "N/A" and c_id in raw_name:
raw_name = raw_name.replace(c_id, "").replace("-", "").strip()
clean_ids.append(c_id)
clean_names.append(raw_name)
addr_parts = [str(row[c]).strip() for c in [street_col, city_col] if c and pd.notna(row[c])]
state_zip = " ".join([str(row[c]).strip() for c in [state_col, zip_col] if c and pd.notna(row[c])]).strip()
if state_zip:
addr_parts.append(state_zip)
full_addresses.append(", ".join(addr_parts) if addr_parts else "Address not provided")
lats.append(row[lat_col] if lat_col and pd.notna(row[lat_col]) else None)
lons.append(row[lon_col] if lon_col and pd.notna(row[lon_col]) else None)
case_count = int(re.search(r'\d+', str(row[cases_col])).group()) if cases_col and pd.notna(row[cases_col]) else 10
service_times.append((case_count * 1) + 5)
has_rec = str(row[has_rec_col]).strip().lower() in ['yes', 'y', 'true', '1'] if has_rec_col and pd.notna(row[has_rec_col]) else False
if has_rec and rec_window_col and pd.notna(row[rec_window_col]):
w_start, w_end = parse_time_window(row[rec_window_col])
window_texts.append(f"{format_time(w_start)} - {format_time(w_end)} (Strict)")
final_time_windows.append((w_start, w_end))
else:
w_start = parse_single_time(row[open_col], 420)
window_texts.append(f"{format_time(w_start)} (Standard)")
final_time_windows.append((w_start, 2880))
df_filtered['Clean_ID'] = clean_ids
df_filtered['Clean_Name'] = clean_names
df_filtered['Full_Address'] = full_addresses
df_filtered['Lat'] = lats
df_filtered['Lon'] = lons
df_filtered['Service_Time'] = service_times
df_filtered['Rec_Window'] = window_texts
df_filtered['Tuple_Window'] = final_time_windows
# Texas exclusion filter
if not df_filtered.empty:
texas_mask = (
df_filtered.astype(str).apply(lambda x: ' '.join(x), axis=1)
.str.contains(r'\bTX\b|Texas', flags=re.IGNORECASE, regex=True)
| df_filtered['Clean_ID'].str.upper().str.startswith('TX')
)
df_filtered = df_filtered[~texas_mask].sort_values(by=['Clean_ID', 'Clean_Name']).reset_index(drop=True)
if df_filtered.empty and not df.empty:
st.info("No stores match your current filters.")
else:
# --- STORE SELECTION EDITOR ---
st.write("π **Select Orders to Route**")
if "editor_key" not in st.session_state:
st.session_state.editor_key = 0
if "toggle_state" not in st.session_state:
st.session_state.toggle_state = True
b1, b2, _ = st.columns([2, 2, 8])
if b1.button("βοΈ Select All Stores", use_container_width=True):
st.session_state.toggle_state = True
st.session_state.editor_key += 1
if b2.button("β Deselect All Stores", use_container_width=True):
st.session_state.toggle_state = False
st.session_state.editor_key += 1
editor_df = pd.DataFrame({
"Route": [st.session_state.toggle_state] * len(df_filtered),
"β Pin 1st": [False] * len(df_filtered),
"Customer ID": df_filtered['Clean_ID'],
"Store Name": df_filtered['Clean_Name'],
"Address": df_filtered['Full_Address'],
"Required Window": df_filtered['Rec_Window'],
"Budgeted Mins": df_filtered['Service_Time'],
})
if rep_col:
editor_df["Assigned Rep"] = df_filtered[rep_col]
edited_df = st.data_editor(
editor_df, key=f"editor_{st.session_state.editor_key}",
hide_index=True, use_container_width=True,
disabled=["Customer ID", "Store Name", "Address", "Assigned Rep", "Required Window", "Budgeted Mins"]
)
df_filtered["Route"] = edited_df["Route"]
df_filtered["β Pin 1st"] = edited_df["β Pin 1st"]
df_final = df_filtered[df_filtered["Route"] == True]
st.divider()
# --- ROUTE OPTIMIZATION ---
if st.button("π Generate Optimized Route", type="primary"):
if df_final.empty:
st.warning("β οΈ No orders selected! Please assign a Rep and select stores to route.")
else:
with st.spinner('Optimizing heavily constrained route...'):
wh_data = WAREHOUSES[selected_warehouse_name]
node_details = [{
"id": "WAREHOUSE", "name": f"Start: {selected_warehouse_name}",
"address": START_ADDRESS, "lat": wh_data["lat"],
"lon": wh_data["lon"], "service_time": 0,
}]
time_windows = [(240, 540)]
pinned_node_idx = None
for row_idx, row in df_final.reset_index(drop=True).iterrows():
node_details.append({
"id": row['Clean_ID'], "name": row['Clean_Name'],
"address": row['Full_Address'], "lat": row['Lat'],
"lon": row['Lon'], "service_time": row['Service_Time'],
})
time_windows.append(row['Tuple_Window'])
if row['β Pin 1st'] == True:
pinned_node_idx = row_idx + 1
size = len(node_details)
time_matrix = []
for i in range(size):
row = []
for j in range(size):
if i == j:
row.append(0)
else:
l1, o1 = node_details[i]['lat'], node_details[i]['lon']
l2, o2 = node_details[j]['lat'], node_details[j]['lon']
if pd.notna(l1) and pd.notna(o1) and pd.notna(l2) and pd.notna(o2):
row.append(int(haversine_miles(l1, o1, l2, o2) * 1.2 + 10))
else:
row.append(FALLBACK_DRIVE_TIME)
time_matrix.append(row)
manager = pywrapcp.RoutingIndexManager(size, 1, 0)
routing = pywrapcp.RoutingModel(manager)
def time_callback(f, t):
fn, tn = manager.IndexToNode(f), manager.IndexToNode(t)
return time_matrix[fn][tn] + node_details[tn]["service_time"]
transit_idx = routing.RegisterTransitCallback(time_callback)
routing.SetArcCostEvaluatorOfAllVehicles(transit_idx)
routing.AddDimension(transit_idx, 1440, 2880, False, 'Time')
time_dim = routing.GetDimensionOrDie('Time')
for i, window in enumerate(time_windows):
time_dim.CumulVar(manager.NodeToIndex(i)).SetRange(window[0], window[1])
for i in range(1, size):
routing.AddDisjunction([manager.NodeToIndex(i)], 100000)
if pinned_node_idx is not None:
routing.solver().Add(routing.NextVar(routing.Start(0)) == pinned_node_idx)
st.session_state.pinned_node_name = node_details[pinned_node_idx]['name']
else:
st.session_state.pinned_node_name = None
routing.AddVariableMinimizedByFinalizer(time_dim.CumulVar(routing.End(0)))
routing.AddVariableMaximizedByFinalizer(time_dim.CumulVar(routing.Start(0)))
search_parameters = pywrapcp.DefaultRoutingSearchParameters()
search_parameters.first_solution_strategy = routing_enums_pb2.FirstSolutionStrategy.PATH_CHEAPEST_ARC
search_parameters.local_search_metaheuristic = routing_enums_pb2.LocalSearchMetaheuristic.GUIDED_LOCAL_SEARCH
search_parameters.time_limit.seconds = 2
solution = routing.SolveWithParameters(search_parameters)
if solution:
st.session_state.route_success = True
st.session_state.dropped_stores = [
node_details[i]["name"] for i in range(1, manager.GetNumberOfNodes())
if solution.Value(routing.NextVar(manager.NodeToIndex(i))) == manager.NodeToIndex(i)
]
route_seq = []
index = routing.Start(0)
while not routing.IsEnd(index):
node_idx = manager.IndexToNode(index)
route_seq.append((node_idx, solution.Value(time_dim.CumulVar(index))))
index = solution.Value(routing.NextVar(index))
end_time = solution.Value(time_dim.CumulVar(index))
route_seq.append((manager.IndexToNode(index), end_time))
st.session_state.end_time = end_time
route_data = []
for step, (node, arr_time) in enumerate(route_seq):
if step == 0:
route_data.append({"Stop": "Start", "Customer ID": node_details[node]["id"], "Location Name": node_details[node]["name"], "Address": node_details[node]["address"], "Time": f"Leave: {format_time(arr_time)}", "Drive Time": "-", "lat": node_details[node]["lat"], "lon": node_details[node]["lon"]})
elif step == len(route_seq) - 1:
drive_time = time_matrix[route_seq[step-1][0]][node]
route_data.append({"Stop": "Finish", "Customer ID": node_details[0]["id"], "Location Name": "Return to Warehouse", "Address": node_details[0]["address"], "Time": f"Arrive: {format_time(arr_time)}", "Drive Time": f"{drive_time} mins", "lat": node_details[0]["lat"], "lon": node_details[0]["lon"]})
else:
p_node, p_arr = route_seq[step-1][0], route_seq[step-1][1]
drive_time = time_matrix[p_node][node]
p_svc = node_details[p_node]["service_time"]
wait = arr_time - (p_arr + p_svc + drive_time)
d_str = f"{drive_time} mins" + (f" (+{wait} min wait)" if wait > 0 else "")
route_data.append({"Stop": f"#{step}", "Customer ID": node_details[node]["id"], "Location Name": node_details[node]["name"], "Address": node_details[node]["address"], "Time": f"Service Begins: {format_time(arr_time)}", "Drive Time": d_str, "lat": node_details[node]["lat"], "lon": node_details[node]["lon"]})
st.session_state.final_route_table = route_data
else:
st.session_state.route_success = False
st.session_state.final_route_table = []
st.error("β No route found. The algorithm couldn't piece together a viable path.")
# --- DISPLAY RESULTS ---
if st.session_state.get("route_success", False):
st.success("β
Route Optimized Successfully!")
if st.session_state.get("pinned_node_name"):
st.success(f"π Hard-Pinned First Stop: {st.session_state.pinned_node_name}")
if st.session_state.get("dropped_stores"):
st.warning(f"β οΈ **OVERFLOW WARNING:** Skipped: **{', '.join(st.session_state.dropped_stores)}**")
st.dataframe(
pd.DataFrame(st.session_state.final_route_table).drop(columns=['lat', 'lon']),
use_container_width=True, hide_index=True,
)
st.info(f"π **Estimated End of Shift:** {format_time(st.session_state.end_time)}")
# --- ORDER SHEET REORGANIZER ---
st.divider()
st.subheader("π¦ Order Sheet Reorganizer")
order_book_file = st.file_uploader(
"Upload Warehouse Excel Workbook (.xlsx) to sync ROUTE ORDER column",
type=["xlsx"], key="excel_uploader",
)
if order_book_file:
with st.spinner("Executing surgical formula-safe update..."):
try:
b_val = order_book_file.getvalue()
wb_vals = openpyxl.load_workbook(io.BytesIO(b_val), data_only=True)
wb_orig = openpyxl.load_workbook(io.BytesIO(b_val), data_only=False)
sheet_name = next((s for s in wb_vals.sheetnames if 'DRIVER' in s.upper()), wb_vals.sheetnames[0])
ws_vals = wb_vals[sheet_name]
ws_orig = wb_orig[sheet_name]
acc_col, ord_col, head_row = None, None, None
for r_idx in range(1, 16):
for c_idx in range(1, ws_vals.max_column + 1):
val_str = str(ws_vals.cell(row=r_idx, column=c_idx).value).upper() if ws_vals.cell(row=r_idx, column=c_idx).value else ""
if 'ACCOUNT NAME' in val_str:
acc_col, head_row = c_idx, r_idx
if 'ROUTE ORDER' in val_str:
ord_col = c_idx
if acc_col and ord_col:
break
if acc_col and ord_col and head_row:
mapping_log = []
ai_stops = [
{"num": int(str(r["Stop"]).replace("#", "")),
"id": re.sub(r'[^A-Z0-9]', '', str(r.get("Customer ID", "")).upper()),
"clean_name": re.sub(r'[^A-Z0-9]', '', str(r.get("Location Name", "")).upper())}
for r in st.session_state.final_route_table if "#" in str(r.get("Stop", ""))
]
for r_idx in range(head_row + 1, ws_vals.max_row + 1):
excel_name_raw = ws_vals.cell(row=r_idx, column=acc_col).value
if not excel_name_raw or 'TOTAL' in str(excel_name_raw).upper():
continue
acc_name_str = str(excel_name_raw).upper()
clean_xl = re.sub(r'[^A-Z0-9]', '', acc_name_str)
match_stop, match_logic = None, "Unmapped"
c_id_match = re.search(r'[A-Z]{2}\d{4}', acc_name_str)
c_id = c_id_match.group(0) if c_id_match else None
if c_id:
for ai in ai_stops:
if ai["id"] == c_id:
match_stop = ai["num"]
match_logic = f"Exact ID Match ({c_id})"
break
if match_stop is None:
highest_ratio = 0.0
for ai in ai_stops:
ratio = difflib.SequenceMatcher(None, clean_xl, ai["clean_name"]).ratio()
if ratio > highest_ratio:
highest_ratio = ratio
match_stop = ai["num"]
if highest_ratio > 0.45:
match_logic = f"Fuzzy Match ({int(highest_ratio * 100)}%)"
else:
match_stop = None
mapping_log.append({
"Excel Row": r_idx,
"Name Seen": acc_name_str,
"Assigned Stop": match_stop if match_stop is not None else "β MAPPING FAILED",
"Logic Used": match_logic,
})
if match_stop is not None:
target_cell = ws_orig.cell(row=r_idx, column=ord_col)
if type(target_cell).__name__ == 'MergedCell':
for m_range in ws_orig.merged_cells.ranges:
if target_cell.coordinate in m_range:
ws_orig.cell(row=m_range.min_row, column=m_range.min_col).value = int(match_stop)
break
else:
target_cell.value = int(match_stop)
output = io.BytesIO()
wb_orig.save(output)
st.success("π Route Order numbers successfully overwritten!")
st.download_button(
"π₯ Download Updated Order Workbook", output.getvalue(),
"Optimized_Warehouse_Orders.xlsx",
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
)
with st.expander("π Click to view X-Ray Mapping Log"):
st.write("**Formulas not updating?** Hit `F9` or 'Enable Editing' in Excel to calculate.")
st.dataframe(pd.DataFrame(mapping_log), use_container_width=True)
else:
st.error("Could not locate 'ACCOUNT NAME' or 'ROUTE ORDER' columns.")
except Exception as e:
st.error(f"Error updating workbook: {e}")
# --- VISUAL ROUTE MAP ---
st.divider()
st.subheader("πΊοΈ Visual Route Map")
map_points, failed_addresses = [], []
for row in st.session_state.final_route_table:
if pd.notna(row.get("lat")) and pd.notna(row.get("lon")):
lbl = str(row["Stop"]).replace("#", "")
lbl = "S" if lbl == "Start" else "F" if lbl == "Finish" else lbl
map_points.append({
"name": row["Location Name"], "address": row["Address"],
"coordinates": [float(row["lon"]), float(row["lat"])],
"dot_label": lbl,
})
elif row["Location Name"] not in failed_addresses:
failed_addresses.append(row["Location Name"])
if failed_addresses:
st.warning(f"β οΈ Missing GPS Data: **{', '.join(failed_addresses)}**")
if len(map_points) >= 2:
avg_lon = sum(p["coordinates"][0] for p in map_points) / len(map_points)
avg_lat = sum(p["coordinates"][1] for p in map_points) / len(map_points)
layer_scatter = pdk.Layer("ScatterplotLayer", data=map_points, get_position="coordinates", get_color="[200, 30, 0, 200]", get_radius=100, radius_min_pixels=15, radius_max_pixels=25, pickable=True)
layer_path = pdk.Layer("PathLayer", data=[{"path": [p["coordinates"][:2] for p in map_points]}], get_path="path", get_color="[0, 100, 255, 150]", width_scale=20, width_min_pixels=4, get_width=8)
layer_text = pdk.Layer("TextLayer", data=map_points, get_position="coordinates", get_text="dot_label", get_color=[255, 255, 255, 255], get_size=20, get_alignment_baseline="'center'", get_text_anchor="'middle'")
st.pydeck_chart(pdk.Deck(
layers=[layer_path, layer_scatter, layer_text],
initial_view_state=pdk.ViewState(longitude=avg_lon, latitude=avg_lat, zoom=7.0, pitch=0),
tooltip={"text": "{name}\n{address}"}, map_style="light",
), use_container_width=True)
elif len(map_points) == 1:
st.error("β Need at least 2 locations with GPS to draw map.")
# ==============================================================================
# MODE 2: SALES TERRITORIES β SQL-POWERED SMART AUTO-ROUTING
# ==============================================================================
elif app_mode == "π€ Sales Territories (Field)":
REP_HOMES = {
"Julia Cameron": {"lat": 35.3942, "lon": -77.9248},
"Aaron Manning": {"lat": 35.9184, "lon": -78.8051},
"Wade Easley": {"lat": 33.9358, "lon": -80.3802},
"David Williams": {"lat": 34.6181, "lon": -79.0086},
"David Christian": {"lat": 35.6325, "lon": -77.3996},
"Charles White": {"lat": 35.0975, "lon": -81.0114},
"Dorrian Hickman": {"lat": 34.0531, "lon": -79.7995},
"Shameek Huggins": {"lat": 33.8643, "lon": -79.0881},
"Tiara Gordon": {"lat": 36.0354, "lon": -79.8662},
"Timothy": {"lat": 35.9478, "lon": -79.7539},
"Brian Milam": {"lat": 36.0152, "lon": -80.2641},
"Stanley Demeritt": {"lat": 35.1856, "lon": -78.9803},
"Michael Abuzuaiter": {"lat": 36.1364, "lon": -79.8517},
"Yousef Abuzuaiter": {"lat": 36.1364, "lon": -79.8517},
"Delmedtris Copeland": {"lat": 33.9165, "lon": -80.3014},
"Jose Herrera": {"lat": 34.9602, "lon": -78.9568},
"Frederick Gray": {"lat": 33.9401, "lon": -80.3542},
"Rolando Taylor": {"lat": 34.7431, "lon": -80.7932},
}
# ββ CHECK DATABASE STATUS βββββββββββββββββββββββββββββββββββββββββββββββββ
client_count = db_get_client_count()
form_count = db_get_form_count()
db_has_data = client_count > 0
last_client_sync = db_get_meta("last_client_sync", "Never")
last_form_sync = db_get_meta("last_form_sync", "Never")
# ββ SYNC PANEL ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
if db_has_data:
earliest, latest, _ = db_get_form_date_range()
st.success(
f"ποΈ **Database Active:** {client_count:,} accounts | {form_count:,} form records | "
f"Forms span {earliest or 'N/A'} β {latest or 'N/A'}"
)
st.caption(f"Last client sync: {last_client_sync} | Last form sync: {last_form_sync}")
else:
st.warning("ποΈ **Database is empty.** Run a Full Sync to get started.")
with st.expander("π Sync Controls", expanded=not db_has_data):
sync_col1, sync_col2 = st.columns(2)
today = datetime.date.today()
with sync_col1:
st.markdown("**π
Date Range for Form Scanning**")
sync_start = st.date_input("From", datetime.date(today.year - 1, 1, 1), key="sync_s")
sync_end = st.date_input("To", today, key="sync_e")
with sync_col2:
st.markdown("**β‘ Sync Actions**")
if st.button("π FULL SYNC (Accounts + Forms)", use_container_width=True, type="primary"):
status = st.empty()
try:
# 1. Sync reps
status.info("π‘ Downloading rep rosterβ¦")
_, rep_data = _get_with_retry(
"https://api.repsly.com/v3/export/representatives",
(API_USERNAME, API_PASSWORD), status, "representatives",
)
if rep_data:
r_data = rep_data.get("Representatives", rep_data) if isinstance(rep_data, dict) else rep_data
reps_list = sorted(list(set([
r.get("Name") for r in r_data if isinstance(r, dict) and r.get("Name")
])))
db_upsert_reps(reps_list)
# 2. Full client sync
sync_clients_to_db(API_USERNAME, API_PASSWORD, status)
# 3. Full form sync (resets cursor to start fresh)
db_set_meta("last_form_cursor", "0")
sync_forms_incremental(API_USERNAME, API_PASSWORD, sync_start, sync_end, status)
status.success("β
**Full sync complete!**")
time.sleep(1)
st.rerun()
except Exception as e:
status.error(f"β Error: {e}")
st.divider()
if db_has_data:
if st.button("β‘ QUICK SYNC (New Forms Only)", use_container_width=True):
status = st.empty()
try:
new = sync_forms_incremental(
API_USERNAME, API_PASSWORD, sync_start, sync_end, status,
)
status.success(f"β
Quick sync done. **{new:,}** new forms added.")
time.sleep(1)
st.rerun()
except Exception as e:
status.error(f"β Error: {e}")
if db_has_data:
if st.button("ποΈ Reset Database", use_container_width=True):
conn = get_db()
for table in ["clients", "forms", "sync_meta", "reps", "generated_routes"]:
conn.execute(f"DELETE FROM {table}")
conn.commit()
conn.close()
st.rerun()
# ββ ROUTE BUILDER (only if we have data) ββββββββββββββββββββββββββββββββββ
if db_has_data:
st.divider()
# Sidebar settings
with st.sidebar:
st.header("π€ Territory Settings")
all_reps = db_get_reps()
if all_reps:
selected_rep = st.selectbox("Select Sales Rep to Route", all_reps)
else:
selected_rep = st.text_input("Sales Rep Name", "Brian Milam")
if selected_rep in REP_HOMES:
start_lat = REP_HOMES[selected_rep]["lat"]
start_lon = REP_HOMES[selected_rep]["lon"]
st.success(f"π **Starting:** {selected_rep}'s Home")
else:
st.warning("β οΈ Using Greensboro default.")
start_lat, start_lon = 36.0726, -79.7919
st.divider()
max_per_day = st.slider("Max Stops Per Day", 10, 40, 25)
include_inactive = st.checkbox("Include Inactive Accounts", value=False)
# Route history
history = db_get_route_history(selected_rep, 5)
if history:
st.divider()
st.markdown("**π Recent Routes**")
for h in history:
st.caption(f"{h['day_name']} β {h['total_stops']} stops β {h['generated_at'][:16]}")
st.subheader(f"π Smart Weekly Route: {selected_rep}")
if st.button(f"π AUTO-BUILD WEEK FOR {selected_rep.upper()}", type="primary", use_container_width=True):
with st.spinner(f"Building smart routes for {selected_rep}..."):
today = datetime.date.today()
# ββ STEP 1: Pull rep's accounts from SQL (instant) ββββββββ
accounts = db_get_rep_accounts(selected_rep, include_inactive)
# Collect all client codes for cross-referencing forms
all_client_codes = []
for acct in accounts:
all_client_codes.append(acct["code"])
if acct.get("raw_client_code") and acct["raw_client_code"] != acct["code"]:
all_client_codes.append(acct["raw_client_code"])
# ββ STEP 2: Pull order volumes from SQL (instant) βββββββββ
volumes = db_get_order_volume(selected_rep, all_client_codes)
for acct in accounts:
# Check both the customer ID and the raw Repsly code
vol = (volumes.get(acct["code"])
or volumes.get(acct.get("raw_client_code", ""))
or {"orders": 0, "cases": 0})
acct["orders"] = vol["orders"]
acct["cases"] = vol["cases"]
# ββ STEP 3: Pull last visit dates from SQL (instant) ββββββ
last_visits = db_get_last_visits(selected_rep, all_client_codes)
# Get date range for frequency calculation
earliest, latest, _ = db_get_form_date_range()
if earliest and latest:
try:
s_date = datetime.datetime.strptime(earliest, "%Y-%m-%d").date()
e_date = datetime.datetime.strptime(latest, "%Y-%m-%d").date()
total_weeks = max(1.0, (e_date - s_date).days / 7.0)
except Exception:
total_weeks = 52.0
else:
total_weeks = 52.0
# ββ STEP 4: Calculate urgency scores ββββββββββββββββββββββ
FREQ_INTERVALS = {"Weekly": 7, "Bi-Weekly": 14, "Monthly": 30, "Infrequent": 60, "No Orders": 90}
for acct in accounts:
oc = acct["orders"]
acct["avg_cases"] = math.ceil(acct["cases"] / max(1, oc)) if oc > 0 else 0
acct["budget"] = 10 + acct["avg_cases"]
if oc == 0:
acct["freq"] = "No Orders"
else:
wb = total_weeks / oc
if wb <= 1.2: acct["freq"] = "Weekly"
elif wb <= 2.5: acct["freq"] = "Bi-Weekly"
elif wb <= 4.5: acct["freq"] = "Monthly"
else: acct["freq"] = "Infrequent"
target = FREQ_INTERVALS[acct["freq"]]
lv = (last_visits.get(acct["code"])
or last_visits.get(acct.get("raw_client_code", "")))
if lv:
try:
days_since = (today - datetime.datetime.strptime(lv, "%Y-%m-%d").date()).days
except Exception:
days_since = 999
acct["last"] = lv
else:
days_since = 999
acct["last"] = "Never"
acct["days_since"] = days_since
acct["target"] = target
acct["urgency"] = round(days_since / target, 2)
if not accounts:
st.error(f"β No routable accounts for '{selected_rep}'.")
with st.expander("π Debug"):
conn = get_db()
rep_lower = selected_rep.lower().strip()
total = conn.execute("SELECT COUNT(*) as c FROM clients").fetchone()["c"]
assigned = conn.execute("SELECT COUNT(*) as c FROM clients WHERE LOWER(rep_name) LIKE ?", (f"%{rep_lower}%",)).fetchone()["c"]
active = conn.execute("SELECT COUNT(*) as c FROM clients WHERE LOWER(rep_name) LIKE ? AND active = 1", (f"%{rep_lower}%",)).fetchone()["c"]
gps = conn.execute("SELECT COUNT(*) as c FROM clients WHERE LOWER(rep_name) LIKE ? AND active = 1 AND lat != 0.0 AND lon != 0.0", (f"%{rep_lower}%",)).fetchone()["c"]
conn.close()
st.markdown(f"Total: **{total:,}** | Assigned: **{assigned}** | Active: **{active}** | With GPS: **{gps}**")
else:
# ββ STEP 5: Sort by urgency, take top N βββββββββββββββ
accounts.sort(key=lambda x: -x["urgency"])
total_slots = 5 * max_per_day
routable = accounts[:total_slots]
skipped = accounts[total_slots:]
overdue = sum(1 for a in accounts if a["urgency"] > 1.0)
due_soon = sum(1 for a in accounts if 0.7 <= a["urgency"] <= 1.0)
on_track = len(accounts) - overdue - due_soon
st.markdown(
f"**{selected_rep}'s Territory:** {len(accounts)} accounts | "
f"π΄ **{overdue} overdue** | π‘ {due_soon} due soon | π’ {on_track} on track"
)
if len(accounts) > total_slots:
st.info(f"π Scheduling top **{total_slots}** most urgent of {len(accounts)} this week.")
# Data quality check
has_orders = sum(1 for a in accounts if a["orders"] > 0)
has_visits = sum(1 for a in accounts if a["last"] != "Never")
with st.expander(f"π¬ Data Quality: {has_orders}/{len(accounts)} have orders, {has_visits}/{len(accounts)} have visit dates"):
never_visited = [a for a in accounts if a["last"] == "Never"][:10]
if never_visited:
st.write(f"**Sample 'Never Visited' accounts** (showing first {len(never_visited)}):")
for a in never_visited:
st.text(f" {a['code']} β {a['name']} (raw code: {a.get('raw_client_code', 'N/A')})")
st.caption("If these should have visit data, check that the sync date range covers their last order dates.")
# ββ STEP 6: Cluster into geographic days ββββββββββββββ
df_route = pd.DataFrame(routable)
n_days = min(5, max(1, math.ceil(len(df_route) / max_per_day)))
unique_locs = len(df_route.drop_duplicates(subset=["lat", "lon"]))
if len(df_route) > n_days and unique_locs >= n_days:
kmeans = KMeans(n_clusters=n_days, random_state=42, n_init=10)
df_route["day"] = kmeans.fit_predict(df_route[["lat", "lon"]])
else:
df_route["day"] = [i % n_days for i in range(len(df_route))]
# Balance clusters
for _ in range(10):
counts = df_route["day"].value_counts()
overflow = counts[counts > max_per_day].index
if len(overflow) == 0:
break
for cd in overflow:
excess = df_route[df_route["day"] == cd].iloc[max_per_day:]
under = counts[counts < max_per_day].index
for idx in excess.index:
if len(under) > 0:
df_route.at[idx, "day"] = under[0]
counts = df_route["day"].value_counts()
under = counts[counts < max_per_day].index
# ββ STEP 7: Optimize route for each day βββββββββββββββ
day_names = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]
day_colors = [[231,76,60], [52,152,219], [46,204,113], [241,196,15], [155,89,182]]
all_day_routes = {}
for day_idx in range(n_days):
day_df = df_route[df_route["day"] == day_idx].reset_index(drop=True)
if day_df.empty:
continue
day_label = day_names[day_idx] if day_idx < 5 else f"Day {day_idx + 1}"
nodes = [{
"name": f"{selected_rep}'s Home", "lat": start_lat, "lon": start_lon,
"budget": 0, "addr": "Home", "freq": "-", "urg": "-", "last": "-", "cases": "-",
}]
for _, r in day_df.iterrows():
nodes.append({
"name": r["name"], "lat": r["lat"], "lon": r["lon"],
"budget": r["budget"], "addr": r["addr"],
"freq": r["freq"], "urg": r["urgency"],
"last": r["last"], "cases": r["avg_cases"],
})
size = len(nodes)
if size < 2:
continue
dist_matrix = [
[0 if i == j else int(haversine_miles(
nodes[i]["lat"], nodes[i]["lon"],
nodes[j]["lat"], nodes[j]["lon"]
) * 1.3 + 5)
for j in range(size)]
for i in range(size)
]
manager = pywrapcp.RoutingIndexManager(size, 1, 0)
routing = pywrapcp.RoutingModel(manager)
def t_callback(f, t, dm=dist_matrix, nd=nodes, mgr=manager):
fn, tn = mgr.IndexToNode(f), mgr.IndexToNode(t)
return dm[fn][tn] + nd[tn]["budget"]
transit_idx = routing.RegisterTransitCallback(t_callback)
routing.SetArcCostEvaluatorOfAllVehicles(transit_idx)
routing.AddDimension(transit_idx, 10000, 10000, True, "Time")
time_dim = routing.GetDimensionOrDie("Time")
search_params = pywrapcp.DefaultRoutingSearchParameters()
search_params.first_solution_strategy = routing_enums_pb2.FirstSolutionStrategy.PATH_CHEAPEST_ARC
search_params.local_search_metaheuristic = routing_enums_pb2.LocalSearchMetaheuristic.GUIDED_LOCAL_SEARCH
search_params.time_limit.seconds = 2
sol = routing.SolveWithParameters(search_params)
if sol:
route_rows = []
curr = routing.Start(0)
stop_num = 0
total_drive = 0
prev_ni = 0
while not routing.IsEnd(curr):
ni = manager.IndexToNode(curr)
cum = sol.Value(time_dim.CumulVar(curr))
if stop_num > 0:
drv = dist_matrix[prev_ni][ni]
total_drive += drv
drv_str = f"{drv} min"
else:
drv_str = "-"
urg_val = nodes[ni]["urg"]
if isinstance(urg_val, (int, float)):
if urg_val > 1.0: urg_display = f"π΄ {urg_val}"
elif urg_val >= 0.7: urg_display = f"π‘ {urg_val}"
else: urg_display = f"π’ {urg_val}"
else:
urg_display = str(urg_val)
route_rows.append({
"Stop": "π " if stop_num == 0 else f"#{stop_num}",
"Store": nodes[ni]["name"],
"Address": nodes[ni]["addr"],
"ETA": format_time(cum + 480),
"Drive": drv_str,
"Service": f"{nodes[ni]['budget']}m" if stop_num > 0 else "-",
"Frequency": nodes[ni]["freq"],
"Urgency": urg_display,
"Last Visit": nodes[ni]["last"],
"Avg Cases": nodes[ni]["cases"],
"lat": nodes[ni]["lat"],
"lon": nodes[ni]["lon"],
})
prev_ni = ni
curr = sol.Value(routing.NextVar(curr))
stop_num += 1
all_day_routes[day_label] = {
"rows": route_rows,
"stops": stop_num - 1,
"drive": total_drive,
"color": day_colors[day_idx % 5],
}
# Save route to database for accountability
db_save_generated_route(selected_rep, day_label, route_rows)
# ββ STEP 8: Display Monday-Friday Tabs ββββββββββββββββ
if all_day_routes:
total_stops = sum(d["stops"] for d in all_day_routes.values())
st.success(f"β
**Week built!** {total_stops} stops across {len(all_day_routes)} days for {selected_rep}")
tabs = st.tabs(list(all_day_routes.keys()))
for tab_idx, (day_name, day_data) in enumerate(all_day_routes.items()):
with tabs[tab_idx]:
r_data = day_data["rows"]
rgb = day_data["color"]
st.markdown(f"**{day_name}** β {day_data['stops']} stops | ~{day_data['drive']} min driving")
display_cols = ["Stop", "Store", "Address", "ETA", "Drive", "Service", "Frequency", "Urgency", "Last Visit", "Avg Cases"]
st.dataframe(pd.DataFrame(r_data)[display_cols], use_container_width=True, hide_index=True)
if len(r_data) >= 2:
pts = [{"lat": p["lat"], "lon": p["lon"], "name": p["Store"], "address": p["Address"]} for p in r_data]
avg_lat = sum(p["lat"] for p in pts) / len(pts)
avg_lon = sum(p["lon"] for p in pts) / len(pts)
labels = [{"lon": p["lon"], "lat": p["lat"], "label": "H" if i == 0 else str(i)} for i, p in enumerate(pts)]
st.pydeck_chart(pdk.Deck(
layers=[
pdk.Layer("PathLayer", data=[{"path": [[p["lon"], p["lat"]] for p in pts]}], get_path="path", get_color=rgb + [200], width_scale=20, get_width=5),
pdk.Layer("ScatterplotLayer", data=pts, get_position="[lon, lat]", get_color=rgb + [255], get_radius=400, radius_min_pixels=8, pickable=True),
pdk.Layer("TextLayer", data=labels, get_position="[lon, lat]", get_text="label", get_color=[255, 255, 255, 255], get_size=16, get_alignment_baseline="'center'", get_text_anchor="'middle'"),
],
initial_view_state=pdk.ViewState(latitude=avg_lat, longitude=avg_lon, zoom=9),
tooltip={"text": "{name}\n{address}"}, map_style="light",
), use_container_width=True)
# ββ Full Week Overview Map ββββββββββββββββββββββββ
st.divider()
st.subheader("πΊοΈ Full Week Overview")
overview_layers = []
all_points = []
for day_name, day_data in all_day_routes.items():
r_data = day_data["rows"]
rgb = day_data["color"]
if len(r_data) >= 2:
overview_layers.append(pdk.Layer(
"PathLayer",
data=[{"path": [[p["lon"], p["lat"]] for p in r_data]}],
get_path="path", get_color=rgb + [150], width_scale=20, get_width=3,
))
day_pts = [{"lat": p["lat"], "lon": p["lon"], "name": f"{day_name}: {p['Store']}", "address": p["Address"]} for p in r_data]
overview_layers.append(pdk.Layer(
"ScatterplotLayer", data=day_pts,
get_position="[lon, lat]", get_color=rgb + [255], get_radius=300, pickable=True,
))
all_points.extend(day_pts)
if all_points:
avg_lat = sum(p["lat"] for p in all_points) / len(all_points)
avg_lon = sum(p["lon"] for p in all_points) / len(all_points)
st.pydeck_chart(pdk.Deck(
layers=overview_layers,
initial_view_state=pdk.ViewState(latitude=avg_lat, longitude=avg_lon, zoom=8),
tooltip={"text": "{name}\n{address}"}, map_style="light",
), use_container_width=True)
legend = " ".join([
f'β {dn} ({dd["stops"]} stops)'
for dn, dd in all_day_routes.items()
])
st.markdown(legend, unsafe_allow_html=True)
# ββ Accounts not scheduled ββββββββββββββββββββββββ
if skipped:
with st.expander(f"π {len(skipped)} accounts NOT scheduled this week (on track / low urgency)"):
skip_df = pd.DataFrame(skipped)[["name", "freq", "urgency", "last", "days_since"]]
skip_df.columns = ["Store", "Frequency", "Urgency", "Last Visit", "Days Since"]
st.dataframe(skip_df, use_container_width=True, hide_index=True)
else:
st.warning("β οΈ Router found no solution. Try increasing max stops or check account data.")