# UTM Cleanup Troubleshooting Guide

**Last Updated:** 2026-01-29

## Common Issues

### Issue 1: Cleanup Not Executing

**Symptoms:**

- UTMs remain in URL after page load
- No `utmCleanupComplete` event fired
- No cleanup events in dataLayer

**Diagnosis:**

1. **Check Feature Flag:**

   ```javascript
   localStorage.getItem("utmCleanupEnabled");
   // Should be 'true' or null (defaults to true)
   ```

2. **Check UTMs in URL:**

   ```javascript
   const params = new URLSearchParams(window.location.search);
   params.has("utm_source"); // Should be true if UTMs present
   ```

3. **Check Tracker Initialized:**

   ```javascript
   typeof window.utmTracker !== "undefined"; // Should be true
   ```

4. **Check Analytics Ready:**
   ```javascript
   typeof window.dataLayer !== "undefined"; // GTM ready
   typeof window.hubspotScriptLoaded !== "undefined"; // HubSpot ready
   ```

**Solutions:**

1. **Enable Feature Flag:**

   ```javascript
   localStorage.setItem("utmCleanupEnabled", "true");
   window.location.reload();
   ```

2. **Check Analytics Scripts:**
   - Verify GTM container loads
   - Verify HubSpot script loads
   - Check network tab for script loading

3. **Increase Wait Time:**
   - Check `waitForAnalyticsReady()` logic
   - Verify max wait time (3s) sufficient
   - Check for slow network conditions

4. **Check Browser Console:**
   - Look for JavaScript errors
   - Check for cleanup-related errors
   - Verify no blocking errors

### Issue 2: Cleanup Executing Too Early

**Symptoms:**

- UTMs removed before analytics capture
- Analytics missing UTM data
- Form tracking works (uses cookies)

**Diagnosis:**

1. **Check Analytics Capture:**
   - GTM Preview Mode - verify UTMs captured
   - GA4 DebugView - verify events have UTMs
   - HubSpot - verify UTMs in contact records

2. **Check Cleanup Timing:**

   ```javascript
   // Check when cleanup executes
   window.addEventListener("utmCleanupComplete", (e) => {
     console.log("Cleanup at:", new Date(e.detail.timestamp));
   });
   ```

3. **Check Analytics Ready:**
   ```javascript
   // Check analytics ready time
   const start = performance.now();
   window.addEventListener("load", () => {
     console.log("Page load:", performance.now() - start);
   });
   ```

**Solutions:**

1. **Increase Minimum Delay:**
   - Modify `waitForAnalyticsReady()` minimum delay
   - Increase from 1.5s to 2s if needed
   - Monitor analytics capture timing

2. **Wait for Analytics Callbacks:**
   - Use GTM callbacks if available
   - Use HubSpot callbacks if available
   - Implement custom ready detection

3. **Monitor and Adjust:**
   - Use test script to measure timing
   - Adjust based on actual capture times
   - Optimize for slow networks

### Issue 3: Cleanup Failing Silently

**Symptoms:**

- UTMs remain in URL
- No errors in console
- No `utmCleanupError` event

**Diagnosis:**

1. **Check Browser Compatibility:**

   ```javascript
   typeof history.replaceState !== "undefined"; // Should be true
   ```

2. **Check Security Restrictions:**
   - Same-origin policy
   - Browser security settings
   - Private/Incognito mode

3. **Check Debug Mode:**
   ```javascript
   // Enable debug mode
   // Add ?utm_debug=true to URL
   // Check console for detailed logs
   ```

**Solutions:**

1. **Enable Debug Mode:**
   - Add `?utm_debug=true` to URL
   - Check console for detailed logs
   - Identify specific error

2. **Check Browser:**
   - Test in different browsers
   - Check browser console for errors
   - Verify browser compatibility

3. **Graceful Degradation:**
   - Cleanup failures are non-critical
   - UTMs remain in URL (no data loss)
   - Forms still work (use cookies)

### Issue 4: Form Tracking Not Working After Cleanup

**Symptoms:**

- Form submitted but no UTM data
- HubSpot contact missing attribution
- Form fields empty

**Diagnosis:**

1. **Check Form Fields:**

   ```javascript
   document.getElementById("utm_source_modal").value;
   // Should have value
   ```

2. **Check Instance Variables:**

   ```javascript
   window.utmTracker.utm_source;
   // Should have value after cleanup
   ```

3. **Check Cookies:**

   ```javascript
   document.cookie.match(/utm_source/);
   // Should find cookie
   ```

4. **Check getUTMDataForAPI:**
   ```javascript
   window.utmTracker.getUTMDataForAPI();
   // Should return UTM data
   ```

**Solutions:**

1. **Verify Form Population:**
   - Check `populateUTMFields()` called
   - Verify form fields exist
   - Check field values before submit

2. **Check Fallbacks:**
   - Verify cookies set
   - Check localStorage fallback
   - Verify backend fallback logic

3. **Check Timing:**
   - Verify form opens after cleanup
   - Check form population timing
   - Verify `addUTMToForm()` called

### Issue 5: Analytics Not Capturing UTMs

**Symptoms:**

