GuglielmoTor commited on
Commit
fe99c78
·
verified ·
1 Parent(s): ca925bb

Update sync_logic.py

Browse files
Files changed (1) hide show
  1. sync_logic.py +135 -125
sync_logic.py CHANGED
@@ -268,23 +268,35 @@ def sync_linkedin_mentions(token_state):
268
  return mentions_sync_message, token_state
269
 
270
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
271
  def sync_linkedin_follower_stats(token_state):
272
  """
273
  Fetches new/updated LinkedIn follower statistics and uploads/updates them in Bubble,
274
- if scheduled by state_manager.
275
- For both monthly gains and demographics, updates counts only if the new LinkedIn count is greater.
276
- Creates new records if the category/month doesn't exist.
277
  """
278
- logging.info("Starting LinkedIn follower stats sync process check.")
279
 
280
  if not token_state.get("fs_should_sync_now", False):
281
- logging.info("Follower Stats sync: Not scheduled by state_manager. Skipping.")
282
  return "Follower Stats: Sync not currently required by schedule. ", token_state
283
 
284
- logging.info("Follower Stats sync: Proceeding as scheduled by state_manager.")
285
 
286
  if not token_state or not token_state.get("token"):
287
- logging.error("Follower Stats sync: Access denied. No LinkedIn token.")
288
  org_urn_for_log = token_state.get('org_urn') if token_state else None
289
  if org_urn_for_log:
290
  token_state = _log_sync_attempt(org_urn_for_log, LOG_SUBJECT_FOLLOWER_STATS, token_state)
@@ -299,126 +311,135 @@ def sync_linkedin_follower_stats(token_state):
299
  attempt_logged = False
300
 
301
  if not org_urn or not client_id or client_id == "ENV VAR MISSING":
302
- logging.error("Follower Stats sync: Configuration error (Org URN or Client ID missing).")
303
  if org_urn:
304
  token_state = _log_sync_attempt(org_urn, LOG_SUBJECT_FOLLOWER_STATS, token_state)
305
  attempt_logged = True
306
  return "Follower Stats: Config error. ", token_state
307
-
308
-
309
- logging.info(f"{bubble_follower_stats_df_orig.columns}")
310
- # Ensure the BUBBLE_UNIQUE_ID_COLUMN_NAME exists in the DataFrame if it's not empty,
311
- # as it's crucial for building the maps for updates.
312
  if not bubble_follower_stats_df_orig.empty and BUBBLE_UNIQUE_ID_COLUMN_NAME not in bubble_follower_stats_df_orig.columns:
313
- logging.error(f"Follower Stats sync: Critical error - '{BUBBLE_UNIQUE_ID_COLUMN_NAME}' column missing in bubble_follower_stats_df. Cannot proceed with updates.")
314
  if org_urn:
315
- token_state = _log_sync_attempt(org_urn, LOG_SUBJECT_FOLLOWER_STATS, token_state) # Log the attempt despite error
316
  attempt_logged = True
317
  return f"Follower Stats: Config error ({BUBBLE_UNIQUE_ID_COLUMN_NAME} missing). ", token_state
318
 
319
- logging.info(f"Follower stats sync proceeding for org_urn: {org_urn}")
320
  try:
321
  api_follower_stats = get_linkedin_follower_stats(client_id, token_dict, org_urn)
322
 
323
- if not api_follower_stats:
324
- logging.info(f"Follower Stats sync: No stats found via API for org {org_urn}.")
325
  follower_stats_sync_message = "Follower Stats: None found via API. "
326
  token_state = _log_sync_attempt(org_urn, LOG_SUBJECT_FOLLOWER_STATS, token_state)
327
  attempt_logged = True
328
  return follower_stats_sync_message, token_state
329
 
330
  stats_for_bulk_upload = []
331
- records_to_update_via_patch = [] # List of tuples: (bubble_id, fields_to_update_dict)
332
 
333
- # --- Prepare maps for existing data in Bubble for efficient lookup ---
334
- # Key: (org_urn, type, category_identifier), Value: (organic, paid, bubble_record_id)
335
- # For monthly gains, category_identifier is the formatted date string.
336
- # For demographics, category_identifier is the FOLLOWER_STATS_CATEGORY_COLUMN value.
337
  existing_stats_map = {}
338
  stats_required_cols = [
339
  FOLLOWER_STATS_ORG_URN_COLUMN, FOLLOWER_STATS_TYPE_COLUMN,
340
- FOLLOWER_STATS_CATEGORY_COLUMN, FOLLOWER_STATS_ORGANIC_COLUMN, # Assuming these apply to monthly too
341
- FOLLOWER_STATS_PAID_COLUMN, # Assuming these apply to monthly too
342
- BUBBLE_UNIQUE_ID_COLUMN_NAME
343
  ]
