Spaces:
Runtime error
Runtime error
Update app.py
Browse files98 unmodified lines991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701 unmodified line1721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572584 unmodified lines263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298227 unmodified lines526527528529530531532197 unmodified lines7307317327337347357368 unmodified lines74574674774874975075175275375475575650 unmodified lines80780880981081181281381481581681781814 unmodified lines83383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187242 unmodified lines91591691791891992092157 unmodified lines97998098198298398498 unmodified linesdef to_minutes(time_str):return parse_single_time(time_str, 420)# ==============================================================================# 🔧 FIXED PAGINATION ENGINE# Repsly stores pagination info inside "MetaCollectionResult" -> "LastID" or# "LastTimeStamp". The old helper only searched the top-level dict and missed it.# Page size is 100 (not 50), so we must never break early on record count alone.# ==============================================================================REPSLY_PAGE_SIZE = 100 # Repsly's hard page size for all v3 export endpointsdef extract_pagination_key(data_dict, target_key):"""Robustly pull a pagination cursor out of a Repsly response.Search order:1. MetaCollectionResult (the standard Repsly v3 envelope)2. Top-level keys (some endpoints flatten it)3. Any nested dict one level down (legacy fallback)All comparisons are case-insensitive to handle Repsly's LastID / LastId typo."""if not isinstance(data_dict, dict):return ""target_lower = target_key.lower()# 1. Preferred location: MetaCollectionResult sub-objectmeta = data_dict.get("MetaCollectionResult") or data_dict.get("metaCollectionResult") or {}for k, v in meta.items():if str(k).lower() == target_lower:return str(v)# 2. Top-level keysfor k, v in data_dict.items():if str(k).lower() == target_lower:return str(v)# 3. Any other one-level-deep nested dictfor 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 str(sub_v)return ""def fetch_all_clients(api_user, api_pass, status_placeholder):"""Download every client record from Repsly using cursor-based pagination.Fix summary vs. old code:- Never breaks on `len(batch) < 50`; only stops when the batch is emptyor the cursor stops advancing (true end-of-data signal).- Reads LastID from MetaCollectionResult first (the correct location).- Uses REPSLY_PAGE_SIZE (100) as the sanity check, not 50."""clients = []last_id = "0"consecutive_no_advance = 0 # safety valve against infinite loopswhile True:status_placeholder.info(f"📡 **Downloading Master Account List… ({len(clients)} accounts fetched so far)**")url = f"https://api.repsly.com/v3/export/clients/{last_id}"try:res = requests.get(url, auth=(api_user, api_pass), timeout=30)except requests.RequestException as e:1 unmodified linebreakif res.status_code != 200:status_placeholder.warning(f"⚠️ Clients API returned HTTP {res.status_code} — stopping pagination.")breakdata = res.json()batch = data.get("Clients", [])if not batch:# Repsly signals last page with an empty listbreakclients.extend(batch)# If the batch is smaller than a full page we're definitely done,# but we still try to read the cursor for correctness.new_last_id = extract_pagination_key(data, "lastid")if not new_last_id or new_last_id == str(last_id):# Cursor didn't advance — we've reached the endconsecutive_no_advance += 1if consecutive_no_advance >= 2 or len(batch) < REPSLY_PAGE_SIZE:breakelse:consecutive_no_advance = 0last_id = new_last_id# Belt-and-suspenders: if the batch was under a full page, stop.if len(batch) < REPSLY_PAGE_SIZE:breakreturn clientsdef fetch_all_forms(api_user, api_pass, start_date, end_date, status_placeholder):"""Download all form results in the given date range using timestamp pagination.Fix summary vs. old code:- Never breaks on `len(batch) < 50`.- Reads LastTimeStamp from MetaCollectionResult first.- Properly compares integer timestamps to avoid off-by-one infinite loops.- Respects end_date hard stop."""forms_slim = []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_ts = str(start_ts)consecutive_no_advance = 0while True:status_placeholder.info(f"📡 **Scanning Order History… ({len(forms_slim)} forms processed so far)**")url = f"https://api.repsly.com/v3/export/formresults/{last_ts}"try:res = requests.get(url, auth=(api_user, api_pass), timeout=30)except requests.RequestException as e:status_placeholder.error(f"Network error fetching forms: {e}")breakif res.status_code != 200:status_placeholder.warning(f"⚠️ Forms API returned HTTP {res.status_code} — stopping pagination.")breakdata = res.json()batch = data.get("FormResults", [])if not batch:break# Filter and slim down each form in this batchfor form in batch:rep_name = form.get("RepresentativeName", "")form_name = str(form.get("FormName", "")).lower()4 unmodified linesfor 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):passforms_slim.append({"Rep": rep_name,"Client": client_code,"Cases": case_count,"FormName": form_name})# Advance cursornew_ts = extract_pagination_key(data, "lasttimestamp")if not new_ts or new_ts == str(last_ts):consecutive_no_advance += 1if consecutive_no_advance >= 2 or len(batch) < REPSLY_PAGE_SIZE:breakelse:consecutive_no_advance = 0# Hard stop: don't page past the user's requested end dateif int(new_ts) > end_ts:breaklast_ts = new_tsif len(batch) < REPSLY_PAGE_SIZE:breakreturn forms_slim227 unmodified linessearch_parameters = pywrapcp.DefaultRoutingSearchParameters()search_parameters.first_solution_strategy = routing_enums_pb2.FirstSolutionStrategy.PATH_CHEAPEST_ARCsearch_parameters.local_search_metaheuristic = routing_enums_pb2.LocalSearchMetaheuristic.GUIDED_LOCAL_SEARCHsearch_parameters.time_limit.seconds = 2solution = routing.SolveWithParameters(search_parameters)197 unmodified linesstatus_text = st.empty()try:# ── 1. Get Reps ──────────────────────────────────────────status_text.info("📡 **Downloading Sales Rep Roster...**")res = requests.get("https://api.repsly.com/v3/export/representatives",8 unmodified linesif isinstance(r, dict) and r.get("Name")])))# ── 2. Get ALL Clients (fixed pagination) ────────────────st.session_state.db_clients = fetch_all_clients(API_USERNAME, API_PASSWORD, status_text)# ── 3. Get ALL Forms (fixed pagination) ──────────────────st.session_state.db_forms = fetch_all_forms(API_USERNAME, API_PASSWORD, start_date, end_date, status_text)50 unmodified linesall_clients = st.session_state.db_clientsall_forms = st.session_state.db_forms# 1. Find officially assigned accountsassigned_accounts = {}for client in all_clients:rep_name = client.get("Representative", "")if selected_rep.lower() in str(rep_name).lower():client_code = client.get("ClientCode", client.get("ClientID", "UNK"))lat_raw = client.get("Latitude")lon_raw = client.get("Longitude")tags_data = client.get("Tags", [])14 unmodified lines"Order_Count": 0, "Total_Cases": 0}# 2. The Ghost Fallback Engineif len(assigned_accounts) == 0:st.toast("⚠️ No officially assigned accounts found. Searching through order history instead...")ghost_codes = set()for form in all_forms:if selected_rep.lower() in str(form["Rep"]).lower():if form["Client"]: ghost_codes.add(form["Client"])for client in all_clients:client_code = client.get("ClientCode", client.get("ClientID", "UNK"))if client_code in ghost_codes:lat_raw = client.get("Latitude")lon_raw = client.get("Longitude")tags_data = client.get("Tags", [])tags_str = ", ".join(tags_data) if isinstance(tags_data, list) else str(tags_data)if not tags_str.strip(): tags_str = "Untagged"try:lat = float(lat_raw) if lat_raw else 0.0lon = float(lon_raw) if lon_raw else 0.0valid_gps = (lat != 0.0 and lon != 0.0)except (ValueError, TypeError):valid_gps = Falseif valid_gps:assigned_accounts[client_code] = {"Store_ID": client_code, "Store_Name": client.get("Name", "Unknown Store"),"Lat": lat, "Lon": lon, "Territory_Tag": tags_str,"Order_Count": 0, "Total_Cases": 0}# 3. Process Volume Mathfor form in all_forms:if selected_rep.lower() in str(form["Rep"]).lower():client_code = form["Client"]if client_code in assigned_accounts:assigned_accounts[client_code]["Order_Count"] += 142 unmodified linest_df = df_sales[df_sales['Territory_Tag'] == t_tag].reset_index(drop=True)num_sub_days = math.ceil(len(t_df) / 25)if num_sub_days > 1:kmeans = KMeans(n_clusters=num_sub_days, random_state=42, n_init=10)t_df['Sub_Day'] = kmeans.fit_predict(t_df[['Lat', 'Lon']])else:57 unmodified linesc_rgb = colors[i % len(colors)]if len(r_data) >= 2:map_layers.append(pdk.Layer("PathLayer", data=[{"path": [[p['lon'], p['lat']] for p in r_data]}], get_path="path", get_color=c_rgb + [200], width_scale=20, get_width=5))98 unmodified lines991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351 unmodified line1371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871884 unmodified lines193194195196197198199200201202203204205206207208209210211212213214215216217227 unmodified lines445446447448449450451197 unmodified lines6496506516526536546558 unmodified lines66466566666766866967067167267367467550 unmodified lines72672772872973073173273373473573673773873974074174274374474574614 unmodified lines76176276376476576676776876942 unmodified lines81281381481581681781881982082157 unmodified lines87988088188288388488598 unmodified linesdef to_minutes(time_str):return parse_single_time(time_str, 420)# ==============================================================================# 🔧 UNBREAKABLE PAGINATION ENGINE# ==============================================================================def extract_pagination_key(data_dict, target_key):"""Case-insensitive search to fix Repsly's API LastId vs LastID typo bug"""if not isinstance(data_dict, dict): return ""target_lower = target_key.lower()meta = data_dict.get("MetaCollectionResult") or data_dict.get("metaCollectionResult") or {}for k, v in meta.items():if str(k).lower() == target_lower: return str(v)for k, v in data_dict.items():if str(k).lower() == target_lower: return 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 str(sub_v)return ""def fetch_all_clients(api_user, api_pass, status_placeholder):clients = []last_id = "0"consecutive_no_advance = 0while True:status_placeholder.info(f"📡 **Downloading Master Account List… ({len(clients)} accounts fetched so far)**")url = f"https://api.repsly.com/v3/export/clients/{last_id}"try:res = requests.get(url, auth=(api_user, api_pass), timeout=30)except requests.RequestException as e:1 unmodified linebreakif res.status_code != 200:status_placeholder.warning(f"⚠️ Clients API returned HTTP {res.status_code} — stopping pagination.")breakdata = res.json()batch = data.get("Clients", [])# PURE LOGIC: If the page is completely empty, we are done.if not batch: breakclients.extend(batch)new_last_id = extract_pagination_key(data, "lastid")if not new_last_id or new_last_id == str(last_id):consecutive_no_advance += 1if consecutive_no_advance >= 2: breakelse:consecutive_no_advance = 0last_id = new_last_idreturn clientsdef fetch_all_forms(api_user, api_pass, start_date, end_date, status_placeholder):forms_slim = []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_ts = str(start_ts)consecutive_no_advance = 0while True:status_placeholder.info(f"📡 **Scanning Order History… ({len(forms_slim)} forms processed so far)**")url = f"https://api.repsly.com/v3/export/formresults/{last_ts}"try:res = requests.get(url, auth=(api_user, api_pass), timeout=30)except requests.RequestException as e:status_placeholder.error(f"Network error fetching forms: {e}")breakif res.status_code != 200: breakdata = res.json()batch = data.get("FormResults", [])# PURE LOGIC: If the page is completely empty, we are done.if not batch: breakfor form in batch:rep_name = form.get("RepresentativeName", "")form_name = str(form.get("FormName", "")).lower()4 unmodified linesfor 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): passforms_slim.append({"Rep": rep_name,"Client": client_code,"Cases": case_count,"FormName": form_name})new_ts = extract_pagination_key(data, "lasttimestamp")if not new_ts or new_ts == str(last_ts):consecutive_no_advance += 1if consecutive_no_advance >= 2: breakelse:consecutive_no_advance = 0if int(new_ts) > end_ts: breaklast_ts = new_tsreturn forms_slim227 unmodified linessearch_parameters = pywrapcp.DefaultRoutingSearchParameters()search_parameters.first_solution_strategy = routing_enums_pb2.FirstSolutionStrategy.PATH_CHEAPEST_ARCsearch_parameters.local_search_metaheuristic = routing_enums_pb2.LocalSearchMetaheuristic.GUIDED_LOCAL_SEARCHsearch_parameters.time_limit.seconds = 2 # FASTEST SOLVEsolution = routing.SolveWithParameters(search_parameters)197 unmodified linesstatus_text = st.empty()try:# 1. Get Repsstatus_text.info("📡 **Downloading Sales Rep Roster...**")res = requests.get("https://api.repsly.com/v3/export/representatives",8 unmodified linesif isinstance(r, dict) and r.get("Name")])))# 2. Get ALL Clients (fixed pagination)st.session_state.db_clients = fetch_all_clients(API_USERNAME, API_PASSWORD, status_text)# 3. Get ALL Forms (fixed pagination)st.session_state.db_forms = fetch_all_forms(API_USERNAME, API_PASSWORD, start_date, end_date, status_text)50 unmodified linesall_clients = st.session_state.db_clientsall_forms = st.session_state.db_forms# 1 & 2. Find ALL accounts (Merge Assigned + Ghost Order History)assigned_accounts = {}ghost_codes = set()# Look at order history first to find where they actually wentfor form in all_forms:if selected_rep.lower() == str(form["Rep"]).lower().strip():if form["Client"]: ghost_codes.add(form["Client"])for client in all_clients:rep_name = str(client.get("Representative", "")).lower().strip()client_code = client.get("ClientCode", client.get("ClientID", "UNK"))# Add if officially assigned OR if found in their ghost order historyif selected_rep.lower() == rep_name or client_code in ghost_codes:lat_raw = client.get("Latitude")lon_raw = client.get("Longitude")tags_data = client.get("Tags", [])14 unmodified lines"Order_Count": 0, "Total_Cases": 0}# 3. Process Volume Math (Exact string match to prevent "David" bleed)for form in all_forms:if selected_rep.lower() == str(form["Rep"]).lower().strip():client_code = form["Client"]if client_code in assigned_accounts:assigned_accounts[client_code]["Order_Count"] += 142 unmodified linest_df = df_sales[df_sales['Territory_Tag'] == t_tag].reset_index(drop=True)num_sub_days = math.ceil(len(t_df) / 25)# Patch: Ensure we have enough UNIQUE locations to satisfy the cluster countunique_locations = len(t_df.drop_duplicates(subset=['Lat', 'Lon']))if num_sub_days > 1 and unique_locations >= num_sub_days:kmeans = KMeans(n_clusters=num_sub_days, random_state=42, n_init=10)t_df['Sub_Day'] = kmeans.fit_predict(t_df[['Lat', 'Lon']])else:57 unmodified linesc_rgb = colors[i % len(colors)]# Visual Patch: Only draw the blue lines if there are at least 2 locationsif len(r_data) >= 2:map_layers.append(pdk.Layer("PathLayer", data=[{"path": [[p['lon'], p['lat']] for p in r_data]}], get_path="path", get_color=c_rgb + [200], width_scale=20, get_width=5))
app.py+51-150