diff --git "a/src/streamlit_app.py" "b/src/streamlit_app.py" --- "a/src/streamlit_app.py" +++ "b/src/streamlit_app.py" @@ -13,10 +13,11 @@ 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 -st.set_page_config(page_title="Repsly Command Center", page_icon="โšก", layout="wide") + +# --- PAGE SETUP & THEME --- +st.set_page_config(page_title="Repsly Enterprise Command Center", page_icon="โšก", layout="wide") st.markdown(""" """, unsafe_allow_html=True) -def _fxaji0y6d(key, default=None): + +# ============================================================================== +# ๐Ÿ”’ 1. ENTERPRISE SECRETS MANAGEMENT +# ============================================================================== +def get_secret(key, default=None): try: val = st.secrets[key] - if val is not None and str(val).strip(): - return str(val).strip() - except Exception: - pass - try: - val = st.secrets["DEFAULT"][key] - if val is not None and str(val).strip(): - return str(val).strip() - except Exception: - pass + if val is not None and str(val).strip(): return str(val).strip() + except Exception: pass val = os.environ.get(key, "").strip() - if val: - return val - val = os.environ.get(f"SECRET_{key}", "").strip() - if val: - return val + if val: return val return default + if "authenticated" not in st.session_state: st.session_state.authenticated = False -_secrets_ok = bool(_fxaji0y6d("APP_USER")) and bool(_fxaji0y6d("APP_PASS")) -_api_ok = bool(_fxaji0y6d("REPSLY_API_USER")) and bool(_fxaji0y6d("REPSLY_API_KEY")) -if not _secrets_ok or not _api_ok: + +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 _fxaji0y6d(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.error("โš ๏ธ **Cannot start:** One or more secrets are missing in Hugging Face Settings.") 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.") + st.title("๐Ÿ”’ Repsly Enterprise Routing") + st.write("Authorized personnel only. Please log in.") 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() == _fxaji0y6d("APP_USER") and pass_input == _fxaji0y6d("APP_PASS"): + 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.") -_vg8sbi4q2 = st.session_state.authenticated and _secrets_ok and _api_ok -if not _vg8sbi4q2: st.stop() -_vir4cowgz = _fxaji0y6d("REPSLY_API_USER", "") -_vrixa11dp = _fxaji0y6d("REPSLY_API_KEY", "") -_vpja1wj0t = "repsly_clients_cache.json" -_vpac56t4u = "repsly_forms_cache.json" -_vfel6246h = "repsly_visits_cache.json" -_vid25owf7 = "repsly_meta_cache.json" -def _fpbhsahxt(): - needed = [_vpja1wj0t, _vpac56t4u, _vid25owf7, _vfel6246h] - if not all(os.path.exists(f) for f in needed): - return False - try: - with open(_vid25owf7, 'r') as f: - return json.load(f).get("last_sync_date") == str(datetime.date.today()) - except Exception: - return False -def _fhv3a3zmf(): - with open(_vpja1wj0t, 'r') as f: - clients = json.load(f) - with open(_vpac56t4u, 'r') as f: - forms = json.load(f) - with open(_vfel6246h, 'r') as f: - visits = json.load(f) - with open(_vid25owf7, 'r') as f: - meta = json.load(f) - return clients, forms, visits, meta.get("reps", []) -def _f8mdd4v30(clients, forms, visits, reps): - with open(_vpja1wj0t, 'w') as f: - json.dump(clients, f) - with open(_vpac56t4u, 'w') as f: - json.dump(forms, f) - with open(_vfel6246h, 'w') as f: - json.dump(visits, f) - with open(_vid25owf7, 'w') as f: - json.dump({"last_sync_date": str(datetime.date.today()), "reps": reps}, f) -_v5935a0l7 = "repsly_command_center.db" -def _ft9nt3w5u(): - conn = sqlite3.connect(_v5935a0l7) + +# ============================================================================== +# ๐Ÿ—„๏ธ 2. DATABASE ENGINE (SQLITE) +# ============================================================================== +API_USERNAME = get_secret("REPSLY_API_USER", "") +API_PASSWORD = get_secret("REPSLY_API_KEY", "") +DB_PATH = "repsly_enterprise.db" +MAX_PAGES = 5000 +MAX_RETRIES = 5 +RETRY_BACKOFF = [2, 4, 8, 15, 30] + +def get_db_connection(): + conn = sqlite3.connect(DB_PATH) conn.execute("PRAGMA journal_mode=WAL") - conn.execute("PRAGMA synchronous=NORMAL") conn.row_factory = sqlite3.Row return conn -def _fzbikcidk(): - conn = _ft9nt3w5u() + +def initialize_database(): + conn = get_db_connection() conn.executescript(""" CREATE TABLE IF NOT EXISTS clients ( - client_code TEXT PRIMARY KEY, - _cid TEXT, - 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 + client_code TEXT PRIMARY KEY, customer_id TEXT, 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, 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 + 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 generated_routes ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - rep_name TEXT, - day_name TEXT, - generated_at TEXT, - _tst INTEGER, - stops_json TEXT - ); - CREATE INDEX IF NOT EXISTS idx_forms_rep ON forms(rep_name); + CREATE TABLE IF NOT EXISTS sync_meta (key TEXT PRIMARY KEY, value TEXT); 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); - CREATE INDEX IF NOT EXISTS idx_clients_custid ON clients(_cid); """) conn.commit() - try: - conn.execute("ALTER TABLE clients ADD COLUMN _cid TEXT") - conn.commit() - except Exception: - pass conn.close() -_fzbikcidk() -def _fwnnhj7xv(key, default=None): - conn = _ft9nt3w5u() + +initialize_database() + +def get_meta(key, default=None): + conn = get_db_connection() row = conn.execute("SELECT value FROM sync_meta WHERE key = ?", (key,)).fetchone() conn.close() return row["value"] if row else default -def _fg0fn9xuy(key, value): - conn = _ft9nt3w5u() - conn.execute( - "INSERT OR REPLACE INTO sync_meta (key, value) VALUES (?, ?)", - (key, str(value)) - ) - conn.commit() - conn.close() -def _f41ibljh7(clients_list, status_placeholder=None): - conn = _ft9nt3w5u() - now = str(datetime.datetime.now()) - batch = [] - _cip = re.compile(r'[A-Za-z]{2}\d{4}') - for client in clients_list: - code = _f4zw9xa3k(client) - if not code: - continue - rep_name = _fchj755nf(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 - acct_name = str(client.get("Name") or "") - id_match = _cip.search(acct_name) - _cid = id_match.group(0).upper() if id_match else "" - batch.append(( - code, - _cid, - acct_name if acct_name else "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, _cid, name, rep_name, active, lat, lon, street_address, city, state, zip, tag, territory, raw_json, updated_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) - """, batch) - conn.commit() - with_id = sum(1 for b in batch if b[1]) - if status_placeholder: - status_placeholder.info(f"๐Ÿ’พ Saved {len(batch):,} accounts ({with_id:,} with Customer ID).") - conn.close() - return len(batch) -def _f5lxo6qji(forms_batch, status_placeholder=None): - conn = _ft9nt3w5u() - sql_batch = [] - for form in forms_batch: - form_id = _fn9j2qp89( - 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 = _fpvs7hzio(form) - visit_date = None - if record_ts is not None: - visit_date = datetime.datetime.utcfromtimestamp(record_ts).strftime("%Y-%m-%d") - 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: - 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 _fujv6oh9s(reps_list): - conn = _ft9nt3w5u() - conn.executemany( - "INSERT OR IGNORE INTO reps (name) VALUES (?)", - [(r,) for r in reps_list] - ) + +def set_meta(key, value): + conn = get_db_connection() + conn.execute("INSERT OR REPLACE INTO sync_meta (key, value) VALUES (?, ?)", (key, str(value))) conn.commit() conn.close() -def _fdbdw2pcn(): - conn = _ft9nt3w5u() - rows = conn.execute("SELECT name FROM reps ORDER BY name").fetchall() - conn.close() - return [r["name"] for r in rows] -def _f9t84azyt(rep_name, include_inactive=False): - conn = _ft9nt3w5u() - rep_lower = rep_name.lower().strip() - visited_codes = conn.execute(""" - SELECT DISTINCT client_code - FROM forms - WHERE LOWER(rep_name) LIKE ? - AND visit_date >= '2024-01-01' - AND client_code IS NOT NULL AND client_code != '' - """, (f"%{rep_lower}%",)).fetchall() - visited_set = set(r["client_code"] for r in visited_codes) - if not visited_set: - conn.close() - return [] - placeholders = ",".join(["?"] * len(visited_set)) - query = f""" - SELECT client_code, _cid, name, lat, lon, active, - street_address, city, state, zip, tag, territory - FROM clients - WHERE client_code IN ({placeholders}) - AND lat != 0.0 AND lon != 0.0 - AND _cid IS NOT NULL AND _cid != '' - """ - params = list(visited_set) - if not include_inactive: - query += " AND active = 1" - rows = conn.execute(query, params).fetchall() - conn.close() - _vphr62gds = ["buying"] - _vwm31yiha = ["aging", "lead"] - accounts = [] - for r in rows: - _cid = r["_cid"] - _ctags = f"{r['tag'] or ''} {r['territory'] or ''}".lower() - if any(excl in _ctags for excl in _vwm31yiha): - continue - if not any(incl in _ctags for incl in _vphr62gds): - continue - _cn = r["name"] - if _cid in _cn: - _cn = _cn.replace(_cid, "").replace("-", "").strip() - if not _cn: - _cn = r["name"] - 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") - accounts.append({ - "code": _cid, - "_rc": r["client_code"], - "name": _cn, - "addr": address or "No address", - "lat": r["lat"], - "lon": r["lon"], - "tag": r["tag"] or r["territory"] or "Untagged", - "active": r["active"], - }) - return accounts -def _f7km3qz9w(rep_name, client_codes=None): - conn = _ft9nt3w5u() - rep_lower = rep_name.lower().strip() - if not client_codes: - conn.close() - return {} - placeholders = ",".join(["?"] * len(client_codes)) - visit_rows = conn.execute(f""" - SELECT client_code, - COUNT(*) as visit_count, - MIN(visit_date) as first_visit, - 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() - order_rows = conn.execute(f""" - SELECT client_code, - COUNT(*) as _oc, - SUM(cases) as _tc, - AVG(cases) as avg_cases_per_order, - MAX(cases) as max_order_size - FROM forms - WHERE client_code IN ({placeholders}) AND is_order = 1 - GROUP BY client_code - """, client_codes).fetchall() - conn.close() - result = {} - for r in visit_rows: - cc = r["client_code"] - result[cc] = { - "visits": r["visit_count"], - "first_visit": r["first_visit"], - "last_visit": r["last_visit"], - "orders": 0, - "_tc": 0, - "_ac": 0, - "max_order": 0, - "conversion": 0.0, - } - for r in order_rows: - cc = r["client_code"] - if cc not in result: - result[cc] = { - "visits": 0, "first_visit": None, "last_visit": None, - "orders": 0, "_tc": 0, "_ac": 0, - "max_order": 0, "conversion": 0.0, - } - result[cc]["orders"] = r["_oc"] - result[cc]["_tc"] = r["_tc"] or 0 - result[cc]["_ac"] = math.ceil(r["avg_cases_per_order"]) if r["avg_cases_per_order"] else 0 - result[cc]["max_order"] = r["max_order_size"] or 0 - if result[cc]["visits"] > 0: - result[cc]["conversion"] = round(r["_oc"] / result[cc]["visits"], 2) - return result -def _fsg65kxvf(rep_name, client_codes=None): - conn = _ft9nt3w5u() - rep_lower = rep_name.lower().strip() - 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} - 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 _f1t2tala7(): - conn = _ft9nt3w5u() - 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 _f53lc58dr(): - conn = _ft9nt3w5u() - row = conn.execute("SELECT COUNT(*) as cnt FROM clients").fetchone() - conn.close() - return row["cnt"] -def _fc11ertj5(): - conn = _ft9nt3w5u() - row = conn.execute("SELECT COUNT(*) as cnt FROM forms").fetchone() - conn.close() - return row["cnt"] -def _fpht0hl9x(rep_name, day_name, stops_data): - conn = _ft9nt3w5u() - conn.execute(""" - INSERT INTO generated_routes (rep_name, day_name, generated_at, _tst, stops_json) - VALUES (?, ?, ?, ?, ?) - """, ( - rep_name, day_name, str(datetime.datetime.now()), - len(stops_data), json.dumps(stops_data) - )) - conn.commit() - conn.close() -def _fpseimvih(rep_name, limit=10): - conn = _ft9nt3w5u() - rows = conn.execute(""" - SELECT day_name, generated_at, _tst - 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] -def _fcwi64ciy(api_user, api_pass, status_placeholder): - raw_clients = _fx7eedtjv(api_user, api_pass, status_placeholder) - count = _f41ibljh7(raw_clients, status_placeholder) - _fg0fn9xuy("last_client_sync", str(datetime.datetime.now())) - return count -def _fhe7ur23g(api_user, api_pass, start_date, end_date, status_placeholder): - last_form_id = _fwnnhj7xv("last_form_cursor", "0") - status_placeholder.info(f"๐Ÿ“ก **Incremental sync starting from cursor {last_form_id}โ€ฆ**") - 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 < _v7e8g8jdp: - 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 = _fykl1cq99(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 - valid_forms = [] - for form in batch: - form_id = _fn9j2qp89( - 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 = _fpvs7hzio(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) - if valid_forms: - new_count = _f5lxo6qji(valid_forms) - total_new += new_count - if count_parseable > 0 and count_future == count_parseable: - break - new_id = _fuzfk8ut0(data, "lastid") - if not new_id or new_id == last_id: - same_cursor += 1 - if same_cursor >= _vl58kxo9t: - break - else: - same_cursor = 0 - last_id = new_id - _fg0fn9xuy("last_form_cursor", last_id) - _fg0fn9xuy("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 -def _fdppq0y9d(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 _fom5igqpk(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 _fi7p5tb94(time_str): - t = str(time_str).strip().lower().replace('.', '') - if t in ['nan', 'none', '']: - return (420, 2880) - parts = re.split(r'[-/]| to ', t) - start = _fom5igqpk(parts[0], 420) - end = _fom5igqpk(parts[1], 2880) if len(parts) > 1 and parts[1].strip() else 2880 - if end < start: - end += 1440 - return (start, end) -def _f874frhoc(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}" -_v253j2d54 = 5 -_vi3qk2iag = [2, 4, 8, 15, 30] -_vl58kxo9t = 5 -_v7e8g8jdp = 5000 -def _fn9j2qp89(value): - if value is None: - return "" - s = str(value).strip() - return "" if s.lower() in ("none", "null", "") else s -def _fuzfk8ut0(data_dict, target_key): - if not isinstance(data_dict, dict): - return "" + +# ============================================================================== +# ๐Ÿ“ก 3. API FETCHING & DB SAVING ENGINE +# ============================================================================== +def safe_str(val): + if val is None: return "" + s = str(val).strip() + return "" if s.lower() in ("none", "null", "", "unk") else s + +def parse_form_timestamp(form): + for key in ("DateAndTime", "dateAndTime", "VisitStart", "visitStart", "Timestamp", "timestamp"): + raw = form.get(key) + if raw: + try: return int(pd.to_datetime(str(raw), utc=True).timestamp()) + except Exception: pass + return None + +def extract_pagination_key(data_dict, target_key): + if not isinstance(data_dict, dict): return "" target_lower = target_key.lower() 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 _fn9j2qp89(v) - for k, v in data_dict.items(): - if str(k).lower() == target_lower: - return _fn9j2qp89(v) + if str(k).lower() == target_lower: return safe_str(v) 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 _fn9j2qp89(sub_v) + if str(k).lower() == target_lower: return safe_str(v) return "" -def _fcvs4f8cg(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 _fvyie6ivw(val): - if val is None: - return None - s = str(val).strip() - m = re.search(r'/Date\((\d+)', s) - if m: - ms = int(m.group(1)) - return ms // 1000 - return None -def _fpvs7hzio(form): - for key in ("DateAndTime", "dateAndTime", "VisitStart", "visitStart", - "VisitEnd", "visitEnd", "Date", "date", - "Timestamp", "timestamp", "CreatedAt", "createdAt"): - raw = form.get(key) - if raw is None: - continue - ms_ts = _fvyie6ivw(raw) - if ms_ts is not None: - return ms_ts - try: - return int(raw) - except (ValueError, TypeError): - pass + +def get_with_retry(url, auth, status_placeholder, context_label): + for attempt in range(MAX_RETRIES): try: - return int(pd.to_datetime(str(raw), utc=True).timestamp()) - except Exception: - pass - return None -def _fykl1cq99(url, auth, status_placeholder, context_label): - for attempt in range(_v253j2d54): - try: - res = requests.get(url, auth=auth, timeout=45) - if res.status_code == 200: - try: - return res, res.json() - except ValueError: - if attempt < _v253j2d54 - 1: - status_placeholder.warning(f"โš ๏ธ Malformed JSON on {context_label} โ€” Retryingโ€ฆ") - time.sleep(_vi3qk2iag[attempt]) - continue + res = requests.get(url, auth=auth, timeout=30) + if res.status_code == 200: return res.json() 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) + wait = max(int(res.headers.get("Retry-After", 60)), 10) + status_placeholder.warning(f"โณ Rate limited by Repsly. Waiting {wait}sโ€ฆ") + time.sleep(wait) continue - if attempt < _v253j2d54 - 1: - status_placeholder.warning(f"โš ๏ธ HTTP {res.status_code} on {context_label} โ€” Retryingโ€ฆ") - time.sleep(_vi3qk2iag[attempt]) - except requests.RequestException as e: - if attempt < _v253j2d54 - 1: - status_placeholder.warning(f"โš ๏ธ Network error: {type(e).__name__} โ€” Retryingโ€ฆ") - time.sleep(_vi3qk2iag[attempt]) - return None, None -_v0lvsnujz = [ - "RepresentativeName", "representativeName", - "Representative", "representative", - "RepresentativeCode", "representativeCode", - "Rep", "rep", - "AssignedTo", "assignedTo", - "SalesRep", "salesRep", - "Agent", "agent", -] -def _fchj755nf(client_dict): - for field in _v0lvsnujz: - 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 - 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 _f4zw9xa3k(client_dict): - 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 "" -def _fx7eedtjv(api_user, api_pass, status_placeholder): - clients = [] - seen = set() + status_placeholder.warning(f"โš ๏ธ HTTP {res.status_code} on {context_label}. Retryingโ€ฆ") + time.sleep(RETRY_BACKOFF[attempt]) + except Exception as e: + status_placeholder.warning(f"โš ๏ธ Network error: {e}. Retryingโ€ฆ") + time.sleep(RETRY_BACKOFF[attempt]) + return None + +def sync_clients(api_user, api_pass, status_placeholder): last_id = "0" - same_cursor = 0 page_count = 0 - total_count = None - while page_count < _v7e8g8jdp: + total_inserted = 0 + conn = get_db_connection() + id_pattern = re.compile(r'[A-Za-z]{2}\d{4}') + + 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})**") + status_placeholder.info(f"๐Ÿ“ก **Downloading Master Account Listโ€ฆ (Page {page_count})**") url = f"https://api.repsly.com/v3/export/clients/{last_id}?count=200" - _, data = _fykl1cq99(url, (api_user, api_pass), status_placeholder, f"clients page {page_count}") - if data is None: - break - if total_count is None: - total_count = _fcvs4f8cg(data) + data = get_with_retry(url, (api_user, api_pass), status_placeholder, "clients") + if not data: break + batch = data.get("Clients", []) - if not batch: - break + if not batch: break + + sql_batch = [] for c in batch: - cid = _f4zw9xa3k(c) - if cid and cid in seen: - continue - if cid: - seen.add(cid) - clients.append(c) - new_id = _fuzfk8ut0(data, "lasttimestamp") or _fuzfk8ut0(data, "lastid") - if not new_id or new_id == last_id: - same_cursor += 1 - if same_cursor >= _vl58kxo9t: - break - else: - same_cursor = 0 - last_id = new_id - return clients -def _fzhwjr64d(api_user, api_pass, start_date, end_date, starting_id, status_placeholder): - order_forms = [] - rep_client_map = {} - last_visit_map = {} - seen_form_ids = set() + code = safe_str(c.get("ClientCode") or c.get("ClientID")) + if not code: continue + + rep_obj = c.get("Representative") + rep_name = safe_str(rep_obj.get("Name")) if isinstance(rep_obj, dict) else safe_str(c.get("RepresentativeName")) + acct_name = safe_str(c.get("Name")) + active = 0 if str(c.get("Active")).lower() in ("false", "0", "no") else 1 + + try: lat, lon = float(c.get("Latitude") or 0.0), float(c.get("Longitude") or 0.0) + except: lat, lon = 0.0, 0.0 + + match = id_pattern.search(acct_name) + cust_id = match.group(0).upper() if match else "" + + sql_batch.append(( + code, cust_id, acct_name, rep_name, active, lat, lon, + safe_str(c.get("StreetAddress")), safe_str(c.get("City")), + safe_str(c.get("State")), safe_str(c.get("ZIP")), + safe_str(c.get("Tag")), safe_str(c.get("Territory")), str(datetime.datetime.now()) + )) + + conn.executemany(""" + INSERT OR REPLACE INTO clients + (client_code, customer_id, name, rep_name, active, lat, lon, street_address, city, state, zip, tag, territory, updated_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + """, sql_batch) + conn.commit() + total_inserted += len(sql_batch) + + new_id = extract_pagination_key(data, "lasttimestamp") or extract_pagination_key(data, "lastid") + if not new_id or new_id == last_id: break + last_id = new_id + + conn.close() + set_meta("last_client_sync", str(datetime.datetime.now())) + return total_inserted + +def sync_forms(api_user, api_pass, start_date, end_date, fast_forward_id, status_placeholder): 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 < _v7e8g8jdp: + last_id = str(fast_forward_id).strip() if fast_forward_id else "0" + page_count, total_scanned, total_inserted = 0, 0, 0 + conn = get_db_connection() + + 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})**" - ) + status_placeholder.info(f"๐Ÿ“ก **Scanning Order Historyโ€ฆ ({total_scanned:,} scanned | {total_inserted:,} new | Page {page_count})**") url = f"https://api.repsly.com/v3/export/forms/{last_id}?count=200" - _, data = _fykl1cq99(url, (api_user, api_pass), status_placeholder, f"forms page {page_count}") - if data is None: - break + data = get_with_retry(url, (api_user, api_pass), status_placeholder, "forms") + if not data: break + batch = data.get("Forms", data.get("FormResults", [])) - if not batch: - break + if not batch: break total_scanned += len(batch) - count_parseable = 0 - count_future = 0 - for form in batch: - form_id = _fn9j2qp89( - 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 = _fpvs7hzio(form) + + sql_batch = [] + count_parseable, count_future = 0, 0 + + for f in batch: + form_id = safe_str(f.get("FormID") or f.get("ID")) + if not form_id: continue + + record_ts = parse_form_timestamp(f) 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() - if rep_name and client_code: - rep_key = rep_name.lower().strip() - rep_client_map.setdefault(rep_key, set()).add(client_code) - 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 - if "order" in form_name: - case_count = 0 - for item in form.get("Items", []): - title = str(item.get("Title", "")).lower() + if record_ts > end_ts: count_future += 1 + if record_ts < start_ts or record_ts > end_ts: continue + + rep_name = safe_str(f.get("RepresentativeName")) + client_code = safe_str(f.get("ClientCode")) + form_name = safe_str(f.get("FormName")).lower() + visit_date = datetime.datetime.utcfromtimestamp(record_ts).strftime("%Y-%m-%d") if record_ts else None + + is_order = 1 if "order" in form_name else 0 + case_count = 0 + if is_order: + for item in f.get("Items", []): + title = safe_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 = _fuzfk8ut0(data, "lastid") - if not new_id or new_id == last_id: - same_cursor += 1 - if same_cursor >= _vl58kxo9t: - break - else: - same_cursor = 0 - last_id = new_id - 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 -st.title("โšก Repsly Operations Command Center") + try: case_count += int(re.search(r'\d+', safe_str(item.get("Value"))).group()) + except: pass + + sql_batch.append((form_id, rep_name, client_code, form_name, case_count, record_ts, visit_date, is_order)) + + if sql_batch: + 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() + total_inserted += conn.execute("SELECT changes()").fetchone()[0] + + 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: break + last_id = new_id + + conn.close() + set_meta("last_form_sync", str(datetime.datetime.now())) + return total_inserted + +# ============================================================================== +# ๐Ÿงฎ 4. PREDICTIVE DATA SCIENCE ENGINE & OSRM +# ============================================================================== +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))) * 1.45 + +def calculate_expected_value(visits, total_cases, days_since_last, days_in_period): + if visits == 0 or total_cases == 0: return 0.0, 0.0, 0.0 + avg_cases_per_order = total_cases / visits + avg_cycle_days = days_in_period / visits + k = 0.2 + probability = 1 / (1 + math.exp(-k * (days_since_last - avg_cycle_days))) + expected_value = probability * avg_cases_per_order + return round(probability, 2), round(avg_cases_per_order, 1), round(expected_value, 2) + +def build_time_matrix(nodes, use_osrm=False): + size = len(nodes) + matrix = [[0]*size for _ in range(size)] + + if use_osrm and size <= 100: + try: + coords = ";".join([f"{n['lon']},{n['lat']}" for n in nodes]) + url = f"http://router.project-osrm.org/table/v1/driving/{coords}?annotations=duration" + resp = requests.get(url, timeout=15) + if resp.status_code == 200: + durations = resp.json()['durations'] + for i in range(size): + for j in range(size): + if durations[i][j] is not None: matrix[i][j] = int(durations[i][j] / 60.0) + else: matrix[i][j] = int((haversine_miles(nodes[i]["lat"], nodes[i]["lon"], nodes[j]["lat"], nodes[j]["lon"]) / 45.0) * 60) + return matrix, True + except Exception: + st.warning("โš ๏ธ OSRM Traffic Engine timeout. Falling back to geometric math.") + + for i in range(size): + for j in range(size): + if i != j: + miles = haversine_miles(nodes[i]["lat"], nodes[i]["lon"], nodes[j]["lat"], nodes[j]["lon"]) + matrix[i][j] = int((miles / 45.0) * 60) + return matrix, False + +def format_time(minutes): + h = (int(minutes) // 60) % 24 + m = int(minutes) % 60 + ap = "AM" if h < 12 else "PM" + ch = h if h <= 12 else h - 12 + if ch == 0: ch = 12 + return f"{ch:02d}:{m:02d} {ap}" + +# ============================================================================== +# ๐Ÿ–ฅ๏ธ 5. USER INTERFACE & MODULES +# ============================================================================== +st.title("โšก Repsly Enterprise Operations") + app_mode = st.sidebar.radio( - "โš™๏ธ Select Operating Mode", - ["๐Ÿšš Driver Dispatch (Warehouse)", "๐Ÿ‘ค Sales Territories (Field)"] + "โš™๏ธ Select Module", + ["๐Ÿ”„ Data Sync Dashboard", "๐Ÿค– Predictive Sales Router (Field)", "๐Ÿšš Driver Dispatch (Warehouse)"] ) st.sidebar.divider() -if app_mode == "๐Ÿšš Driver Dispatch (Warehouse)": + +conn = get_db_connection() +client_count = conn.execute("SELECT COUNT(*) as c FROM clients").fetchone()["c"] +form_count = conn.execute("SELECT COUNT(*) as c FROM forms").fetchone()["c"] +conn.close() + +# ------------------------------------------------------------------------------ +# MODULE: DATA SYNC DASHBOARD +# ------------------------------------------------------------------------------ +if app_mode == "๐Ÿ”„ Data Sync Dashboard": + st.subheader("๐Ÿ—„๏ธ Database Management") + if client_count > 0: + st.success(f"**Database Active:** {client_count:,} accounts | {form_count:,} forms.") + st.caption(f"Last client sync: {get_meta('last_client_sync', 'Never')} | Last form sync: {get_meta('last_form_sync', 'Never')}") + else: + st.warning("Database is empty. Run a sync below.") + + st.divider() + col1, col2, col3 = st.columns(3) + today = datetime.date.today() + with col1: start_date = st.date_input("Start Date", datetime.date(today.year - 1, 1, 1)) + with col2: end_date = st.date_input("End Date", today) + with col3: fast_forward_id = st.text_input("โฉ Fast-Forward ID (Optional)", value="0") + + if st.button("๐Ÿš€ RUN ENTERPRISE API SYNC", type="primary", use_container_width=True): + status = st.empty() + try: + status.info("๐Ÿ“ก Syncing Master Account List...") + sync_clients(API_USERNAME, API_PASSWORD, status) + status.info("๐Ÿ“ก Syncing Order History...") + sync_forms(API_USERNAME, API_PASSWORD, start_date, end_date, fast_forward_id, status) + status.success("โœ… **Enterprise Sync Complete!** Database updated.") + time.sleep(2) + st.rerun() + except Exception as e: + status.error(f"โŒ Sync Error: {e}") + + if st.button("๐Ÿ—‘๏ธ Nuke Database (Factory Reset)"): + conn = get_db_connection() + for t in ["clients", "forms", "sync_meta"]: conn.execute(f"DELETE FROM {t}") + conn.commit() + conn.close() + st.success("Database erased.") + time.sleep(1) + st.rerun() + +# ------------------------------------------------------------------------------ +# MODULE: PREDICTIVE SALES ROUTER (DSD CALIBRATED) +# ------------------------------------------------------------------------------ +elif app_mode == "๐Ÿค– Predictive Sales Router (Field)": + if client_count == 0: + st.warning("Database is empty. Please run the Data Sync Dashboard first.") + st.stop() + + REP_HOMES = { + "Brian Milam": {"lat": 36.0152, "lon": -80.2641}, + "Julia Cameron": {"lat": 35.3942, "lon": -77.9248}, + "Aaron Manning": {"lat": 35.9184, "lon": -78.8051}, + "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} + } + + with st.sidebar: + st.header("๐Ÿ‘ค Fleet Optimizer") + conn = get_db_connection() + reps = [r["rep_name"] for r in conn.execute("SELECT DISTINCT rep_name FROM clients WHERE rep_name != ''").fetchall()] + selected_reps = st.multiselect("Select Sales Reps (Combine for Fleet Balancing)", reps, default=[reps[0]] if reps else None) + + st.divider() + st.markdown("**Routing Constraints**") + route_days = st.slider("Days in Routing Cycle (per rep)", 1, 14, 10, help="10 days = 2 working weeks.") + + # ELASTIC WORKDAY: Defaults to 10 hours, but allows 14 hours (up to 8:30 PM) for heavy volume days. + max_hours = st.slider("Max Hours per Shift", 6.0, 14.0, 10.0, step=0.5, help="Allows for long beverage DSD days when volume dictates.") + + use_osrm = st.toggle("๐Ÿšฆ Use Live Traffic (OSRM API)", value=True, help="Limits processing to top 90 stores to respect public API limits.") + + if not selected_reps: + st.info("Please select at least one rep to begin.") + st.stop() + + st.subheader("๐Ÿง  MDVRP Fleet Optimization") + rep_placeholders = ",".join(["?"] * len(selected_reps)) + accounts = conn.execute(f"SELECT client_code, name, lat, lon, street_address, city FROM clients WHERE rep_name IN ({rep_placeholders}) AND active = 1 AND lat != 0 AND lon != 0", selected_reps).fetchall() + + account_names = [a["name"] for a in accounts] + vip_selections = st.multiselect("๐Ÿ“Œ VIP Accounts (Force Solver to Visit These)", account_names) + + if st.button("๐Ÿš€ GENERATE FLEET ROUTE", type="primary", use_container_width=True): + with st.spinner("Crunching predictive models and global vehicle routing matrix..."): + codes = [a["client_code"] for a in accounts] + if not codes: + st.error("No active GPS accounts found for these reps.") + st.stop() + + code_placeholders = ",".join(["?"] * len(codes)) + stats = conn.execute(f"SELECT client_code, COUNT(*) as visits, SUM(cases) as total_cases, MAX(visit_date) as last_visit FROM forms WHERE client_code IN ({code_placeholders}) AND is_order = 1 GROUP BY client_code", codes).fetchall() + stats_dict = {r["client_code"]: r for r in stats} + today = datetime.date.today() + + client_nodes = [] + for acct in accounts: + cc = acct["client_code"] + s = stats_dict.get(cc, {"visits": 0, "total_cases": 0, "last_visit": None}) + lv = s["last_visit"] + days_since = (today - datetime.datetime.strptime(lv, "%Y-%m-%d").date()).days if lv else 999 + prob, avg_cases, ev = calculate_expected_value(s["visits"], s["total_cases"], days_since, 365) + + # BEVERAGE DSD LIGHT MERCH MATH: 15 min base + 1.5 mins per case. + svc_time = int(15 + (ev * 1.5)) if ev > 0 else 10 + + if acct["name"] in vip_selections: ev += 1000 + + client_nodes.append({ + "id": cc, "name": acct["name"], "lat": acct["lat"], "lon": acct["lon"], + "budget_mins": svc_time, "ev": ev, "prob": prob, "avg_cases": avg_cases, + "days_since": days_since, "desc": f"{acct['street_address']}, {acct['city']}" + }) + + client_nodes.sort(key=lambda x: x["ev"], reverse=True) + if use_osrm and len(client_nodes) > 90: client_nodes = client_nodes[:90] + + depot_nodes, starts, ends, vehicle_labels = [], [], [], [] + node_idx = 0 + for rep in selected_reps: + d_lat, d_lon = REP_HOMES.get(rep, {"lat": 36.0726, "lon": -79.7919}).values() + depot_nodes.append({"id": f"DEPOT_{rep}", "name": f"๐Ÿ  {rep} Home", "lat": d_lat, "lon": d_lon, "budget_mins": 0, "ev": 0, "prob": 0}) + for day in range(route_days): + starts.append(node_idx) + ends.append(node_idx) + vehicle_labels.append({"rep": rep, "day": day + 1}) + node_idx += 1 + + nodes = depot_nodes + client_nodes + size = len(nodes) + num_vehicles = len(starts) + max_time_per_day = int(max_hours * 60) + + time_matrix, used_osrm = build_time_matrix(nodes, use_osrm) + if used_osrm: st.success("๐Ÿšฆ Successfully fetched Real-World OSRM Traffic Data!") + + manager = pywrapcp.RoutingIndexManager(size, num_vehicles, starts, ends) + routing = pywrapcp.RoutingModel(manager) + + def time_callback(from_index, to_index): + fn, tn = manager.IndexToNode(from_index), manager.IndexToNode(to_index) + return time_matrix[fn][tn] + nodes[tn]["budget_mins"] + + transit_callback_index = routing.RegisterTransitCallback(time_callback) + routing.SetArcCostEvaluatorOfAllVehicles(transit_callback_index) + routing.AddDimension(transit_callback_index, 30, max_time_per_day, False, 'Time') + + num_depots = len(depot_nodes) + for i in range(num_depots, size): + n = nodes[i] + penalty = 10000000 if n["name"] in vip_selections else int(500 + (n["ev"] * 1000)) + routing.AddDisjunction([manager.NodeToIndex(i)], penalty) + + 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 = 5 + + solution = routing.SolveWithParameters(search_parameters) + + if solution: + st.success("โœ… Global Fleet Matrix Solved!") + time_dim = routing.GetDimensionOrDie('Time') + colors = [[231,76,60], [52,152,219], [46,204,113], [241,196,15], [155,89,182], [26,188,156]] + rep_color_map = {rep: colors[i % len(colors)] for i, rep in enumerate(selected_reps)} + rep_tabs = st.tabs(selected_reps) + map_layers = [] + + for rep_idx, rep in enumerate(selected_reps): + with rep_tabs[rep_idx]: + c_rgb = rep_color_map[rep] + rep_vehicles = [v for v, label in enumerate(vehicle_labels) if label["rep"] == rep] + + for v_id in rep_vehicles: + day_num = vehicle_labels[v_id]["day"] + index = routing.Start(v_id) + route_output = [] + day_ev = 0 + + while not routing.IsEnd(index): + node_index = manager.IndexToNode(index) + + # TIME OFFSET: 390 mins = 6:30 AM physical start. Arrive at store #1 by ~7:00 AM. + arr_time = solution.Value(time_dim.CumulVar(index)) + 390 + + if node_index >= num_depots: + n = nodes[node_index] + day_ev += n['ev'] + route_output.append({ + "Time": format_time(arr_time), + "Store": "๐Ÿ“Œ " + n["name"] if n["name"] in vip_selections else n["name"], + "Prob": f"{int(n['prob']*100)}%", + "Exp. Cases": round(n["ev"]-1000 if n["ev"]>500 else n["ev"], 1), + "Days Since": n["days_since"], + "Service": f"{n['budget_mins']}m", + "lat": n["lat"], "lon": n["lon"] + }) + index = solution.Value(routing.NextVar(index)) + + if route_output: + with st.expander(f"Day {day_num} โ€” {round(day_ev, 1)} Expected Cases"): + st.dataframe(pd.DataFrame(route_output).drop(columns=['lat', 'lon']), use_container_width=True) + + start_coords = [depot_nodes[rep_idx]["lon"], depot_nodes[rep_idx]["lat"]] + path_data = [start_coords] + [[p['lon'], p['lat']] for p in route_output] + map_layers.append(pdk.Layer("PathLayer", data=[{"path": path_data}], get_path="path", get_color=c_rgb + [200], width_scale=20, get_width=4)) + map_layers.append(pdk.Layer("ScatterplotLayer", data=route_output, get_position="[lon, lat]", get_color=c_rgb + [255], get_radius=250)) + + st.divider() + avg_lat = sum(n["lat"] for n in nodes) / len(nodes) + avg_lon = sum(n["lon"] for n in nodes) / len(nodes) + st.subheader("๐Ÿ—บ๏ธ Global Fleet Map") + st.pydeck_chart(pdk.Deck(layers=map_layers, initial_view_state=pdk.ViewState(latitude=avg_lat, longitude=avg_lon, zoom=8), map_style="light"), use_container_width=True) + else: + st.error("โŒ The solver could not find a viable solution.") + + # ============================================================================== + # PHASE 4: THE "ONE-MORE-STOP" HUSTLE FINDER + # ============================================================================== + st.divider() + st.subheader("๐Ÿšจ The 'One-More-Stop' Hustle Finder") + st.write("Finished a stop early? Find the highest probability buyer sitting right around the corner.") + + all_stores = conn.execute("SELECT name, lat, lon, client_code FROM clients WHERE active = 1 AND lat != 0").fetchall() + store_names = [s["name"] for s in all_stores] + current_location = st.selectbox("Where are you right now?", ["Select a store..."] + store_names) + + if current_location != "Select a store...": + ref_store = next(s for s in all_stores if s["name"] == current_location) + nearby = [] + for s in all_stores: + if s["name"] != current_location: + miles = haversine_miles(ref_store["lat"], ref_store["lon"], s["lat"], s["lon"]) + if miles <= 10.0: nearby.append({"name": s["name"], "miles": round(miles, 1), "code": s["client_code"]}) + + if nearby: + codes = [n["code"] for n in nearby] + code_placeholders = ",".join(["?"] * len(codes)) + stats = conn.execute(f"SELECT client_code, COUNT(*) as visits, SUM(cases) as total_cases, MAX(visit_date) as last_visit FROM forms WHERE client_code IN ({code_placeholders}) AND is_order = 1 GROUP BY client_code", codes).fetchall() + stats_dict = {r["client_code"]: r for r in stats} + today = datetime.date.today() + + for n in nearby: + s = stats_dict.get(n["code"], {"visits": 0, "total_cases": 0, "last_visit": None}) + lv = s["last_visit"] + days_since = (today - datetime.datetime.strptime(lv, "%Y-%m-%d").date()).days if lv else 999 + prob, _, ev = calculate_expected_value(s["visits"], s["total_cases"], days_since, 365) + n["Expected Cases"] = ev + n["Probability"] = f"{int(prob*100)}%" + + nearby.sort(key=lambda x: x["Expected Cases"], reverse=True) + st.success("๐ŸŽฏ **Top 3 High-Value Targets within a 10-mile radius:**") + st.dataframe(pd.DataFrame(nearby[:3]).drop(columns=['code']), use_container_width=True) + else: + st.info("No active accounts found within a 10-mile radius of this location.") + conn.close() + +# ------------------------------------------------------------------------------ +# MODULE: DRIVER DISPATCH (WAREHOUSE) +# ------------------------------------------------------------------------------ +elif 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.") - _vxll4zklo = { + + 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}, + "Sumter (SUMT)": {"address": "50 Commerce St, Sumter, SC 29150", "lat": 33.918, "lon": -80.328} } - _va7tz0ync = 15 + + def parse_time_window(time_str): + time_str = str(time_str).strip().lower().replace('.', '') + if time_str in ['nan', 'none', '']: return (420, 2880) + parts = re.split(r'[-/]| to ', time_str) + def parse_single_time(t_str, default_val): + match = re.search(r'(\d{1,2}):?(\d{2})?\s*(am|pm)?', t_str) + if match: + hr, mn, ampm = int(match.group(1)), int(match.group(2) or 0), match.group(3) + if ampm == 'pm' and hr < 12: hr += 12 + if ampm == 'am' and hr == 12: hr = 0 + return hr * 60 + mn + return default_val + start_mins = parse_single_time(parts[0], 420) + end_mins = parse_single_time(parts[1], 2880) if len(parts) > 1 and parts[1].strip() else 2880 + if end_mins < start_mins: end_mins += 1440 + return (start_mins, end_mins) + 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') - 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()] + if uploaded_file.name.endswith('.xlsx'): df = pd.read_excel(uploaded_file) + else: df = pd.read_csv(uploaded_file, sep=';', encoding='latin1') + + 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) 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' + rec_window_col = next((c for c in df.columns if 'receiving window' in c.lower()), None) 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 = [] + 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(_vxll4zklo.keys())) - _vy9v86wzs = _vxll4zklo[selected_warehouse_name]["address"] - st.caption(f"๐Ÿ“ *{_vy9v86wzs}*") - 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.") - 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] - clean_ids, clean_names, full_addresses = [], [], [] - lats, lons, service_times, window_texts, final_time_windows = [], [], [], [], [] - for _, row in df_filtered.iterrows(): + selected_warehouse_name = st.selectbox("๐Ÿข Starting Warehouse", list(WAREHOUSES.keys())) + START_ADDRESS = WAREHOUSES[selected_warehouse_name]["address"] + + clean_ids, clean_names, lats, lons, service_times, window_texts, final_time_windows = [], [], [], [], [], [], [] + + for _, row in df.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() + c_id = match.group(0).upper() if match 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 = _fi7p5tb94(row[rec_window_col]) - window_texts.append(f"{_f874frhoc(w_start)} - {_f874frhoc(w_end)} (Strict)") + + if 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)}") final_time_windows.append((w_start, w_end)) else: - w_start = _fom5igqpk(row[open_col], 420) - window_texts.append(f"{_f874frhoc(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 - 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: - 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() - 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 = _vxll4zklo[selected_warehouse_name] - _ndl = [{ - "id": "WAREHOUSE", "name": f"Start: {selected_warehouse_name}", - "address": _vy9v86wzs, "lat": wh_data["lat"], - "lon": wh_data["lon"], "service_time": 0, - }] - _twn = [(240, 540)] - _pni = None - for row_idx, row in df_final.reset_index(drop=True).iterrows(): - _ndl.append({ - "id": row['Clean_ID'], "name": row['Clean_Name'], - "address": row['Full_Address'], "lat": row['Lat'], - "lon": row['Lon'], "service_time": row['Service_Time'], - }) - _twn.append(row['Tuple_Window']) - if row['โญ Pin 1st'] == True: - _pni = row_idx + 1 - size = len(_ndl) - _tmx = [] - for i in range(size): - row = [] - for j in range(size): - if i == j: - row.append(0) - else: - l1, o1 = _ndl[i]['lat'], _ndl[i]['lon'] - l2, o2 = _ndl[j]['lat'], _ndl[j]['lon'] - if pd.notna(l1) and pd.notna(o1) and pd.notna(l2) and pd.notna(o2): - row.append(int(_fdppq0y9d(l1, o1, l2, o2) * 1.2 + 10)) - else: - row.append(_va7tz0ync) - _tmx.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 _tmx[fn][tn] + _ndl[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(_twn): - time_dim.CumulVar(manager.NodeToIndex(i)).SetRange(window[0], window[1]) - for i in range(1, size): - routing.AddDisjunction([manager.NodeToIndex(i)], 100000) - if _pni is not None: - routing.solver().Add(routing.NextVar(routing.Start(0)) == _pni) - st.session_state.pinned_node_name = _ndl[_pni]['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))) - _sp = pywrapcp.DefaultRoutingSearchParameters() - _sp.first_solution_strategy = routing_enums_pb2.FirstSolutionStrategy.PATH_CHEAPEST_ARC - _sp.local_search_metaheuristic = routing_enums_pb2.LocalSearchMetaheuristic.GUIDED_LOCAL_SEARCH - _sp.time_limit.seconds = 2 - solution = routing.SolveWithParameters(_sp) - if solution: - st.session_state.route_success = True - st.session_state.dropped_stores = [ - _ndl[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": _ndl[node]["id"], "Location Name": _ndl[node]["name"], "Address": _ndl[node]["address"], "Time": f"Leave: {_f874frhoc(arr_time)}", "Drive Time": "-", "lat": _ndl[node]["lat"], "lon": _ndl[node]["lon"]}) - elif step == len(route_seq) - 1: - drive_time = _tmx[route_seq[step-1][0]][node] - route_data.append({"Stop": "Finish", "Customer ID": _ndl[0]["id"], "Location Name": "Return to Warehouse", "Address": _ndl[0]["address"], "Time": f"Arrive: {_f874frhoc(arr_time)}", "Drive Time": f"{drive_time} mins", "lat": _ndl[0]["lat"], "lon": _ndl[0]["lon"]}) - else: - p_node, p_arr = route_seq[step-1][0], route_seq[step-1][1] - drive_time = _tmx[p_node][node] - p_svc = _ndl[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": _ndl[node]["id"], "Location Name": _ndl[node]["name"], "Address": _ndl[node]["address"], "Time": f"Service Begins: {_f874frhoc(arr_time)}", "Drive Time": d_str, "lat": _ndl[node]["lat"], "lon": _ndl[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.") - 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:** {_f874frhoc(st.session_state.end_time)}") - 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: - _mlog = [] - _ais = [ - {"num": int(str(r["Stop"]).replace("#", "")), - "id": re.sub(r'[^A-Z0-9]', '', str(r.get("Customer ID", "")).upper()), - "_cn": 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) - _ms, _ml = 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 _ais: - if ai["id"] == c_id: - _ms = ai["num"] - _ml = f"Exact ID Match ({c_id})" - break - if _ms is None: - _hr = 0.0 - for ai in _ais: - ratio = difflib.SequenceMatcher(None, clean_xl, ai["_cn"]).ratio() - if ratio > _hr: - _hr = ratio - _ms = ai["num"] - if _hr > 0.45: - _ml = f"Fuzzy Match ({int(_hr * 100)}%)" - else: - _ms = None - _mlog.append({ - "Excel Row": r_idx, - "Name Seen": acc_name_str, - "Assigned Stop": _ms if _ms is not None else "โŒ MAPPING FAILED", - "Logic Used": _ml, - }) - if _ms 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(_ms) - break - else: - target_cell.value = int(_ms) - 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(_mlog), 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}") - 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, + window_texts.append("Standard (7 AM+)") + final_time_windows.append((420, 2880)) + + df['Clean_ID'] = clean_ids + df['Clean_Name'] = clean_names + df['Lat'] = lats + df['Lon'] = lons + df['Service_Time'] = service_times + df['Rec_Window'] = window_texts + df['Tuple_Window'] = final_time_windows + + editor_df = pd.DataFrame({"Route": [True]*len(df), "โญ Pin 1st": [False]*len(df), "Customer ID": df['Clean_ID'], "Store Name": df['Clean_Name'], "Required Window": df['Rec_Window'], "Budgeted Mins": df['Service_Time']}) + edited_df = st.data_editor(editor_df, hide_index=True, use_container_width=True) + + df_final = df[edited_df["Route"] == True] + pinned_node_idx = edited_df.index[edited_df['โญ Pin 1st'] == True].tolist() + + if st.button("๐Ÿš€ Generate Optimized Route", type="primary"): + 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)] + + final_pin = 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": "Route Stop", "lat": row['Lat'], "lon": row['Lon'], "service_time": row['Service_Time']}) + time_windows.append(row['Tuple_Window']) + if row_idx in pinned_node_idx: final_pin = row_idx + 1 + + size = len(node_details) + time_matrix, _ = build_time_matrix(node_details, use_osrm=False) # Geometric math for warehouse + + 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 final_pin is not None: routing.solver().Add(routing.NextVar(routing.Start(0)) == final_pin) + routing.AddVariableMinimizedByFinalizer(time_dim.CumulVar(routing.End(0))) + + search_parameters = pywrapcp.DefaultRoutingSearchParameters() + 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.success("โœ… Route Optimized Successfully!") + 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)) + + route_data = [] + for step, (node, arr_time) in enumerate(route_seq): + route_data.append({ + "Stop": "Start" if step == 0 else f"#{step}", + "Customer ID": node_details[node]["id"], + "Location Name": node_details[node]["name"], + "Time": format_time(arr_time), + "lat": node_details[node]["lat"], "lon": node_details[node]["lon"] }) - 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.") -elif app_mode == "๐Ÿ‘ค Sales Territories (Field)": - _vokep7y6w = { - "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}, - } - client_count = _f53lc58dr() - form_count = _fc11ertj5() - db_has_data = client_count > 0 - last_client_sync = _fwnnhj7xv("last_client_sync", "Never") - last_form_sync = _fwnnhj7xv("last_form_sync", "Never") - if db_has_data: - earliest, latest, _ = _f1t2tala7() - 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(2024, 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: - status.info("๐Ÿ“ก Downloading rep rosterโ€ฆ") - _, rep_data = _fykl1cq99( - "https://api.repsly.com/v3/export/representatives", - (_vir4cowgz, _vrixa11dp), 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") - ]))) - _fujv6oh9s(reps_list) - _fcwi64ciy(_vir4cowgz, _vrixa11dp, status) - status.info("๐Ÿ—‘๏ธ Clearing old form data for clean re-importโ€ฆ") - conn = _ft9nt3w5u() - conn.execute("DELETE FROM forms") - conn.commit() - conn.close() - _fg0fn9xuy("last_form_cursor", "0") - _fhe7ur23g(_vir4cowgz, _vrixa11dp, 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 = _fhe7ur23g( - _vir4cowgz, _vrixa11dp, 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 = _ft9nt3w5u() - for table in ["clients", "forms", "sync_meta", "reps", "generated_routes"]: - conn.execute(f"DELETE FROM {table}") - conn.commit() - conn.close() - st.rerun() - if db_has_data: - with st.expander("๐Ÿ”ฌ Database Inspector โ€” See Raw Data"): - insp_col1, insp_col2 = st.columns(2) - with insp_col1: - st.markdown("**๐Ÿ” Search Clients**") - search_term = st.text_input("Search by name, code, or customer ID", "", key="db_search") - if search_term: - conn = _ft9nt3w5u() - search_like = f"%{search_term}%" - rows = conn.execute(""" - SELECT client_code, _cid, name, rep_name, active, lat, lon - FROM clients - WHERE name LIKE ? OR client_code LIKE ? OR _cid LIKE ? - LIMIT 20 - """, (search_like, search_like, search_like)).fetchall() - conn.close() - if rows: - st.dataframe(pd.DataFrame([dict(r) for r in rows]), use_container_width=True, hide_index=True) - else: - st.warning("No matches found.") - with insp_col2: - st.markdown("**๐Ÿ“‹ Search Forms by Client Code**") - form_search = st.text_input("Enter Repsly client_code (e.g. 4907)", "", key="form_search") - if form_search: - conn = _ft9nt3w5u() - form_like = f"%{form_search}%" - rows = conn.execute(""" - SELECT form_id, rep_name, client_code, form_name, cases, visit_date, is_order - FROM forms - WHERE client_code LIKE ? - ORDER BY visit_date DESC - LIMIT 20 - """, (form_like,)).fetchall() - conn.close() - if rows: - st.dataframe(pd.DataFrame([dict(r) for r in rows]), use_container_width=True, hide_index=True) - st.success(f"Found {len(rows)} form records. Latest visit: {rows[0]['visit_date']}") - else: - st.warning(f"No forms found for client_code containing '{form_search}'.") - st.divider() - st.markdown("**๐Ÿ“Š Quick Stats**") - conn = _ft9nt3w5u() - total_clients = conn.execute("SELECT COUNT(*) as c FROM clients").fetchone()["c"] - clients_with_id = conn.execute("SELECT COUNT(*) as c FROM clients WHERE _cid IS NOT NULL AND _cid != ''").fetchone()["c"] - total_forms = conn.execute("SELECT COUNT(*) as c FROM forms").fetchone()["c"] - forms_with_date = conn.execute("SELECT COUNT(*) as c FROM forms WHERE visit_date IS NOT NULL").fetchone()["c"] - forms_with_client = conn.execute("SELECT COUNT(*) as c FROM forms WHERE client_code IS NOT NULL AND client_code != ''").fetchone()["c"] - sample_form_codes = conn.execute(""" - SELECT DISTINCT client_code FROM forms - WHERE client_code IS NOT NULL AND client_code != '' - LIMIT 10 - """).fetchall() - sample_client_codes = conn.execute(""" - SELECT client_code, _cid, name FROM clients - WHERE _cid IS NOT NULL AND _cid != '' - LIMIT 10 - """).fetchall() - conn.close() - stat_col1, stat_col2 = st.columns(2) - with stat_col1: - st.markdown(f""" -| Clients | Count | -|---|---| -| Total | **{total_clients:,}** | -| With Customer ID | **{clients_with_id:,}** | -| Without (_skpd) | **{total_clients - clients_with_id:,}** | -""") - if sample_client_codes: - st.write("**Sample client records (code โ†’ _cid โ†’ name):**") - for r in sample_client_codes: - st.text(f" {r['client_code']} โ†’ {r['_cid']} โ†’ {r['name'][:40]}") - with stat_col2: - st.markdown(f""" -| Forms | Count | -|---|---| -| Total | **{total_forms:,}** | -| With visit date | **{forms_with_date:,}** | -| With client code | **{forms_with_client:,}** | -""") - if sample_form_codes: - st.write("**Sample client_codes from forms table:**") - for r in sample_form_codes: - st.text(f" {r['client_code']}") - st.divider() - st.markdown("**๐Ÿ”Ž RAW API FORM INSPECTOR** โ€” Fetch a live form to see actual field names") - if st.button("๐Ÿ“ก Fetch 1 Raw Form from Repsly API", key="fetch_raw_form"): - with st.spinner("Fetching..."): - status_tmp = st.empty() - _, raw_data = _fykl1cq99( - "https://api.repsly.com/v3/export/forms/0?count=5", - (_vir4cowgz, _vrixa11dp), status_tmp, "raw form sample" - ) - status_tmp.empty() - if raw_data: - batch = raw_data.get("Forms", raw_data.get("FormResults", [])) - if batch: - st.success(f"Got {len(batch)} forms. Showing all fields:") - for idx, form in enumerate(batch[:3]): - st.write(f"**--- Form {idx + 1} ---**") - for key, val in form.items(): - val_str = str(val)[:300] - if any(t in key.lower() for t in ["date", "time", "stamp", "visit", "start", "end", "created"]): - st.markdown(f" ๐Ÿ• **{key}**: `{val_str}`") - elif any(t in key.lower() for t in ["client", "code", "account", "store", "place"]): - st.markdown(f" ๐Ÿช **{key}**: `{val_str}`") - else: - st.text(f" {key}: {val_str}") - st.divider() - else: - st.warning("API returned no forms.") - else: - st.error("API request failed.") - if db_has_data: - st.divider() - with st.sidebar: - st.header("๐Ÿ‘ค Territory Settings") - all_reps = _fdbdw2pcn() - 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 _vokep7y6w: - start_lat = _vokep7y6w[selected_rep]["lat"] - start_lon = _vokep7y6w[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.session_state.final_route_table = route_data + st.dataframe(pd.DataFrame(route_data).drop(columns=['lat', 'lon']), use_container_width=True, hide_index=True) + else: + st.error("โŒ No route found.") + + if st.session_state.get("final_route_table"): st.divider() - max_per_day = st.slider("Max Stops Per Day", 10, 40, 25) - include_inactive = st.checkbox("Include Inactive Accounts", value=False) - include_never_visited = st.checkbox("Include Never-Visited Stores", value=False, help="Stores with zero form history since 2024") - history = _fpseimvih(selected_rep, 5) - if history: - st.divider() - st.markdown("**๐Ÿ“œ Recent Routes**") - for h in history: - st.caption(f"{h['day_name']} โ€” {h['_tst']} 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() - accounts = _f9t84azyt(selected_rep, include_inactive) - _cids = [acct["code"] for acct in accounts] - _cids = [acct["code"] for acct in accounts] - metrics = _f7km3qz9w(selected_rep, _cids) - for acct in accounts: - m = (metrics.get(acct["code"]) - or metrics.get(acct.get("_rc", "")) - or {"visits": 0, "orders": 0, "_tc": 0, - "_ac": 0, "max_order": 0, "conversion": 0.0, - "last_visit": None, "first_visit": None}) - acct["visits"] = m["visits"] - acct["orders"] = m["orders"] - acct["_tc"] = m["_tc"] - acct["_ac"] = m["_ac"] - acct["max_order"] = m["max_order"] - acct["conversion"] = m["conversion"] - acct["last"] = m["last_visit"] or "Never" - earliest, latest, _ = _f1t2tala7() - if earliest and latest: + 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_up") + if order_book_file: + with st.spinner("Executing surgical formula-safe update..."): try: - s_date = datetime.datetime.strptime(earliest, "%Y-%m-%d").date() - e_date = datetime.datetime.strptime(latest, "%Y-%m-%d").date() - _tw = max(1.0, (e_date - s_date).days / 7.0) - except Exception: - _tw = 52.0 - else: - _tw = 52.0 - _vktakpuxq = {"Weekly": 7, "Bi-Weekly": 14, "Monthly": 30, "Infrequent": 60, "No Orders": 90} - all_avg_cases = [a["_ac"] for a in accounts if a["_ac"] > 0] - territory_avg_cases = sum(all_avg_cases) / len(all_avg_cases) if all_avg_cases else 10 - for acct in accounts: - vc = acct["visits"] - oc = acct["orders"] - acct["budget"] = max(10, int(10 + (acct["_ac"] * 1.5))) - if vc == 0: - acct["freq"] = "No Visits" - else: - weeks_between_visits = _tw / vc - if weeks_between_visits <= 1.2: acct["freq"] = "Weekly" - elif weeks_between_visits <= 2.5: acct["freq"] = "Bi-Weekly" - elif weeks_between_visits <= 4.5: acct["freq"] = "Monthly" - else: acct["freq"] = "Infrequent" - _vktakpuxq["No Visits"] = 90 - target = _vktakpuxq[acct["freq"]] - lv = acct["last"] - if lv and lv != "Never": - try: - _dss = (today - datetime.datetime.strptime(lv, "%Y-%m-%d").date()).days - except Exception: - _dss = 999 - else: - _dss = 999 - acct["_dss"] = _dss - acct["target"] = target - if territory_avg_cases > 0 and acct["_ac"] > 0: - revenue_weight = 1.0 + (min(acct["_ac"] / territory_avg_cases, 3.0) - 1.0) * 0.5 - else: - revenue_weight = 1.0 - if vc > 3 and acct["conversion"] < 0.2: - conv_factor = 0.85 - elif acct["conversion"] > 0.7: - conv_factor = 1.1 - else: - conv_factor = 1.0 - base_urgency = _dss / target - acct["_u"] = round(base_urgency * revenue_weight * conv_factor, 2) - acct["revenue_weight"] = round(revenue_weight, 2) - if not include_never_visited: - before_count = len(accounts) - accounts = [a for a in accounts if a["last"] != "Never"] - never_count = before_count - len(accounts) - if never_count > 0: - st.caption(f"๐Ÿ”‡ Filtered out {never_count} never-visited stores. Toggle 'Include Never-Visited' in sidebar to show them.") - if not accounts: - st.error(f"โŒ No _rtbl accounts for '{selected_rep}'.") - with st.expander("๐Ÿ” Debug โ€” Why zero accounts?"): - conn = _ft9nt3w5u() - rep_lower = selected_rep.lower().strip() - visited = conn.execute(""" - SELECT COUNT(DISTINCT client_code) as c FROM forms - WHERE LOWER(rep_name) LIKE ? AND visit_date >= '2024-01-01' - """, (f"%{rep_lower}%",)).fetchone()["c"] - visited_codes = [r["client_code"] for r in conn.execute(""" - SELECT DISTINCT client_code FROM forms - WHERE LOWER(rep_name) LIKE ? AND visit_date >= '2024-01-01' - AND client_code IS NOT NULL AND client_code != '' - """, (f"%{rep_lower}%",)).fetchall()] - in_clients = 0 - with_id = 0 - with_gps = 0 - active_count = 0 - if visited_codes: - ph = ",".join(["?"] * len(visited_codes)) - in_clients = conn.execute(f"SELECT COUNT(*) as c FROM clients WHERE client_code IN ({ph})", visited_codes).fetchone()["c"] - with_id = conn.execute(f"SELECT COUNT(*) as c FROM clients WHERE client_code IN ({ph}) AND _cid IS NOT NULL AND _cid != ''", visited_codes).fetchone()["c"] - with_gps = conn.execute(f"SELECT COUNT(*) as c FROM clients WHERE client_code IN ({ph}) AND _cid != '' AND lat != 0 AND lon != 0", visited_codes).fetchone()["c"] - active_count = conn.execute(f"SELECT COUNT(*) as c FROM clients WHERE client_code IN ({ph}) AND _cid != '' AND lat != 0 AND lon != 0 AND active = 1", visited_codes).fetchone()["c"] - tag_rows = conn.execute(f""" - SELECT LOWER(tag) as tag_lower, COUNT(*) as cnt - FROM clients - WHERE client_code IN ({ph}) AND _cid != '' AND lat != 0 AND lon != 0 AND active = 1 - GROUP BY LOWER(tag) ORDER BY cnt DESC LIMIT 15 - """, visited_codes).fetchall() + 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, ws_orig = wb_vals[sheet_name], 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: + 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 = None + + c_id = (re.search(r'[A-Z]{2}\d{4}', acc_name_str) or type('obj', (object,), {'group': lambda s: None})()).group(0) + if c_id: + for ai in ai_stops: + if ai["id"] == c_id: match_stop = ai["num"]; 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, match_stop = ratio, ai["num"] + if highest_ratio <= 0.45: match_stop = None + + 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") else: - tag_rows = [] - conn.close() - st.markdown(f""" -| Pipeline Step | Count | -|---|---| -| Stores visited by rep (since 2024) | **{visited}** | -| Found in clients table | **{in_clients}** | -| With Customer ID (XX0000) | **{with_id}** | -| With GPS coordinates | **{with_gps}** | -| Active only | **{active_count}** | -| After tag filter (buying) | **{len(accounts)}** | -""") - if tag_rows: - st.write("**Tags on this rep's visited stores:**") - for tr in tag_rows: - tag_val = tr["tag_lower"] or "(empty)" - is_buying = "โœ…" if "buying" in tag_val else "โŒ" - st.text(f" {is_buying} '{tag_val}' โ€” {tr['cnt']} accounts") - if visited == 0: - st.warning("This rep has zero form submissions since 2024. Check that the sync date range starts from 2024-01-01.") - else: - df_all = pd.DataFrame(accounts) - n_days = 10 - unique_locs = len(df_all.drop_duplicates(subset=["lat", "lon"])) - if len(df_all) < 10: - n_days = 5 - if unique_locs < n_days: - n_days = max(1, unique_locs) - if len(df_all) > n_days and unique_locs >= n_days: - kmeans = KMeans(n_clusters=n_days, random_state=42, n_init=10) - df_all["zone"] = kmeans.fit_predict(df_all[["lat", "lon"]]) - else: - df_all["zone"] = [i % n_days for i in range(len(df_all))] - _rf = [] - _sf = [] - for zone_id in range(n_days): - _zdf = df_all[df_all["zone"] == zone_id].sort_values("_u", ascending=False) - _zr = _zdf.head(max_per_day).copy() - _zs = _zdf.iloc[max_per_day:].copy() - _zr["day"] = zone_id - _rf.append(_zr) - _sf.append(_zs) - df_route = pd.concat(_rf, ignore_index=True) if _rf else pd.DataFrame() - _sdf = pd.concat(_sf, ignore_index=True) if _sf else pd.DataFrame() - _rtbl = df_route.to_dict('records') if not df_route.empty else [] - _skpd = _sdf.to_dict('records') if not _sdf.empty else [] - _od = sum(1 for a in accounts if a["_u"] > 1.0) - _ds = sum(1 for a in accounts if 0.7 <= a["_u"] <= 1.0) - _ot = len(accounts) - _od - _ds - st.markdown( - f"**{selected_rep}'s Territory:** {len(accounts)} accounts | " - f"๐Ÿ”ด **{_od} _od** | ๐ŸŸก {_ds} due soon | ๐ŸŸข {_ot} on track" - ) - if len(accounts) > len(_rtbl): - st.info(f"๐Ÿ“Š Scheduling **{len(_rtbl)}** most urgent of {len(accounts)} across 2 weeks.") - 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']} (Repsly code: {a.get('_rc', 'N/A')})") - st.caption("If these should have visit data, check that the sync date range covers their last order dates.") - weekday_names = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"] - _dcl = [ - [231, 76, 60], [52, 152, 219], [46, 204, 113], - [241, 196, 15], [155, 89, 182], - ] - _adr = {} - 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 - week_num = (day_idx // 5) + 1 - weekday_idx = day_idx % 5 - day_label = f"Wk{week_num} {weekday_names[weekday_idx]}" - nodes = [{ - "name": f"{selected_rep}'s Home", "lat": start_lat, "lon": start_lon, - "budget": 0, "addr": "Home", "freq": "-", "urg": "-", "last": "-", - "cases": "-", "visits": "-", "orders": "-", "conv": "-", - }] - 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["_u"], - "last": r["last"], "cases": r["_ac"], - "visits": r.get("visits", 0), - "orders": r.get("orders", 0), - "conv": f"{int(r.get('conversion', 0) * 100)}%", - }) - size = len(nodes) - if size < 2: - continue - _dm = [ - [0 if i == j else int(_fdppq0y9d( - 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=_dm, 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: - _rr = [] - curr = routing.Start(0) - stop_num = 0 - _tdr = 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 = _dm[prev_ni][ni] - _tdr += 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) - _rr.append({ - "Stop": "๐Ÿ " if stop_num == 0 else f"#{stop_num}", - "Store": nodes[ni]["name"], "Address": nodes[ni]["addr"], - "ETA": _f874frhoc(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"], - "Visits": nodes[ni]["visits"], - "Orders": nodes[ni]["orders"], - "Avg Cases": nodes[ni]["cases"], - "Conv %": nodes[ni]["conv"], - "lat": nodes[ni]["lat"], "lon": nodes[ni]["lon"], - }) - prev_ni = ni - curr = sol.Value(routing.NextVar(curr)) - stop_num += 1 - _adr[day_label] = { - "rows": _rr, "stops": stop_num - 1, - "drive": _tdr, "color": _dcl[weekday_idx], - } - _fpht0hl9x(selected_rep, day_label, _rr) - if _adr: - _tst = sum(d["stops"] for d in _adr.values()) - total_days = len(_adr) - n_weeks = max(1, math.ceil(total_days / 5)) - st.success(f"โœ… **{n_weeks}-week plan built!** {_tst} stops across {total_days} days for {selected_rep}") - week1_routes = {k: v for k, v in _adr.items() if k.startswith("Wk1")} - week2_routes = {k: v for k, v in _adr.items() if k.startswith("Wk2")} - week_tab_labels = ["๐Ÿ“… Week 1"] - week_data_list = [("Week 1", week1_routes)] - if week2_routes: - week_tab_labels.append("๐Ÿ“… Week 2") - week_data_list.append(("Week 2", week2_routes)) - week_tabs = st.tabs(week_tab_labels) - for week_idx, (week_label, week_routes) in enumerate(week_data_list): - with week_tabs[week_idx]: - if not week_routes: - st.info(f"No routes for {week_label}.") - continue - week_stops = sum(d["stops"] for d in week_routes.values()) - st.markdown(f"**{week_label}:** {week_stops} stops across {len(week_routes)} days") - clean_labels = [k.replace("Wk1 ", "").replace("Wk2 ", "") for k in week_routes.keys()] - day_tabs = st.tabs(clean_labels) - for tab_idx, (day_name, day_data) in enumerate(week_routes.items()): - with day_tabs[tab_idx]: - r_data = day_data["rows"] - rgb = day_data["color"] - clean_day = day_name.replace("Wk1 ", "").replace("Wk2 ", "") - st.markdown(f"**{clean_day}** โ€” {day_data['stops']} stops | ~{day_data['drive']} min driving") - display_cols = ["Stop", "Store", "Address", "ETA", "Drive", "Service", "Frequency", "Urgency", "Last Visit", "Visits", "Orders", "Avg Cases", "Conv %"] - 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) - st.divider() - st.subheader(f"๐Ÿ—บ๏ธ {week_label} Overview") - _ol = [] - _ap = [] - for day_name, day_data in week_routes.items(): - r_data = day_data["rows"] - rgb = day_data["color"] - if len(r_data) >= 2: - _ol.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] - _ol.append(pdk.Layer( - "ScatterplotLayer", data=day_pts, - get_position="[lon, lat]", get_color=rgb + [255], get_radius=300, pickable=True, - )) - _ap.extend(day_pts) - if _ap: - avg_lat = sum(p["lat"] for p in _ap) / len(_ap) - avg_lon = sum(p["lon"] for p in _ap) / len(_ap) - st.pydeck_chart(pdk.Deck( - layers=_ol, - 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.split(" ",1)[-1]} ({dd["stops"]})' - for dn, dd in week_routes.items() - ]) - st.markdown(legend, unsafe_allow_html=True) - if _skpd: - with st.expander(f"๐Ÿ“‹ {len(_skpd)} accounts NOT scheduled in 2-week plan (on track / low _u)"): - skip_df = pd.DataFrame(_skpd)[["name", "freq", "_u", "last", "_dss"]] - 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.") \ No newline at end of file + st.error("Could not locate 'ACCOUNT NAME' or 'ROUTE ORDER' columns.") + except Exception as e: + st.error(f"Error updating workbook: {e}") \ No newline at end of file