344
 
 
345
  if not bubble_follower_stats_df_orig.empty and all(col in bubble_follower_stats_df_orig.columns for col in stats_required_cols):
346
- for _, row in bubble_follower_stats_df_orig.iterrows():
347
- category_identifier = str(row[FOLLOWER_STATS_CATEGORY_COLUMN])
348
- # For monthly gains, ensure category (date) is consistently formatted if needed
349
- if row[FOLLOWER_STATS_TYPE_COLUMN] == 'follower_gains_monthly':
350
- try:
351
- category_identifier = pd.to_datetime(row[FOLLOWER_STATS_CATEGORY_COLUMN], errors='coerce').strftime('%Y-%m-%d')
352
- if category_identifier == 'NaT': # Handle parsing errors
353
- logging.warning(f"Could not parse date for existing monthly gain: {row[FOLLOWER_STATS_CATEGORY_COLUMN]}. Skipping this entry for map.")
354
- continue
355
- except Exception: # Catch any other parsing issues
356
- logging.warning(f"Error parsing date for existing monthly gain: {row[FOLLOWER_STATS_CATEGORY_COLUMN]}. Skipping this entry for map.")
 
 
 
 
357
  continue
 
 
 
 
358
 
359
- key = (
360
- str(row[FOLLOWER_STATS_ORG_URN_COLUMN]),
361
- str(row[FOLLOWER_STATS_TYPE_COLUMN]),
362
- category_identifier
363
- )
 
 
 
364
  existing_stats_map[key] = (
365
- row[FOLLOWER_STATS_ORGANIC_COLUMN], # Assuming monthly gains have this
366
- row[FOLLOWER_STATS_PAID_COLUMN], # Assuming monthly gains have this
367
- row[BUBBLE_UNIQUE_ID_COLUMN_NAME]
368
  )
369
- elif not bubble_follower_stats_df_orig.empty:
370
- logging.warning(f"Follower Stats: Data in Bubble is missing one or more required columns for update logic: {stats_required_cols}. Will treat all API stats as new if not matched by key elements.")
371
 
 
 
 
 
372
 
373
- # --- Process all stats from API (monthly gains and demographics) ---
374
- for stat_from_api in api_follower_stats:
375
- api_type = str(stat_from_api.get(FOLLOWER_STATS_TYPE_COLUMN))
 
376
  api_category_raw = stat_from_api.get(FOLLOWER_STATS_CATEGORY_COLUMN)
377
 
378
- api_category_identifier = str(api_category_raw)
379
- if api_type == 'follower_gains_monthly':
380
- try:
381
- api_category_identifier = pd.to_datetime(api_category_raw, errors='coerce').strftime('%Y-%m-%d')
382
- if api_category_identifier == 'NaT':
383
- logging.warning(f"Could not parse date from API for monthly gain: {api_category_raw}. Skipping this API stat.")
384
- continue
385
- except Exception:
386
- logging.warning(f"Error parsing date from API for monthly gain: {api_category_raw}. Skipping this API stat.")
387
  continue
 
 
 
 
388
 
389
- key = (
390
- str(stat_from_api.get(FOLLOWER_STATS_ORG_URN_COLUMN)),
391
- api_type,
392
- api_category_identifier
393
- )
394
 
395
- # Assuming monthly gains also have organic/paid counts.
396
- # If they have different count fields, these need to be specified.
397
- # For simplicity, using FOLLOWER_STATS_ORGANIC_COLUMN and FOLLOWER_STATS_PAID_COLUMN.
398
- # If monthly gains only have a single 'count' field, adjust logic accordingly.
399
- api_organic_count = stat_from_api.get(FOLLOWER_STATS_ORGANIC_COLUMN, 0)
400
- api_paid_count = stat_from_api.get(FOLLOWER_STATS_PAID_COLUMN, 0)
401
-
402
- if key not in existing_stats_map:
403
- # This stat category/month is entirely new, add for bulk creation
404
  stats_for_bulk_upload.append(stat_from_api)
405
  else:
406
- # Stat category/month exists, check if counts need updating
407
- existing_organic, existing_paid, bubble_id = existing_stats_map[key]
 
408
  fields_to_update_in_bubble = {}
409
-
410
- if api_organic_count != existing_organic:
411
  fields_to_update_in_bubble[FOLLOWER_STATS_ORGANIC_COLUMN] = api_organic_count
 
412
 
