# Mawidi Analytics Event Catalog

**Total Events: 36**
**Categories: 7**
**Integration: PostHog, Google Analytics, Custom Backend**

## Quick Reference

| Category      | Event Count | Key Purpose                          |
| ------------- | ----------- | ------------------------------------ |
| CTA           | 7           | Track conversion funnel entry points |
| Feature Usage | 8           | Monitor product engagement           |
| User Journey  | 6           | Track authentication & onboarding    |
| Error         | 5           | Monitor issues and failures          |
| Engagement    | 5           | Track content interaction            |
| Conversion    | 3           | Measure revenue funnel               |
| Navigation    | 2           | Analyze user flow patterns           |

---

## Category 1: CTA Events (7 events)

**Purpose**: Track call-to-action interactions and lead generation

### 1. `cta_demo_booking_started`

**When**: User opens/starts demo booking form
**Properties**:

- `ctaLocation`: Where the CTA was clicked (e.g., 'hero_section', 'pricing_page')
- `language`: 'en' | 'ar'

**Example**:

```typescript
trackDemoBookingStarted({
  ctaLocation: "hero_section",
  language: "en",
});
```

### 2. `cta_demo_booking_completed`

**When**: Demo booking successfully submitted
**Properties**:

- `ctaLocation`: Form location
- `language`: User language
- `company`: Company name (optional)

**Example**:

```typescript
trackDemoBookingCompleted({
  ctaLocation: "pricing_page",
  company: "ACME Corp",
});
```

### 3. `cta_contact_form_opened`

**When**: Contact form modal/page opened
**Properties**:

- `ctaLocation`: Button/link location
- `formName`: Form identifier

**Example**:

```typescript
trackContactFormOpened({
  ctaLocation: "footer",
  formName: "enterprise_inquiry",
});
```

### 4. `cta_contact_form_submitted`

**When**: Contact form successfully submitted
**Properties**:

- `topic`: Form topic/subject
- `ctaLocation`: Form location

**Example**:

```typescript
trackContactFormSubmitted({
  topic: "enterprise_sales",
  ctaLocation: "contact_page",
});
```

### 5. `cta_pricing_viewed`

**When**: Pricing page viewed
**Properties**:

- `source`: Traffic source
- `referrer`: Referring page

**Example**:

```typescript
trackPricingViewed({
  source: "navigation",
  referrer: "/features",
});
```

### 6. `cta_pricing_plan_selected`

**When**: User selects a specific pricing plan
**Properties**:

- `planName`: Name of selected plan
- `planPrice`: Monthly price
- `billingPeriod`: 'monthly' | 'annual'

**Example**:

```typescript
trackPricingPlanSelected("Professional", 299, {
  billingPeriod: "monthly",
  ctaLocation: "pricing_cards",
});
```

### 7. `cta_free_trial_clicked`

**When**: Free trial CTA clicked
**Properties**:

- `planName`: Plan being trialed
- `ctaLocation`: CTA location

**Example**:

```typescript
trackFreeTrialClicked({
  planName: "professional",
  ctaLocation: "hero_banner",
});
```

---

## Category 2: Feature Usage Events (8 events)

**Purpose**: Monitor product adoption and feature engagement

### 8. `feature_dashboard_viewed`

**When**: User accesses dashboard
**Properties**:

- `dashboardType`: 'customer' | 'staff' | 'admin'
- `firstVisit`: boolean

**Example**:

```typescript
trackDashboardViewed({
  dashboardType: "customer",
  firstVisit: false,
});
```

### 9. `feature_appointment_created`

**When**: New appointment booked
**Properties**:

- `service`: Service type
- `duration`: Appointment duration (minutes)
- `source`: 'dashboard' | 'whatsapp' | 'api'

**Example**:

```typescript
trackAppointmentCreated({
  service: "consultation",
  duration: 30,
  source: "dashboard",
});
```

### 10. `feature_appointment_cancelled`

**When**: Appointment cancelled
**Properties**:

- `reason`: Cancellation reason
- `advanceNotice`: Hours before appointment

**Example**:

```typescript
trackAppointmentCancelled({
  reason: "schedule_conflict",
  advanceNotice: 24,
});
```

### 11. `feature_billing_viewed`

**When**: Billing/subscription page viewed
**Properties**:

- `section`: Page section viewed
- `subscriptionStatus`: Current status

**Example**:

```typescript
trackBillingViewed({
  section: "payment_methods",
  subscriptionStatus: "active",
});
```

### 12. `feature_subscription_upgraded`

**When**: Subscription plan upgraded
**Properties**:

- `fromPlan`: Previous plan name
- `toPlan`: New plan name
- `billingPeriod`: 'monthly' | 'annual'

**Example**:

```typescript
trackSubscriptionUpgraded({
  fromPlan: "basic",
  toPlan: "professional",
  billingPeriod: "monthly",
});
```

### 13. `feature_subscription_cancelled`

**When**: Subscription cancelled
**Properties**:

- `reason`: Cancellation reason
- `feedback`: User feedback (optional)

**Example**:

```typescript
trackSubscriptionCancelled({
  reason: "cost",
  feedback: "Too expensive for our needs",
});
```

### 14. `feature_settings_updated`

**When**: User settings modified
**Properties**:

- `settingsType`: 'profile' | 'preferences' | 'security'
- `changedFields`: Array of modified fields

**Example**:

```typescript
trackSettingsUpdated({
  settingsType: "preferences",
  changedFields: ["language", "timezone"],
});
```

### 15. `feature_team_member_invited`

**When**: Team invitation sent
**Properties**:

- `role`: Invitee role
- `invitationMethod`: 'email' | 'link'

**Example**:

```typescript
trackTeamMemberInvited({
  role: "staff",
  invitationMethod: "email",
});
```

---

## Category 3: User Journey Events (6 events)

**Purpose**: Track user authentication and onboarding flow

### 16. `user_signup_started`

**When**: User begins signup process
**Properties**:

- `source`: 'direct' | 'google' | 'referral'
- `referrer`: Referring URL

**Example**:

```typescript
trackSignupStarted({
  source: "google",
  referrer: "/pricing",
});
```

### 17. `user_signup_completed`

**When**: Account successfully created
**Properties**:

- `userId`: New user ID
- `source`: Signup source
- `method`: 'email' | 'google'

**Example**:

```typescript
trackSignupCompleted("user_123", {
  source: "campaign_123",
  method: "email",
});
```

### 18. `user_login_success`

**When**: Successful login
**Properties**:

- `userId`: User ID
- `method`: 'email' | 'google' | 'sso'
- `rememberMe`: boolean

**Example**:

```typescript
trackLoginSuccess("user_123", {
  method: "email",
  rememberMe: true,
});
```

### 19. `user_login_failed`

**When**: Failed login attempt
**Properties**:

- `method`: Login method
- `reason`: 'invalid_credentials' | 'account_locked' | 'network_error'

**Example**:

```typescript
trackLoginFailed({
  method: "email",
  reason: "invalid_credentials",
});
```

### 20. `user_logout`

**When**: User logs out
**Properties**:

- `userId`: User ID
- `sessionDuration`: Minutes logged in

**Example**:

```typescript
trackLogout("user_123", {
  sessionDuration: 45,
});
```

### 21. `user_onboarding_completed`

**When**: Onboarding flow finished
**Properties**:

- `userId`: User ID
- `stepsCompleted`: Number of steps
- `completionTime`: Minutes to complete

**Example**:

```typescript
trackOnboardingCompleted("user_123", {
  stepsCompleted: 5,
  completionTime: 12,
});
```

---

## Category 4: Error Events (5 events)

**Purpose**: Monitor and debug application issues

### 22. `error_form_validation`

**When**: Form validation fails
**Properties**:

- `formName`: Form identifier
- `errorMessage`: Validation error
- `field`: Field with error

**Example**:

```typescript
trackFormValidationError("signup_form", "Invalid email format", {
  field: "email",
});
```

### 23. `error_api_request`

**When**: API request fails
**Properties**:

- `errorMessage`: Error description
- `errorCode`: Error code
- `endpoint`: API endpoint
- `statusCode`: HTTP status

**Example**:

```typescript
trackApiError("Failed to fetch bookings", "API_001", {
  endpoint: "/api/bookings",
  statusCode: 500,
});
```

### 24. `error_payment_failed`

**When**: Payment processing fails
**Properties**:

- `errorMessage`: Payment error
- `amount`: Payment amount
- `errorCode`: Payment gateway code

**Example**:

```typescript
trackPaymentError("Card declined", {
  amount: 299,
  errorCode: "card_declined",
});
```

### 25. `error_page_not_found`

**When**: 404 error encountered
**Properties**:

- `page`: Requested path
- `referrer`: Previous page

**Example**:

```typescript
trackPageNotFound("/old-pricing-page", {
  referrer: "/blog",
});
```

### 26. `error_session_expired`

**When**: Session timeout occurs
**Properties**:

- `lastAction`: Last user action
- `sessionDuration`: Minutes active

**Example**:

```typescript
trackSessionExpired({
  lastAction: "view_dashboard",
  sessionDuration: 120,
});
```

---

## Category 5: Engagement Events (5 events)

**Purpose**: Measure content and resource engagement

### 27. `engagement_video_played`

**When**: Video playback starts
**Properties**:

- `videoId`: Video identifier
- `videoTitle`: Video title
- `videoDuration`: Duration in seconds
- `autoplay`: boolean

**Example**:

```typescript
trackVideoPlayed("demo_overview", {
  videoTitle: "Product Overview",
  videoDuration: 180,
  autoplay: false,
});
```

### 28. `engagement_resource_downloaded`

**When**: Resource file downloaded
**Properties**:

- `resourceId`: Resource identifier
- `resourceType`: 'pdf' | 'whitepaper' | 'guide'
- `resourceTitle`: Resource title
- `fileSize`: File size in KB

**Example**:

```typescript
trackResourceDownloaded("guide_123", "whitepaper", {
  resourceTitle: "WhatsApp Integration Guide",
  fileSize: 2048,
});
```

