Spaces:
Runtime error
Runtime error
Update app.py
Browse files542 unmodified lines5435445455465475485492 unmodified lines5525535545555565575585595605615625635645655665 unmodified lines5725735745755765775785795807 unmodified lines58858959059159259359459559659759859960060160260360460560640 unmodified lines64764864965065165265319 unmodified lines67367467567667767867932 unmodified lines71271371471571671771864 unmodified lines78378478578678778878931 unmodified lines821822823824825826827542 unmodified linesr_data = data.get("Representatives", data) if isinstance(data, dict) else datast.session_state.db_reps = sorted(list(set([r.get("Name") for r in r_data if isinstance(r, dict) and r.get("Name")])))# 2. Get Clientsstatus_text.info("📡 **Downloading Master Account List... (This takes a moment)**")clients = []last_id = "0"2 unmodified linesres = requests.get(url, auth=(API_USERNAME, API_PASSWORD), timeout=15)if res.status_code != 200: breakdata = res.json()clients.extend(data.get("Clients", []))meta = data.get("Meta", {})if meta.get("TotalCount", 0) == 0: breaknew_last_id = meta.get("LastID", "")if str(new_last_id) == str(last_id) or not new_last_id: breaklast_id = str(new_last_id)st.session_state.db_clients = clients# 3. Get Forms (The Shredder)status_text.info(f"📡 **Scanning Order History from {start_date} to {end_date}... (Do Not Refresh)**")forms_slim = []start_ts = int(datetime.datetime.combine(start_date, datetime.datetime.min.time()).timestamp())5 unmodified linesres = requests.get(url, auth=(API_USERNAME, API_PASSWORD), timeout=15)if res.status_code != 200: breakdata = res.json()f_data = data.get("FormResults", [])for form in f_data:rep_name = form.get("RepresentativeName", "")form_name = str(form.get("FormName", "")).lower()client_code = form.get("ClientCode", "")7 unmodified linesforms_slim.append({"Rep": rep_name, "Client": client_code, "Cases": case_count, "FormName": form_name})meta = data.get("MetaCollectionResult", data.get("Meta", {}))if meta.get("TotalCount", 0) == 0: breaknew_ts = meta.get("LastTimeStamp", "")if not new_ts or str(new_ts) == str(last_ts): breakif int(new_ts) > end_ts: breaklast_ts = str(new_ts)st.session_state.db_forms = forms_slim# Lock dates into memory so the math engine uses the exact same timeframe!st.session_state.sync_start_date = start_datest.session_state.sync_end_date = end_date# SUCCESS! Lock the state and reload the page.st.session_state.is_synced = Truest.rerun()40 unmodified linesall_clients = st.session_state.db_clientsall_forms = st.session_state.db_forms# 1. Find officially assigned accounts (With Strict Bad Data Patch)assigned_accounts = {}for client in all_clients:rep_name = client.get("Representative", "")19 unmodified lines"Order_Count": 0, "Total_Cases": 0}# 2. The Ghost Fallback Engine (If assigned == 0)if len(assigned_accounts) == 0:st.toast("⚠️ No officially assigned accounts found. Searching through order history instead...")ghost_codes = set()32 unmodified linesassigned_accounts[client_code]["Order_Count"] += 1assigned_accounts[client_code]["Total_Cases"] += form["Cases"]# Robust Date Math Check (Prevents zero/negative days if user picked dates poorly)s_date = st.session_state.sync_start_datee_date = st.session_state.sync_end_dateif s_date and e_date:64 unmodified linestransit_idx = routing.RegisterTransitCallback(t_callback)routing.SetArcCostEvaluatorOfAllVehicles(transit_idx)# Capacity Patch: Up to 10,000 minutes (7 days of buffer) so it never drops heavy storesrouting.AddDimension(transit_idx, 10000, 10000, True, 'Time')time_dim = routing.GetDimensionOrDie('Time')31 unmodified linesc_rgb = colors[i % len(colors)]# Visual Patch: Only draw the blue lines if there are at least 2 locations (Home + Store)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))542 unmodified lines5435445455465475485492 unmodified lines5525535545555565575585595605615625635645655665675685695705715725 unmodified lines5785795805815825835845855865877 unmodified lines59559659759859960060160260360460560660760860961061161261361440 unmodified lines65565665765865966066119 unmodified lines68168268368468568668732 unmodified lines72072172272372472564 unmodified lines79079179279379479531 unmodified lines827828829830831832542 unmodified linesr_data = data.get("Representatives", data) if isinstance(data, dict) else datast.session_state.db_reps = sorted(list(set([r.get("Name") for r in r_data if isinstance(r, dict) and r.get("Name")])))# 2. Get Clients (BRUTE FORCE PAGINATION FIX)status_text.info("📡 **Downloading Master Account List... (This takes a moment)**")clients = []last_id = "0"2 unmodified linesres = requests.get(url, auth=(API_USERNAME, API_PASSWORD), timeout=15)if res.status_code != 200: breakdata = res.json()fetched_clients = data.get("Clients", [])clients.extend(fetched_clients)meta = data.get("MetaCollectionResult", data.get("Meta", {}))new_last_id = str(meta.get("LastID", ""))# The unbreakable loop checkif not fetched_clients or not new_last_id or new_last_id == str(last_id):breaklast_id = new_last_idst.session_state.db_clients = clients# 3. Get Forms (BRUTE FORCE PAGINATION FIX)status_text.info(f"📡 **Scanning Order History from {start_date} to {end_date}... (Do Not Refresh)**")forms_slim = []start_ts = int(datetime.datetime.combine(start_date, datetime.datetime.min.time()).timestamp())5 unmodified linesres = requests.get(url, auth=(API_USERNAME, API_PASSWORD), timeout=15)if res.status_code != 200: breakdata = res.json()fetched_forms = data.get("FormResults", [])for form in fetched_forms:rep_name = form.get("RepresentativeName", "")form_name = str(form.get("FormName", "")).lower()client_code = form.get("ClientCode", "")7 unmodified linesforms_slim.append({"Rep": rep_name, "Client": client_code, "Cases": case_count, "FormName": form_name})meta = data.get("MetaCollectionResult", data.get("Meta", {}))new_ts = str(meta.get("LastTimeStamp", ""))# The unbreakable loop checkif not fetched_forms or not new_ts or new_ts == str(last_ts):breakif int(new_ts) > end_ts:breaklast_ts = new_tsst.session_state.db_forms = forms_slimst.session_state.sync_start_date = start_datest.session_state.sync_end_date = end_datest.session_state.is_synced = Truest.rerun()40 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", "")19 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()32 unmodified linesassigned_accounts[client_code]["Order_Count"] += 1assigned_accounts[client_code]["Total_Cases"] += form["Cases"]s_date = st.session_state.sync_start_datee_date = st.session_state.sync_end_dateif s_date and e_date:64 unmodified linestransit_idx = routing.RegisterTransitCallback(t_callback)routing.SetArcCostEvaluatorOfAllVehicles(transit_idx)routing.AddDimension(transit_idx, 10000, 10000, True, 'Time')time_dim = routing.GetDimensionOrDie('Time')31 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))
app.py+27-22