413
- if api_paid_count != existing_paid:
414
  fields_to_update_in_bubble[FOLLOWER_STATS_PAID_COLUMN] = api_paid_count
 
415
 
416
- if fields_to_update_in_bubble: # If there's at least one field to update
417
  records_to_update_via_patch.append((bubble_id, fields_to_update_in_bubble))
 
 
 
418
 
419
- # --- Perform Bubble Operations ---
420
  num_bulk_uploaded = 0
421
  if stats_for_bulk_upload:
 
422
  if bulk_upload_to_bubble(stats_for_bulk_upload, BUBBLE_FOLLOWER_STATS_TABLE_NAME):
423
  num_bulk_uploaded = len(stats_for_bulk_upload)
424
  logging.info(f"Successfully bulk-uploaded {num_bulk_uploaded} new follower stat entries to Bubble for org {org_urn}.")
@@ -427,15 +448,18 @@ def sync_linkedin_follower_stats(token_state):
427
 
428
  num_patched_updated = 0
429
  if records_to_update_via_patch:
 
 
430
  for bubble_id, fields_to_update in records_to_update_via_patch:
431
  if update_record_in_bubble(BUBBLE_FOLLOWER_STATS_TABLE_NAME, bubble_id, fields_to_update):
432
  num_patched_updated += 1
 
433
  else:
434
  logging.error(f"Failed to update record {bubble_id} via PATCH for follower stats for org {org_urn}.")
435
  logging.info(f"Attempted to update {len(records_to_update_via_patch)} follower stat entries via PATCH, {num_patched_updated} succeeded for org {org_urn}.")
436
 
437
  if not stats_for_bulk_upload and not records_to_update_via_patch:
438
- logging.info(f"Follower Stats sync: Data for org {org_urn} is up-to-date or no changes met update criteria.")
439
  follower_stats_sync_message = "Follower Stats: Data up-to-date or no qualifying changes. "
440
  else:
441
  follower_stats_sync_message = f"Follower Stats: Synced (New: {num_bulk_uploaded}, Updated: {num_patched_updated}). "
@@ -443,85 +467,71 @@ def sync_linkedin_follower_stats(token_state):
443
  # --- Update token_state's follower stats DataFrame ---
444
  current_data_for_state_df = bubble_follower_stats_df_orig.copy()
445
 
446
- if records_to_update_via_patch and num_patched_updated > 0:
447
- # Create a temporary map of successful updates for quick lookup
448
- successful_updates_map = {
449
- bubble_id: fields for i, (bubble_id, fields) in enumerate(records_to_update_via_patch) if i < num_patched_updated
450
- }
451
- if successful_updates_map: # only proceed if there were successful updates to reflect
452
- for index, row in current_data_for_state_df.iterrows():
453
- bubble_id_from_df = row.get(BUBBLE_UNIQUE_ID_COLUMN_NAME)
454
- if bubble_id_from_df in successful_updates_map:
455
- fields_updated = successful_updates_map[bubble_id_from_df]
456
- for col, value in fields_updated.items():
457
- current_data_for_state_df.loc[index, col] = value
458
 
459
- if stats_for_bulk_upload and num_bulk_uploaded > 0:
460
- # Only consider successfully uploaded new records
461
- successfully_created_stats = [s for i, s in enumerate(stats_for_bulk_upload) if i < num_bulk_uploaded]
462
  if successfully_created_stats:
463
  newly_created_df = pd.DataFrame(successfully_created_stats)
464
  if not newly_created_df.empty:
465
  for col in current_data_for_state_df.columns:
466
  if col not in newly_created_df.columns:
467
- newly_created_df[col] = pd.NA # Use pd.NA for missing values
468
- # Align columns before concat to avoid issues with differing column orders or types
469
  aligned_newly_created_df = newly_created_df.reindex(columns=current_data_for_state_df.columns).fillna(pd.NA)
470
  current_data_for_state_df = pd.concat([current_data_for_state_df, aligned_newly_created_df], ignore_index=True)
471
 
472
  if not current_data_for_state_df.empty:
473
- # Deduplication logic (important after combining original, patched, and new data)
474
- # Ensure consistent primary key for deduplication across types
475
- # For monthly gains, primary key is (org_urn, type='follower_gains_monthly', category=date_str)
476
- # For demographics, primary key is (org_urn, type, category)
477
-
478
- # To handle this, we can sort by a hypothetical 'last_modified_indicator' if we had one,
479
- # or rely on 'keep=last' after ensuring data is ordered such that API data (potentially newer) comes later.
480
- # The concat order (original, then new) and then drop_duplicates with keep='last' on identifying keys is standard.
481
-
482
- # We need to define unique keys for each type to drop duplicates correctly.
483
- # The current deduplication splits by type and then applies different subsets. This should still work.
484
-
485
- monthly_part = current_data_for_state_df[current_data_for_state_df[FOLLOWER_STATS_TYPE_COLUMN] == 'follower_gains_monthly']
486
  if not monthly_part.empty:
487
- # Ensure category is consistently formatted for monthly gains before deduplication
488
- monthly_part_copy = monthly_part.copy() # To avoid SettingWithCopyWarning
489
- monthly_part_copy[FOLLOWER_STATS_CATEGORY_COLUMN] = pd.to_datetime(monthly_part_copy[FOLLOWER_STATS_CATEGORY_COLUMN], errors='coerce').dt.strftime('%Y-%m-%d')
490
- monthly_part = monthly_part_copy.drop_duplicates(
491
  subset=[FOLLOWER_STATS_ORG_URN_COLUMN, FOLLOWER_STATS_TYPE_COLUMN, FOLLOWER_STATS_CATEGORY_COLUMN],
492
  keep='last'
493
  )
494
 
495
- demographics_part = current_data_for_state_df[current_data_for_state_df[FOLLOWER_STATS_TYPE_COLUMN] != 'follower_gains_monthly']
496
  if not demographics_part.empty:
 
 
497
  demo_subset_cols = [FOLLOWER_STATS_ORG_URN_COLUMN, FOLLOWER_STATS_TYPE_COLUMN, FOLLOWER_STATS_CATEGORY_COLUMN]
498
  if all(col in demographics_part.columns for col in demo_subset_cols):
 
 
499
  demographics_part = demographics_part.drop_duplicates(
500
  subset=demo_subset_cols,
501
  keep='last'
502
  )
503
  else:
504
- logging.warning("Follower Stats: Missing columns for demographic deduplication in token_state update. Skipping.")
505
 
506
  if monthly_part.empty and demographics_part.empty:
507
  token_state["bubble_follower_stats_df"] = pd.DataFrame(columns=bubble_follower_stats_df_orig.columns)
508
- elif monthly_part.empty:
509
  token_state["bubble_follower_stats_df"] = demographics_part.reset_index(drop=True) if not demographics_part.empty else pd.DataFrame(columns=bubble_follower_stats_df_orig.columns)
510
- elif demographics_part.empty:
511
  token_state["bubble_follower_stats_df"] = monthly_part.reset_index(drop=True) if not monthly_part.empty else pd.DataFrame(columns=bubble_follower_stats_df_orig.columns)
512
- else:
513
  token_state["bubble_follower_stats_df"] = pd.concat([monthly_part, demographics_part], ignore_index=True)
514
- else:
515
  token_state["bubble_follower_stats_df"] = pd.DataFrame(columns=bubble_follower_stats_df_orig.columns)
516
 
 
517
  except ValueError as ve:
518
- logging.error(f"ValueError during follower stats sync for {org_urn}: {ve}", exc_info=True)
519
  follower_stats_sync_message = f"Follower Stats Error: {html.escape(str(ve))}. "
520
- except Exception as e:
521
- logging.exception(f"Unexpected error in sync_linkedin_follower_stats for {org_urn}.")
522
  follower_stats_sync_message = f"Follower Stats: Unexpected error ({type(e).__name__}). "
523
  finally:
524
- if not attempt_logged and org_urn:
525
  token_state = _log_sync_attempt(org_urn, LOG_SUBJECT_FOLLOWER_STATS, token_state)
526
 
527
  return follower_stats_sync_message, token_state
 
268
  return mentions_sync_message, token_state
269
 
270
 
271
+ def _clean_key_component(component_value, is_category_identifier=False):
272
+ """
273
+ Helper to consistently clean key components.
274
+ For non-date category identifiers, converts to lowercase for case-insensitive matching.
275
+ """
276
+ if pd.isna(component_value) or component_value is None:
277
+ return "NONE_VALUE" # Consistent placeholder for None/NaN
278
+
279
+ cleaned_value = str(component_value).strip()
280
+ if is_category_identifier: # Apply lowercasing only to general category text, not dates or URNs/Types
281
+ return cleaned_value.lower()
282
+ return cleaned_value
283
+
284
+
285
  def sync_linkedin_follower_stats(token_state):
286
  """
287
  Fetches new/updated LinkedIn follower statistics and uploads/updates them in Bubble,
288
+ if scheduled by state_manager. Includes detailed logging for debugging key mismatches.
 
 
289
  """
290
+ logging.info("DEBUG: Starting LinkedIn follower stats sync process check.")
291
 