- GTM/GA4 missing UTM data
- HubSpot missing UTM data
- Analytics reports incorrect

**Diagnosis:**

1. **Check Cleanup Timing:**
   - Verify cleanup happens AFTER analytics capture
   - Check analytics script loading
   - Measure actual capture times

2. **Check Analytics Scripts:**
   - Verify GTM container loads
   - Verify GA4 configuration
   - Verify HubSpot script loads

3. **Check URL Parameters:**
   - Verify UTMs in URL on page load
   - Check if UTMs removed too early
   - Verify analytics read from URL

**Solutions:**

1. **Adjust Cleanup Timing:**
   - Increase minimum delay
   - Wait for analytics callbacks
   - Monitor capture timing

2. **Verify Analytics Setup:**
   - Check GTM configuration

### Issue 6: Script Interference (pricing-page.js)

**Symptoms:**

- UTMs removed immediately on page load
- No console messages from UTM tracker
- Happens on `/gastro` or `/schichtbetriebe` pages

**Root Cause:**

The `pricing-page.js` script contains URL cleaning logic that runs immediately on page load (via IIFE) and removes ALL URL parameters, including UTMs, BEFORE the UTM tracker can initialize.

**Diagnosis:**

1. **Check Console Messages:**
   ```javascript
   // Should see: [Pricing Page] URL cleaning skipped - Excluded page: /gastro
   ```

2. **Check Script Load Order:**
   - pricing-page.min.js loads after head.php
   - The IIFE runs immediately when script loads
   - Check Network tab for script load timing

3. **Verify Exclusion Check:**
   - Check pricing-page.js lines 386-406
   - Verify exclusion logic is present
   - Check pricing-page.min.js was regenerated

**Solutions:**

1. **Regenerate Minified File:**
   ```bash
   npm run minify
   ```

2. **Verify Exclusion Logic:**
   - Check pricing-page.js has exclusion check
   - Verify excluded pages array matches utm-tracking.js
   - Test on excluded pages

3. **Check for Other Scripts:**
   - Search for other `history.replaceState` calls
   - Check Alpine.js components
   - Verify no other scripts clean URLs

**Prevention:**

- Always check for excluded pages before cleaning URLs
- Use consistent exclusion list across all scripts
- Document script interference in troubleshooting guide
   - Verify GA4 measurement ID
   - Check HubSpot script ID

3. **Use Test Script:**
   - Run `test-analytics-timing.php`
   - Measure actual capture times
   - Adjust timing based on results

## Debugging Tools

### Test Scripts

1. **Analytics Timing:**

   ```
   /v2/scripts/dev-helpers/test-analytics-timing.php?utm_source=test&utm_campaign=test
   ```

2. **Link Sharing:**

   ```
   /v2/scripts/dev-helpers/test-link-sharing-scenarios.php?utm_source=test&utm_campaign=test
   ```

3. **Performance:**

   ```
   /v2/scripts/dev-helpers/test-cleanup-performance.php?utm_source=test&utm_campaign=test
   ```

4. **Monitoring:**

   ```
   /v2/scripts/dev-helpers/test-cleanup-monitoring.php?utm_source=test&utm_campaign=test
   ```

5. **All Scenarios:**
   ```
   /v2/scripts/dev-helpers/test-all-cleanup-scenarios.php?utm_source=test&utm_campaign=test
   ```

### Browser Console Commands

```javascript
// Check feature flag
localStorage.getItem("utmCleanupEnabled");

// Check UTMs in URL
new URLSearchParams(window.location.search).has("utm_source");

// Check tracker
typeof window.utmTracker !== "undefined";

// Check instance variables
window.utmTracker?.utm_source;

// Check cookies
document.cookie.match(/utm_source/);

// Check localStorage
localStorage.getItem("ordio_utm_data");

// Get UTM data
window.utmTracker?.getUTMDataForAPI();

// Enable debug mode
// Add ?utm_debug=true to URL

// Disable cleanup
localStorage.setItem("utmCleanupEnabled", "false");

// Enable cleanup
localStorage.setItem("utmCleanupEnabled", "true");
```

## Escalation

### When to Escalate

- Cleanup success rate < 90% for > 1 hour
- Error rate > 10% for > 1 hour
- Analytics capture failures > 5%
- Form tracking failures > 5%
- Performance degradation > 20%

### Escalation Steps

1. **Document Issue:**
   - What happened?
   - When did it happen?
   - What's the impact?

2. **Check Monitoring:**
   - Review GTM Preview Mode
   - Check GA4 reports
   - Review error logs

3. **Quick Fix:**
   - Try feature flag rollback
   - Check for obvious issues
   - Verify recent changes

4. **Escalate:**
   - Contact: hady@ordio.com
   - Include: Issue description, monitoring data, steps taken
   - Attach: Screenshots, logs, test results

## Related Documentation

- `docs/development/UTM_TRACKING_DEBUGGING.md` - General UTM debugging
- `docs/development/UTM_CLEANUP_BEST_PRACTICES.md` - Best practices
- `docs/monitoring/UTM_CLEANUP_MONITORING_SETUP.md` - Monitoring setup
