> ## Documentation Index
> Fetch the complete documentation index at: https://docs.encoreos.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Form Analytics Guide

> Form Analytics provides actionable insights into form usage, completion patterns, and user engagement to help optimize forms and improve completion rates.

## Overview

Form Analytics provides actionable insights into form usage, completion patterns, and user engagement to help optimize forms and improve completion rates.

## Features

### Analytics Tracking

* **Form Events:** Track form starts, completions, and abandonments
* **Field Interactions:** Monitor focus, changes, and validation errors per field
* **Device Tracking:** Separate analytics for mobile, tablet, and desktop
* **Session Tracking:** Group events by user session for funnel analysis

### Metrics

* **Completion Rate:** Percentage of started forms that are completed
* **Time to Complete:** Median and P95 completion times
* **Drop-off Analysis:** Identify where users abandon forms
* **Field Performance:** See which fields cause errors or confusion

## Enabling Analytics

Analytics are enabled by default for all new forms. To disable:

1. Open Form Builder
2. Go to Settings tab
3. Toggle "Analytics Enabled" off

## Viewing Analytics

### Form Analytics Dashboard

Navigate to `/fw/analytics` to view:

* **Overview:** Summary cards with key metrics
* **Completion Funnel:** Visualize where users drop off
* **Field Performance:** Table showing field-level statistics
* **Trends:** Chart showing submission volume over time

### Per-Form Analytics

From the Form Builder, click "View Analytics" to see metrics for a specific form.

## Privacy & Security

* **No Field Values Logged:** Only field keys and interaction types are tracked
* **No PII:** Personal information is never logged
* **Aggregate Reporting:** Individual user tracking is not supported
* **Opt-Out:** Forms can disable analytics entirely
* **Data Retention:** Raw events are retained for 90 days, aggregates indefinitely

## Optimization Tips

### Improving Completion Rates

1. **Identify Drop-off Points:** Look for fields with high abandonment rates
2. **Simplify Complex Fields:** If a field has many errors, consider breaking it into simpler components
3. **Reduce Form Length:** Forms with fewer fields generally have higher completion rates
4. **Optimize Mobile Experience:** Check mobile completion rate vs desktop

### Reducing Time to Complete

1. **Remove Unnecessary Fields:** Every field adds cognitive load
2. **Use Defaults:** Pre-fill fields when possible
3. **Add Helper Text:** Clear instructions reduce errors and speed completion
4. **Use Appropriate Input Types:** Date pickers are faster than text inputs for dates

### Reducing Errors

1. **Clear Validation Messages:** Tell users exactly what's wrong
2. **Inline Validation:** Validate as users type, not just on submit
3. **Format Examples:** Show expected format (e.g., "MM/DD/YYYY")

## API Reference

### `useFormAnalytics` Hook

```typescript theme={null}
import { useFormAnalytics } from '@/platform/forms/hooks/useFormAnalytics';

const analytics = useFormAnalytics(formId, {
  enabled: true,
  batchSize: 10,
  batchInterval: 5000,
});

// Track events
analytics.trackFormStart();
analytics.trackFieldFocus('email');
analytics.trackFieldChange('email', { length: 15 });
analytics.trackValidationError('email', 'Invalid format');
analytics.trackFormComplete(submissionId);
```

### Analytics Functions

#### `log_form_analytics_event()`

Logs a single analytics event.

```sql theme={null}
SELECT log_form_analytics_event(
  _form_id := '...',
  _event_type := 'form_started',
  _session_id := '...',
  _field_key := NULL,
  _submission_id := NULL,
  _event_data := '{}',
  _device_type := 'desktop'
);
```

#### `aggregate_completion_metrics()`

Aggregates raw events into daily completion metrics.

```sql theme={null}
SELECT aggregate_completion_metrics('2025-01-27');
```

#### `aggregate_field_stats()`

Aggregates field-level statistics.

```sql theme={null}
SELECT aggregate_field_stats('2025-01-27');
```

## Database Schema

### `pf_form_analytics_events`

Raw analytics events (pruned after 90 days).

| Column           | Type        | Description                                      |
| ---------------- | ----------- | ------------------------------------------------ |
| id               | UUID        | Event ID                                         |
| form\_id         | UUID        | Form being tracked                               |
| session\_id      | UUID        | User session                                     |
| event\_type      | TEXT        | Event type (form\_started, field\_focused, etc.) |
| field\_key       | TEXT        | Field identifier (for field events)              |
| event\_timestamp | TIMESTAMPTZ | When event occurred                              |
| device\_type     | TEXT        | mobile/tablet/desktop                            |

### `pf_form_completion_metrics`

Daily aggregated completion metrics (retained indefinitely).

| Column                              | Type  | Description            |
| ----------------------------------- | ----- | ---------------------- |
| form\_id                            | UUID  | Form                   |
| metric\_date                        | DATE  | Aggregation date       |
| started\_count                      | INT   | Forms started          |
| completed\_count                    | INT   | Forms completed        |
| completion\_rate                    | FLOAT | Completion percentage  |
| median\_time\_to\_complete\_seconds | INT   | Median completion time |

### `pf_field_interaction_stats`

Daily aggregated field statistics (retained indefinitely).

| Column        | Type | Description       |
| ------------- | ---- | ----------------- |
| form\_id      | UUID | Form              |
| field\_key    | TEXT | Field identifier  |
| metric\_date  | DATE | Aggregation date  |
| focus\_count  | INT  | Times focused     |
| change\_count | INT  | Times changed     |
| error\_count  | INT  | Validation errors |

## Troubleshooting

### Events Not Appearing

1. **Check Analytics Enabled:** Ensure the form has `analytics_enabled = true`
2. **Verify RLS Policies:** User must have access to the form's organization
3. **Check Console:** Look for errors in browser console
4. **Aggregation Delay:** Raw events are aggregated every 5 minutes

### Metrics Don't Match Submissions

* Metrics are based on sessions, not individual submissions
* A user can start a form multiple times in different sessions
* Completed count may be less than submission count if analytics was disabled

### Performance Issues

* Analytics use batching (5 second intervals) to minimize impact
* Raw events are automatically pruned after 90 days
* Aggregated metrics use indexed queries for fast access

## Best Practices

1. **Review Analytics Weekly:** Check for trends and issues
2. **A/B Test Changes:** Compare metrics before and after form updates
3. **Focus on High-Volume Forms:** Optimize forms with the most submissions first
4. **Monitor Abandonment:** Set up alerts for sudden drops in completion rate
5. **Respect Privacy:** Never log field values or personally identifiable information