292
  if not token_state.get("fs_should_sync_now", False):
293
+ logging.info("DEBUG: Follower Stats sync: Not scheduled by state_manager. Skipping.")
294
  return "Follower Stats: Sync not currently required by schedule. ", token_state
295
 
296
+ logging.info("DEBUG: Follower Stats sync: Proceeding as scheduled by state_manager.")
297
 
298
  if not token_state or not token_state.get("token"):
299
+ logging.error("DEBUG: Follower Stats sync: Access denied. No LinkedIn token.")
300
  org_urn_for_log = token_state.get('org_urn') if token_state else None
301
  if org_urn_for_log:
302
  token_state = _log_sync_attempt(org_urn_for_log, LOG_SUBJECT_FOLLOWER_STATS, token_state)
 
311
  attempt_logged = False
312
 
313
  if not org_urn or not client_id or client_id == "ENV VAR MISSING":
314
+ logging.error("DEBUG: Follower Stats sync: Configuration error (Org URN or Client ID missing).")
315
  if org_urn:
316
  token_state = _log_sync_attempt(org_urn, LOG_SUBJECT_FOLLOWER_STATS, token_state)
317
  attempt_logged = True
318
  return "Follower Stats: Config error. ", token_state
319
+
 
 
 
 
320
  if not bubble_follower_stats_df_orig.empty and BUBBLE_UNIQUE_ID_COLUMN_NAME not in bubble_follower_stats_df_orig.columns:
321
+ logging.error(f"DEBUG: Follower Stats sync: Critical error - '{BUBBLE_UNIQUE_ID_COLUMN_NAME}' column missing in bubble_follower_stats_df. Cannot proceed with updates.")
322
  if org_urn:
323
+ token_state = _log_sync_attempt(org_urn, LOG_SUBJECT_FOLLOWER_STATS, token_state)
324
  attempt_logged = True
325
  return f"Follower Stats: Config error ({BUBBLE_UNIQUE_ID_COLUMN_NAME} missing). ", token_state
326
 
327
+ logging.info(f"DEBUG: Follower stats sync proceeding for org_urn: {org_urn}")
328
  try:
329
  api_follower_stats = get_linkedin_follower_stats(client_id, token_dict, org_urn)
330
 
331
+ if not api_follower_stats: # This is a list of dicts
332
+ logging.info(f"DEBUG: Follower Stats sync: No stats found via API for org {org_urn}. API returned: {api_follower_stats}")
333
  follower_stats_sync_message = "Follower Stats: None found via API. "
334
  token_state = _log_sync_attempt(org_urn, LOG_SUBJECT_FOLLOWER_STATS, token_state)
335
  attempt_logged = True
336
  return follower_stats_sync_message, token_state
337
 
338
  stats_for_bulk_upload = []
339
+ records_to_update_via_patch = []
340
 
 
 
 
 
341
  existing_stats_map = {}
342
  stats_required_cols = [
343
  FOLLOWER_STATS_ORG_URN_COLUMN, FOLLOWER_STATS_TYPE_COLUMN,
344
+ FOLLOWER_STATS_CATEGORY_COLUMN, FOLLOWER_STATS_ORGANIC_COLUMN,
345
+ FOLLOWER_STATS_PAID_COLUMN, BUBBLE_UNIQUE_ID_COLUMN_NAME
 
346
  ]
347
 
348
+ logging.info("DEBUG: Populating existing_stats_map from Bubble data...")
349
  if not bubble_follower_stats_df_orig.empty and all(col in bubble_follower_stats_df_orig.columns for col in stats_required_cols):
350
+ for index, row in bubble_follower_stats_df_orig.iterrows():
351
+ org_urn_val = _clean_key_component(row[FOLLOWER_STATS_ORG_URN_COLUMN])
352
+ type_val = _clean_key_component(row[FOLLOWER_STATS_TYPE_COLUMN])
353
+ category_raw_val = row[FOLLOWER_STATS_CATEGORY_COLUMN]
354
+ bubble_id_val = row.get(BUBBLE_UNIQUE_ID_COLUMN_NAME)
355
+
356
+ if pd.isna(bubble_id_val):
357
+ logging.warning(f"DEBUG: Row index {index} from Bubble data has missing Bubble ID ('{BUBBLE_UNIQUE_ID_COLUMN_NAME}'). Cannot use for updates. Data: {row.to_dict()}")
358
+ continue
359
+
360
+ category_identifier = ""
361
+ if type_val == 'follower_gains_monthly': # Type is already cleaned
362
+ parsed_date = pd.to_datetime(category_raw_val, errors='coerce')
363
+ if pd.NaT is parsed_date or pd.isna(parsed_date):
364
+ logging.warning(f"DEBUG: Could not parse date for existing monthly gain: '{category_raw_val}' from Bubble row index {index}. Skipping for map.")
365
  continue
