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

# User Preferences

> Documentation for user preferences and settings management

The user preferences system allows users to manage their notification settings, integrations, and other personalized configurations within the platform.

## Database Schema

We will extend the existing `users` collection to include user preferences:

```typescript theme={null}
users/{userId} {
  // ... existing user fields ...

  preferences: {
    notifications: {
      bookings: {
        newRequests: boolean,      // Receive notifications for new booking requests
        bookingUpdates: boolean,   // Receive notifications for booking changes
        payments: boolean,         // Receive notifications for payment events
        conversations: boolean     // Receive notifications for new messages
      },
      marketing: boolean          // Receive marketing and product updates
    },
    preferredLanguage: string     // User's preferred language
  },

  // Third-party integrations (stored at root level alongside preferences)
  integrations: {
    instagram: {
      accessToken: string,        // SENSITIVE - never send to frontend
      userId: string,
      username: string,
      connectedAt: number,
      tokenExpiresAt: number
    },
    stripe: {
      accountId: string,          // Stripe account ID
      isEnabled: boolean,         // Whether Stripe integration is enabled
      isChargesEnabled: boolean,  // Whether charges are enabled
      isPayoutsEnabled: boolean   // Whether payouts are enabled
    }
    // Future integrations can be added here
  }
}
```

## Feature Implementation Plan

### Phase 1: Core Preferences Structure

1. Update Firestore schema
   * Add preferences object to user documents
   * Create migration for existing users
   * Add TypeScript types and interfaces

2. Backend Implementation
   * Create API endpoints for updating preferences
   * Implement preferences validation
   * Add preferences to user context

3. Frontend Implementation
   * Build settings UI components
   * Implement preferences form
   * Add real-time updates
   * Add loading and error states

### Phase 2: Notification Integration

1. Email Notification System
   * Integrate preferences with existing email notification system
   * Add preference checks before sending notifications
   * Update notification templates

2. In-App Notification System
   * Update notification filtering based on preferences
   * Add preference checks in notification creation
   * Implement real-time preference updates

### Phase 3: Integration Management

1. Stripe Integration
   * Add Stripe connection/disconnection flow
   * Implement account status tracking
   * Add payment capability management

## API Endpoints

### Get User Preferences

```typescript theme={null}
GET /api/users/{userId}/preferences

Response:
{
  notifications: {
    bookings: {
      newRequests: boolean,
      bookingUpdates: boolean,
      payments: boolean,
      conversations: boolean
    },
    marketing: boolean
  },
  preferredLanguage: string
}
```

### Update User Preferences

```typescript theme={null}
PATCH /api/users/{userId}/preferences

Request Body:
{
  path: string[],    // Path to the preference to update (e.g., ["notifications", "marketing"])
  value: any         // New value for the preference
}

Response:
{
  success: boolean,
  updatedPreferences: PreferencesObject
}
```

## Security Considerations

1. Access Control
   * Only authenticated users can access their own preferences
   * Admin users can access preferences for support purposes
   * Rate limiting on preference updates

2. Data Validation
   * Strict type checking for preference values
   * Validation of integration credentials
   * Sanitization of user input

## Testing Strategy

1. Unit Tests
   * Preference validation functions
   * API endpoint handlers
   * UI components

2. Integration Tests
   * Preference update flow
   * Notification system integration
   * Integration connection/disconnection

3. E2E Tests
   * Complete settings update workflow
   * Notification preference behavior
   * Integration management flow

## Future Considerations

1. Additional Preferences
   * Theme/appearance settings
   * Language preferences
   * Time zone settings
   * Communication preferences

2. Integration Expansions
   * Calendar integrations
   * Social media connections
   * Payment processor alternatives

3. Advanced Features
   * Preference templates
   * Bulk preference updates
   * Preference history/audit log

## Adding New Preferences

When adding new preferences to the system, follow these steps to ensure type safety and proper default values:

Here's a complete example of adding theme preferences:

1. Define Types:

   ```typescript theme={null}
   // types/models/preferences.ts

   export interface ThemePreferences {
     darkMode: boolean;
     accentColor: string;
     fontSize: "small" | "medium" | "large";
   }

   export interface UserPreferences {
     notifications: NotificationPreferences;
     preferredLanguage: LanguagePreference;
     theme: ThemePreferences;
   }
   ```

2. Add Defaults:

   ```typescript theme={null}
   export const DEFAULT_PREFERENCES: UserPreferences = {
     // ... existing defaults ...
     theme: {
       darkMode: false,
       accentColor: "#6366f1",
       fontSize: "medium",
     },
   };
   ```

3. Use in Components:

   ```typescript theme={null}
   function ThemeSettings() {
     const { preferences, updatePreference } = useUserPreferences();

     return (
       <div>
         <Switch
           checked={preferences.theme.darkMode}
           onCheckedChange={(checked) =>
             updatePreference(['theme', 'darkMode'], checked)
           }
         />
         <ColorPicker
           value={preferences.theme.accentColor}
           onChange={(color) =>
             updatePreference(['theme', 'accentColor'], color)
           }
         />
       </div>
     );
   }
   ```

### Best Practices

1. **Grouping**: Group related preferences together under a meaningful category (e.g., `notifications`, `theme`, etc.)

2. **Type Safety**: Always define proper TypeScript interfaces for new preference groups

3. **Default Values**: Provide sensible default values that will work for most users

4. **Validation**: Add any necessary validation rules for the new preferences

5. **Migration**: Consider if existing users need a data migration for the new preferences
   * The `mergeWithDefaultPreferences` function will automatically handle basic cases
   * For complex migrations, create a migration script
