mktgtech commited on
Commit
621eddc
·
verified ·
1 Parent(s): 3e68c51

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +59 -26
app.py CHANGED
@@ -64,12 +64,17 @@ def authenticate(pwd):
64
  return True
65
 
66
  # =====================================================
67
- # DATA FETCH (FIXED FOR VISITS)
68
  # =====================================================
69
- def fetch_company_data(start_date, end_date):
70
  page = 1
71
  rows = []
72
 
 
 
 
 
 
73
  while True:
74
  try:
75
  r = requests.get(
@@ -80,9 +85,9 @@ def fetch_company_data(start_date, end_date):
80
  "end_date": end_date,
81
  "page[number]": page,
82
  "page[size]": PAGE_SIZE,
83
- "include": "location,visits" # <--- CRITICAL: Request visits data
84
  },
85
- timeout=30
86
  )
87
  r.raise_for_status()
88
  js = r.json()
@@ -94,41 +99,67 @@ def fetch_company_data(start_date, end_date):
94
  # --- MAP INCLUDED DATA ---
95
  included = js.get("included", [])
96
 
97
- # 1. Map Locations by ID
98
  loc_map = {
99
- i["id"]: i["attributes"]
100
  for i in included
101
  if i["type"] == "locations"
102
  }
103
 
104
- # 2. Map Visits by ID (to lookup landing pages)
105
  visit_map = {
106
- i["id"]: i["attributes"]
107
  for i in included
108
  if i["type"] == "visits"
109
  }
110
 
 
 
 
 
 
 
 
111
  for lead in data:
112
  a = lead["attributes"]
113
 
114
  # --- LOGIC: GET LATEST VISIT ---
115
- landing = None
116
- exit_page = None
117
 
118
- # The 'relationships' key contains a list of visit IDs for this company
119
  visit_refs = lead.get("relationships", {}).get("visits", {}).get("data", [])
120
 
121
  if visit_refs:
122
- # We take the last visit in the list, assuming it is the most recent
123
- latest_visit_id = visit_refs[-1]["id"]
124
 
125
- # Look up the details in our map
126
- visit_details = visit_map.get(latest_visit_id, {})
127
- landing = visit_details.get("landing_page_path")
128
- exit_page = visit_details.get("exit_page_path")
129
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
130
  # --- LOGIC: GET LOCATION ---
131
- loc_id = lead.get("relationships", {}).get("location", {}).get("data", {}).get("id")
 
132
  loc = loc_map.get(loc_id, {})
133
 
134
  rows.append({
@@ -146,10 +177,8 @@ def fetch_company_data(start_date, end_date):
146
  "total_visits": a.get("visits"),
147
  "lead_quality_score": a.get("quality"),
148
  "employee_count": a.get("employee_count"),
149
- "employees_min": a.get("employees_range", {}).get("min")
150
- if a.get("employees_range") else None,
151
- "employees_max": a.get("employees_range", {}).get("max")
152
- if a.get("employees_range") else None,
153
  "revenue": a.get("revenue"),
154
  "assignee": a.get("assignee"),
155
  "emailed_to": a.get("emailed_to"),
@@ -161,8 +190,8 @@ def fetch_company_data(start_date, end_date):
161
  "facebook_url": a.get("facebook_url"),
162
 
163
  # --- NEW FIELDS ---
164
- "landing_page_path": landing,
165
- "exit_page_path": exit_page,
166
  # ------------------
167
 
168
  "country": loc.get("country"),
@@ -171,10 +200,14 @@ def fetch_company_data(start_date, end_date):
171
  "leadfeeder_url": a.get("view_in_leadfeeder"),
172
  })
173
 
 
174
  page += 1
175
 
176
  except requests.exceptions.RequestException as e:
177
  print(f"Error fetching page {page}: {e}")
 
 
 
178
  break
179
 
180
  df = pd.DataFrame(rows)
@@ -183,7 +216,7 @@ def fetch_company_data(start_date, end_date):
183
  return df
184
 
185
  # =====================================================
186
- # LOAD WRAPPER (STATE SAFE)
187
  # =====================================================
188
  def load_data_with_preview(start_date, end_date):
189
  df = fetch_company_data(start_date, end_date)
 
64
  return True
65
 
66
  # =====================================================
67
+ # DATA FETCH (DEEP DIVE FOR PAGE VIEWS)
68
  # =====================================================
69
+ def fetch_company_data(start_date, end_date, progress=gr.Progress()):
70
  page = 1
71
  rows = []
72
 
73
+ # We ask for "visits.page_views" to get the nested URL data
74
+ include_param = "location,visits,visits.page_views"
75
+
76
+ print(f"🚀 Starting fetch for {start_date} to {end_date}...")
77
+
78
  while True:
79
  try:
80
  r = requests.get(
 
85
  "end_date": end_date,
86
  "page[number]": page,
87
  "page[size]": PAGE_SIZE,
88
+ "include": include_param
89
  },
90
+ timeout=45 # Increased timeout for heavier query
91
  )
92
  r.raise_for_status()
93
  js = r.json()
 
99
  # --- MAP INCLUDED DATA ---
100
  included = js.get("included", [])
101
 
102
+ # 1. Map Locations
103
  loc_map = {
104
+ str(i["id"]): i["attributes"]
105
  for i in included
106
  if i["type"] == "locations"
107
  }
108
 
109
+ # 2. Map Visits
110
  visit_map = {
111
+ str(i["id"]): i["attributes"]
112
  for i in included
113
  if i["type"] == "visits"
114
  }
115
 
116
+ # 3. Map Page Views (This is where the URL lives)
117
+ page_view_map = {
118
+ str(i["id"]): i["attributes"]
119
+ for i in included
120
+ if i["type"] == "page_views"
121
+ }
122
+
123
  for lead in data:
124
  a = lead["attributes"]
125
 
126
  # --- LOGIC: GET LATEST VISIT ---
127
+ landing_url = None
128
+ exit_url = None
129
 
130
+ # Get visit IDs
131
  visit_refs = lead.get("relationships", {}).get("visits", {}).get("data", [])
132
 
133
  if visit_refs:
134
+ # Get the ID of the LAST visit (Most recent)
135
+ latest_visit_id = str(visit_refs[-1]["id"])
136
 
137
+ # Find that visit in the included list to check its relationships
138
+ # Note: We need the RELATIONSHIP object for the visit, not just attributes
139
+ # We have to scan 'included' again or build a relationship map.
140
+ # Optimization: We loop through included only if needed or build a full map.
141
+
142
+ # Efficient approach: Find the visit object in 'included' list directly
143
+ visit_obj = next((item for item in included if str(item["id"]) == latest_visit_id and item["type"] == "visits"), None)
144
+
145
+ if visit_obj:
146
+ # Get Page Views for this specific visit
147
+ pv_refs = visit_obj.get("relationships", {}).get("page_views", {}).get("data", [])
148
+
149
+ if pv_refs:
150
+ # FIRST Page View = Landing Page
151
+ first_pv_id = str(pv_refs[0]["id"])
152
+ if first_pv_id in page_view_map:
153
+ landing_url = page_view_map[first_pv_id].get("url") or page_view_map[first_pv_id].get("path")
154
+
155
+ # LAST Page View = Exit Page
156
+ last_pv_id = str(pv_refs[-1]["id"])
157
+ if last_pv_id in page_view_map:
158
+ exit_url = page_view_map[last_pv_id].get("url") or page_view_map[last_pv_id].get("path")
159
+
160
  # --- LOGIC: GET LOCATION ---
161
+ loc_id_ref = lead.get("relationships", {}).get("location", {}).get("data", {})
162
+ loc_id = str(loc_id_ref.get("id")) if loc_id_ref else None
163
  loc = loc_map.get(loc_id, {})
164
 
165
  rows.append({
 
177
  "total_visits": a.get("visits"),
178
  "lead_quality_score": a.get("quality"),
179
  "employee_count": a.get("employee_count"),
180
+ "employees_min": a.get("employees_range", {}).get("min") if a.get("employees_range") else None,
181
+ "employees_max": a.get("employees_range", {}).get("max") if a.get("employees_range") else None,
 
 
182
  "revenue": a.get("revenue"),
183
  "assignee": a.get("assignee"),
184
  "emailed_to": a.get("emailed_to"),
 
190
  "facebook_url": a.get("facebook_url"),
191
 
192
  # --- NEW FIELDS ---
193
+ "landing_page_path": landing_url,
194
+ "exit_page_path": exit_url,
195
  # ------------------
196
 
197
  "country": loc.get("country"),
 
200
  "leadfeeder_url": a.get("view_in_leadfeeder"),
201
  })
202
 
203
+ print(f"✅ Page {page} processed. Total rows: {len(rows)}")
204
  page += 1
205
 
206
  except requests.exceptions.RequestException as e:
207
  print(f"Error fetching page {page}: {e}")
208
+ # If the complex include fails (400 Bad Request), you might see it here.
209
+ if "400" in str(e):
210
+ print("❌ The API rejected the nested include. Your plan might not support 'visits.page_views'.")
211
  break
212
 
213
  df = pd.DataFrame(rows)
 
216
  return df
217
 
218
  # =====================================================
219
+ # LOAD WRAPPER
220
  # =====================================================
221
  def load_data_with_preview(start_date, end_date):
222
  df = fetch_company_data(start_date, end_date)