366
+ category_identifier = parsed_date.strftime('%Y-%m-%d') # Date format, not lowercased
367
+ else:
368
+ # Apply lowercasing for general text categories for case-insensitive matching
369
+ category_identifier = _clean_key_component(category_raw_val, is_category_identifier=True)
370
 
371
+ key = (org_urn_val, type_val, category_identifier)
372
+
373
+ # Ensure counts are numeric when storing in map
374
+ existing_organic_count = pd.to_numeric(row[FOLLOWER_STATS_ORGANIC_COLUMN], errors='coerce')
375
+ existing_paid_count = pd.to_numeric(row[FOLLOWER_STATS_PAID_COLUMN], errors='coerce')
376
+ existing_organic_count = 0 if pd.isna(existing_organic_count) else int(existing_organic_count)
377
+ existing_paid_count = 0 if pd.isna(existing_paid_count) else int(existing_paid_count)
378
+
379
  existing_stats_map[key] = (
380
+ existing_organic_count,
381
+ existing_paid_count,
382
+ str(bubble_id_val) # Ensure Bubble ID is string
383
  )
384
+ logging.debug(f"DEBUG: Added to existing_stats_map: Key={key}, BubbleID={str(bubble_id_val)}, OrgCounts={existing_organic_count}, PaidCounts={existing_paid_count}")
 
385
 
386
+ elif not bubble_follower_stats_df_orig.empty:
387
+ logging.warning(f"DEBUG: Follower Stats: Bubble data is missing one or more required columns for map: {stats_required_cols}.")
388
+ else:
389
+ logging.info("DEBUG: Follower Stats: Bubble_follower_stats_df_orig is empty. existing_stats_map will be empty.")
390
 
391
+ logging.info(f"DEBUG: Processing {len(api_follower_stats)} stats from API...")
392
+ for i, stat_from_api in enumerate(api_follower_stats): # api_follower_stats is a list of dicts
393
+ api_org_urn = _clean_key_component(stat_from_api.get(FOLLOWER_STATS_ORG_URN_COLUMN))
394
+ api_type = _clean_key_component(stat_from_api.get(FOLLOWER_STATS_TYPE_COLUMN))
395
  api_category_raw = stat_from_api.get(FOLLOWER_STATS_CATEGORY_COLUMN)
396
 
397
+ api_category_identifier = ""
398
+ if api_type == 'follower_gains_monthly': # API type is already cleaned
399
+ parsed_date = pd.to_datetime(api_category_raw, errors='coerce')
400
+ if pd.NaT is parsed_date or pd.isna(parsed_date):
401
+ logging.warning(f"DEBUG: API stat index {i}: Could not parse date for API monthly gain: '{api_category_raw}'. Skipping.")
 
 
 
 
402
  continue
403
+ api_category_identifier = parsed_date.strftime('%Y-%m-%d') # Date format, not lowercased
404
+ else:
405
+ # Apply lowercasing for general text categories for case-insensitive matching
406
+ api_category_identifier = _clean_key_component(api_category_raw, is_category_identifier=True)
407
 
408
+ key_from_api = (api_org_urn, api_type, api_category_identifier)
409
+ logging.debug(f"DEBUG: API stat index {i}: Generated Key={key_from_api}, RawData={stat_from_api}")
 
 
 
410
 
411
+ # Ensure API counts are numeric
412
+ api_organic_count = pd.to_numeric(stat_from_api.get(FOLLOWER_STATS_ORGANIC_COLUMN), errors='coerce')
413
+ api_paid_count = pd.to_numeric(stat_from_api.get(FOLLOWER_STATS_PAID_COLUMN), errors='coerce')
414
+ api_organic_count = 0 if pd.isna(api_organic_count) else int(api_organic_count)
415
+ api_paid_count = 0 if pd.isna(api_paid_count) else int(api_paid_count)
416
+
417
+
418
+ if key_from_api not in existing_stats_map:
419
+ logging.info(f"DEBUG: API stat index {i}: Key={key_from_api} NOT FOUND in existing_stats_map. Adding for BULK UPLOAD.")
420
  stats_for_bulk_upload.append(stat_from_api)
421
  else:
422
+ existing_organic, existing_paid, bubble_id = existing_stats_map[key_from_api] # Counts are already int from map
423
+ logging.info(f"DEBUG: API stat index {i}: Key={key_from_api} FOUND in existing_stats_map. BubbleID={bubble_id}. ExistingCounts(O/P): {existing_organic}/{existing_paid}. APICounts(O/P): {api_organic_count}/{api_paid_count}.")
424
+
425
  fields_to_update_in_bubble = {}
426
+ if api_organic_count > existing_organic:
 
427
  fields_to_update_in_bubble[FOLLOWER_STATS_ORGANIC_COLUMN] = api_organic_count
428
+ logging.debug(f"DEBUG: API stat index {i}: Organic count update: API({api_organic_count}) > Bubble({existing_organic}) for BubbleID {bubble_id}")
429
 
430
+ if api_paid_count > existing_paid:
431
  fields_to_update_in_bubble[FOLLOWER_STATS_PAID_COLUMN] = api_paid_count
432
+ logging.debug(f"DEBUG: API stat index {i}: Paid count update: API({api_paid_count}) > Bubble({existing_paid}) for BubbleID {bubble_id}")
433
 
434
+ if fields_to_update_in_bubble:
435
  records_to_update_via_patch.append((bubble_id, fields_to_update_in_bubble))
436
+ logging.info(f"DEBUG: API stat index {i}: Queued for PATCH update. BubbleID={bubble_id}, Updates={fields_to_update_in_bubble}")
437
+ else:
438
+ logging.info(f"DEBUG: API stat index {i}: Counts are not greater or equal. No update needed for BubbleID={bubble_id}.")
439
 
 
440
  num_bulk_uploaded = 0
441
  if stats_for_bulk_upload:
442
+ logging.info(f"DEBUG: Attempting to bulk upload {len(stats_for_bulk_upload)} new follower stat entries.")
443
  if bulk_upload_to_bubble(stats_for_bulk_upload, BUBBLE_FOLLOWER_STATS_TABLE_NAME):
444
  num_bulk_uploaded = len(stats_for_bulk_upload)
445
  logging.info(f"Successfully bulk-uploaded {num_bulk_uploaded} new follower stat entries to Bubble for org {org_urn}.")
 
448
 
449
  num_patched_updated = 0
450
  if records_to_update_via_patch:
451
+ logging.info(f"DEBUG: Attempting to PATCH update {len(records_to_update_via_patch)} follower stat entries.")
452
+ successfully_patched_ids_and_data_temp = [] # To store what was actually successful for token_state update
453
  for bubble_id, fields_to_update in records_to_update_via_patch:
454
  if update_record_in_bubble(BUBBLE_FOLLOWER_STATS_TABLE_NAME, bubble_id, fields_to_update):
455
  num_patched_updated += 1
456
+ successfully_patched_ids_and_data_temp.append({'bubble_id': bubble_id, 'fields': fields_to_update})
457
  else:
458
  logging.error(f"Failed to update record {bubble_id} via PATCH for follower stats for org {org_urn}.")
459
  logging.info(f"Attempted to update {len(records_to_update_via_patch)} follower stat entries via PATCH, {num_patched_updated} succeeded for org {org_urn}.")
460
 
461
  if not stats_for_bulk_upload and not records_to_update_via_patch:
462
+ logging.info(f"DEBUG: Follower Stats sync: Data for org {org_urn} is up-to-date or no changes met update criteria.")
463
  follower_stats_sync_message = "Follower Stats: Data up-to-date or no qualifying changes. "
464
  else:
465
  follower_stats_sync_message = f"Follower Stats: Synced (New: {num_bulk_uploaded}, Updated: {num_patched_updated}). "
 
467
  # --- Update token_state's follower stats DataFrame ---
468
  current_data_for_state_df = bubble_follower_stats_df_orig.copy()
469
 
470
+ if num_patched_updated > 0: # Check against actual successful patches
471
+ for item in successfully_patched_ids_and_data_temp: # Iterate over successfully patched items
472
+ bubble_id = item['bubble_id']
473
+ fields_updated = item['fields']
474
+ idx = current_data_for_state_df[current_data_for_state_df[BUBBLE_UNIQUE_ID_COLUMN_NAME] == bubble_id].index
475
+ if not idx.empty:
476
+ for col, value in fields_updated.items():
477
+ current_data_for_state_df.loc[idx, col] = value
 
 
 
 
478
 
479
+ if num_bulk_uploaded > 0: # Check against actual successful bulk uploads
480
+ successfully_created_stats = stats_for_bulk_upload[:num_bulk_uploaded] # Slice based on success count
 
481
  if successfully_created_stats:
482
  newly_created_df = pd.DataFrame(successfully_created_stats)
483
  if not newly_created_df.empty:
484
  for col in current_data_for_state_df.columns:
485
  if col not in newly_created_df.columns:
486
+ newly_created_df[col] = pd.NA
 
487
  aligned_newly_created_df = newly_created_df.reindex(columns=current_data_for_state_df.columns).fillna(pd.NA)
488
  current_data_for_state_df = pd.concat([current_data_for_state_df, aligned_newly_created_df], ignore_index=True)
489
 
490
  if not current_data_for_state_df.empty:
491
+ monthly_part = current_data_for_state_df[current_data_for_state_df[FOLLOWER_STATS_TYPE_COLUMN] == 'follower_gains_monthly'].copy()
 
 
 
 
 
 
 
 
 
 
 
 
492
  if not monthly_part.empty:
493
+ # Ensure FOLLOWER_STATS_CATEGORY_COLUMN is string before strftime, after to_datetime
494
+ monthly_part.loc[:, FOLLOWER_STATS_CATEGORY_COLUMN] = pd.to_datetime(monthly_part[FOLLOWER_STATS_CATEGORY_COLUMN], errors='coerce').dt.strftime('%Y-%m-%d')
495
+ monthly_part = monthly_part.drop_duplicates(
 
496
  subset=[FOLLOWER_STATS_ORG_URN_COLUMN, FOLLOWER_STATS_TYPE_COLUMN, FOLLOWER_STATS_CATEGORY_COLUMN],
497
  keep='last'
498
  )
499
 
500
+ demographics_part = current_data_for_state_df[current_data_for_state_df[FOLLOWER_STATS_TYPE_COLUMN] != 'follower_gains_monthly'].copy()
501
  if not demographics_part.empty:
502
+ # For demographics, category is already cleaned (and lowercased) if it was text
503
+ # Ensure all subset columns exist before drop_duplicates
504
  demo_subset_cols = [FOLLOWER_STATS_ORG_URN_COLUMN, FOLLOWER_STATS_TYPE_COLUMN, FOLLOWER_STATS_CATEGORY_COLUMN]
505
  if all(col in demographics_part.columns for col in demo_subset_cols):
506
+ # Clean the category column here again to match the key generation for demographics
507
+ demographics_part.loc[:, FOLLOWER_STATS_CATEGORY_COLUMN] = demographics_part[FOLLOWER_STATS_CATEGORY_COLUMN].apply(lambda x: _clean_key_component(x, is_category_identifier=True))
508
  demographics_part = demographics_part.drop_duplicates(
509
  subset=demo_subset_cols,
510
  keep='last'
511
  )
512
  else:
513
+ logging.warning(f"DEBUG: Demographics part missing one of {demo_subset_cols} for deduplication.")
514
 
515
  if monthly_part.empty and demographics_part.empty:
516
  token_state["bubble_follower_stats_df"] = pd.DataFrame(columns=bubble_follower_stats_df_orig.columns)
517
+ elif monthly_part.empty: # only demographics_part has data or is empty
518
  token_state["bubble_follower_stats_df"] = demographics_part.reset_index(drop=True) if not demographics_part.empty else pd.DataFrame(columns=bubble_follower_stats_df_orig.columns)
519
+ elif demographics_part.empty: # only monthly_part has data or is empty
520
  token_state["bubble_follower_stats_df"] = monthly_part.reset_index(drop=True) if not monthly_part.empty else pd.DataFrame(columns=bubble_follower_stats_df_orig.columns)
521
+ else: # both have data
522
  token_state["bubble_follower_stats_df"] = pd.concat([monthly_part, demographics_part], ignore_index=True)
523
+ else: # if current_data_for_state_df ended up empty
524
  token_state["bubble_follower_stats_df"] = pd.DataFrame(columns=bubble_follower_stats_df_orig.columns)
525
 
526
+
527
  except ValueError as ve:
528
+ logging.error(f"DEBUG: ValueError during follower stats sync for {org_urn}: {ve}", exc_info=True)
529
  follower_stats_sync_message = f"Follower Stats Error: {html.escape(str(ve))}. "
530
+ except Exception as e: # Catch any other unexpected error
531
+ logging.exception(f"DEBUG: Unexpected error in sync_linkedin_follower_stats for {org_urn}.") # .exception logs stack trace
532
  follower_stats_sync_message = f"Follower Stats: Unexpected error ({type(e).__name__}). "
533
  finally:
534
+ if not attempt_logged and org_urn: # Ensure log attempt happens if not already logged due to early exit
535
  token_state = _log_sync_attempt(org_urn, LOG_SUBJECT_FOLLOWER_STATS, token_state)
536
 
537
  return follower_stats_sync_message, token_state