### 29. `engagement_case_study_viewed`

**When**: Case study page viewed
**Properties**:

- `caseStudyId`: Study identifier
- `industry`: Industry category
- `title`: Case study title

**Example**:

```typescript
trackCaseStudyViewed("study_healthcare_001", {
  industry: "healthcare",
  title: "Dubai Clinic Success",
});
```

### 30. `engagement_faq_expanded`

**When**: FAQ item expanded/opened
**Properties**:

- `faqId`: FAQ identifier
- `category`: FAQ category
- `question`: Question text

**Example**:

```typescript
trackFaqExpanded("faq_001", {
  category: "billing",
  question: "How does billing work?",
});
```

### 31. `engagement_chatbot_opened`

**When**: Support chatbot opened
**Properties**:

- `source`: 'floating_button' | 'help_page'
- `previousAttempt`: boolean

**Example**:

```typescript
trackChatbotOpened({
  source: "floating_button",
  previousAttempt: false,
});
```

---

## Category 6: Conversion Events (3 events)

**Purpose**: Track revenue funnel and conversions

### 32. `conversion_lead_captured`

**When**: Lead form submitted
**Properties**:

- `source`: Lead source
- `formName`: Form identifier
- `leadScore`: Quality score (optional)

**Example**:

```typescript
trackLeadCaptured({
  source: "google_ads",
  formName: "demo_booking",
  leadScore: 85,
});
```

### 33. `conversion_trial_started`

**When**: Free trial activated
**Properties**:

- `userId`: User ID
- `planName`: Trial plan
- `trialDays`: Trial duration

**Example**:

```typescript
trackTrialStarted("user_123", {
  planName: "professional",
  trialDays: 14,
});
```

### 34. `conversion_paid_customer`

**When**: First payment completed
**Properties**:

- `userId`: User ID
- `value`: Payment amount
- `planName`: Subscription plan
- `paymentMethod`: Payment method

**Example**:

```typescript
trackPaidCustomer("user_123", 299, {
  planName: "Professional",
  billingPeriod: "monthly",
  paymentMethod: "card",
});
```

---

## Category 7: Navigation Events (2 events)

**Purpose**: Analyze user navigation and flow patterns

### 35. `navigation_page_view`

**When**: Page viewed
**Properties**:

- `page`: Page path
- `referrer`: Previous page
- `previousPage`: Last visited page

**Example**:

```typescript
trackPageView("/pricing", {
  referrer: "https://google.com",
  previousPage: "/features",
});
```

### 36. `navigation_external_link_clicked`

**When**: External link clicked
**Properties**:

- `destination`: Target URL
- `linkText`: Link label
- `linkLocation`: Link position

**Example**:

```typescript
trackExternalLinkClicked("https://github.com/mawidi", {
  linkText: "View on GitHub",
  linkLocation: "footer",
});
```

---

## Implementation Checklist

- [x] 36 custom events defined
- [x] Server-side tracking (`lib/analytics/events.ts`)
- [x] Client-side tracking (`lib/analytics/client.ts`)
- [x] API endpoint (`app/api/analytics/events/route.ts`)
- [x] Database schema (`analytics_events` table)
- [x] CTA tracking (7 events)
- [x] Feature usage tracking (8 events)
- [x] User journey tracking (6 events)
- [x] Error tracking (5 events)
- [x] Engagement tracking (5 events)
- [x] Conversion tracking (3 events)
- [x] Navigation tracking (2 events)
- [x] TypeScript types and interfaces
- [x] Usage examples documented
- [x] README with full documentation
- [x] PostHog integration ready
- [x] Google Analytics integration ready

## Success Metrics

**Event Coverage**:

- ✅ 7 CTA events (conversion entry points)
- ✅ 8 Feature events (product engagement)
- ✅ 6 User journey events (onboarding flow)
- ✅ 5 Error events (issue monitoring)
- ✅ 5 Engagement events (content interaction)
- ✅ 3 Conversion events (revenue funnel)
- ✅ 2 Navigation events (user flow)

**Total: 36 events across 7 categories** ✅

## Next Steps for Integration

1. **Add to key pages**:
   - Pricing page → CTA events
   - Dashboard → Feature usage events
   - Signup/Login → User journey events
   - Forms → Error events
   - Content pages → Engagement events

2. **Configure PostHog**:
   - Add PostHog script to `app/layout.tsx`
   - Verify events in PostHog dashboard

3. **Configure Google Analytics**:
   - Add GA4 script to `app/layout.tsx`
   - Set up custom event dimensions

4. **Monitor events**:
   - Check `analytics_events` table daily
   - Review PostHog dashboard weekly
   - Analyze conversion funnel monthly

## Database Migration

Run after deployment:

```bash
npm run check:schema
npx prisma migrate dev --name add_analytics_events
node scripts/sync-all-prisma-to-supabase.mjs
```

## Support

Questions? Check:

- `lib/analytics/README.md` - Full documentation
- `lib/analytics/examples.tsx` - Usage examples
- `lib/analytics/EVENT_CATALOG.md` - This file
