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

# Content Services

> Content creation, management, and social media synchronization services

# Content Services

The Content Services provide comprehensive content management capabilities including social media content creation, synchronization, analytics, and bio link management for the VChata platform.

## Overview

The Content Services layer includes:

* 📝 **Content Service** - Core content creation and management
* 🔄 **Content Sync Service** - Social media synchronization and live data fetching
* 🔗 **Bio Link Service** - Bio link creation and management
* 📊 **Content Analytics** - Performance tracking and insights
* 🎯 **Content Attribution** - Track content performance and lead generation

## Content Service

### Core Content Management

The Content Service handles all content-related operations including creation, updates, and retrieval.

#### Create Content Post

```typescript theme={null}
// Create a new content post
const contentPost = await contentService.createContentPost(
  organizationId,
  {
    socialAccountId: "social_123",
    platform: "FACEBOOK",
    content: "Check out our new product!",
    scheduledAt: "2024-01-20T10:00:00Z",
    tags: ["product", "launch"],
    keyword: "new-product-2024",
    utmSource: "social_media",
    utmMedium: "post",
    utmCampaign: "product_launch"
  }
);
```

#### Get Content Posts

```typescript theme={null}
// Get content posts with filtering
const posts = await contentService.getContentPosts(
  organizationId,
  {
    socialAccountId: "social_123",
    platform: "FACEBOOK",
    tags: ["product"],
    dateFrom: "2024-01-01",
    dateTo: "2024-01-31",
    includeLiveData: true
  }
);
```

#### Update Content Post

```typescript theme={null}
// Update content post
const updatedPost = await contentService.updateContentPost(
  postId,
  {
    content: "Updated content with new information",
    tags: ["product", "updated"],
    scheduledAt: "2024-01-21T10:00:00Z"
  }
);
```

### Content Operations

<Expandable title="createContentPost(organizationId, postData)">
  **Description**: Creates a new content post for social media.

  **Parameters**:

  * `organizationId`: Organization ID
  * `postData`: Post configuration and content

  **Returns**: `Promise<ContentPost>` - Created content post
</Expandable>

<Expandable title="getContentPosts(organizationId, filters)">
  **Description**: Retrieves content posts with optional filtering.

  **Parameters**:

  * `organizationId`: Organization ID
  * `filters`: Filtering options (platform, tags, date range, etc.)

  **Returns**: `Promise<ContentPost[]>` - List of content posts
</Expandable>

<Expandable title="updateContentPost(postId, updates)">
  **Description**: Updates an existing content post.

  **Parameters**:

  * `postId`: Content post ID
  * `updates`: Update data

  **Returns**: `Promise<ContentPost>` - Updated content post
</Expandable>

<Expandable title="deleteContentPost(postId)">
  **Description**: Deletes a content post.

  **Parameters**:

  * `postId`: Content post ID

  **Returns**: `Promise<void>`
</Expandable>

<Expandable title="getContentAnalytics(organizationId, dateRange)">
  **Description**: Retrieves content performance analytics.

  **Parameters**:

  * `organizationId`: Organization ID
  * `dateRange`: Date range for analytics

  **Returns**: `Promise<ContentAnalytics>` - Analytics data
</Expandable>

## Content Sync Service

### Social Media Synchronization

The Content Sync Service handles synchronization with social media platforms and live data fetching.

#### Sync Content

```typescript theme={null}
// Sync content from social media platform
const syncResult = await contentSyncService.syncContent(
  organizationId,
  {
    socialAccountId: "social_123",
    platform: "FACEBOOK",
    syncType: "posts",
    dateRange: {
      start: "2024-01-01",
      end: "2024-01-31"
    }
  }
);
```

#### Fetch Live Data

```typescript theme={null}
// Fetch live data for existing posts
const liveData = await contentSyncService.fetchLiveData(
  organizationId,
  {
    postIds: ["post_123", "post_456"],
    includeMetrics: true,
    includeComments: true,
    includeReactions: true
  }
);
```

#### Auto-Sync New Posts

```typescript theme={null}
// Automatically sync new posts from platform
const newPosts = await contentSyncService.autoSyncNewPosts(
  organizationId,
  {
    socialAccountId: "social_123",
    platform: "FACEBOOK",
    batchSize: 20,
    createTrackingRecords: true
  }
);
```

### Sync Operations

<Expandable title="syncContent(organizationId, syncOptions)">
  **Description**: Synchronizes content from social media platforms.

  **Parameters**:

  * `organizationId`: Organization ID
  * `syncOptions`: Synchronization configuration

  **Returns**: `Promise<SyncResult>` - Synchronization results
</Expandable>

<Expandable title="fetchLiveData(organizationId, options)">
  **Description**: Fetches live data for existing content posts.

  **Parameters**:

  * `organizationId`: Organization ID
  * `options`: Live data fetching options

  **Returns**: `Promise<LiveDataResult>` - Live data results
</Expandable>

<Expandable title="autoSyncNewPosts(organizationId, options)">
  **Description**: Automatically syncs new posts from platforms.

  **Parameters**:

  * `organizationId`: Organization ID
  * `options`: Auto-sync configuration

  **Returns**: `Promise<ContentPost[]>` - Newly synced posts
</Expandable>

<Expandable title="mergeLiveData(posts, liveData)">
  **Description**: Merges live data with existing post data.

  **Parameters**:

  * `posts`: Existing content posts
  * `liveData`: Live data from platforms

  **Returns**: `Promise<ContentPost[]>` - Merged posts with live data
</Expandable>

## Bio Link Service

### Bio Link Management

The Bio Link Service handles creation and management of bio links for social media profiles.

#### Create Bio Link

```typescript theme={null}
// Create a new bio link
const bioLink = await bioLinkService.createBioLink(
  organizationId,
  {
    title: "Summer Sale 2024",
    description: "Check out our amazing summer deals!",
    url: "https://acme.com/summer-sale",
    imageUrl: "https://acme.com/images/summer-banner.jpg",
    buttonText: "Shop Now",
    utmSource: "bio_link",
    utmMedium: "social",
    utmCampaign: "summer_2024",
    isActive: true
  }
);
```

#### Get Bio Links

```typescript theme={null}
// Get bio links for organization
const bioLinks = await bioLinkService.getBioLinks(
  organizationId,
  {
    isActive: true,
    sortBy: "createdAt",
    sortOrder: "desc"
  }
);
```

#### Update Bio Link

```typescript theme={null}
// Update bio link
const updatedBioLink = await bioLinkService.updateBioLink(
  bioLinkId,
  {
    title: "Updated Summer Sale 2024",
    description: "New and improved summer deals!",
    url: "https://acme.com/summer-sale-v2"
  }
);
```

### Bio Link Operations

<Expandable title="createBioLink(organizationId, linkData)">
  **Description**: Creates a new bio link.

  **Parameters**:

  * `organizationId`: Organization ID
  * `linkData`: Bio link configuration

  **Returns**: `Promise<BioLink>` - Created bio link
</Expandable>

<Expandable title="getBioLinks(organizationId, filters)">
  **Description**: Retrieves bio links with filtering.

  **Parameters**:

  * `organizationId`: Organization ID
  * `filters`: Filtering options

  **Returns**: `Promise<BioLink[]>` - List of bio links
</Expandable>

<Expandable title="updateBioLink(bioLinkId, updates)">
  **Description**: Updates an existing bio link.

  **Parameters**:

  * `bioLinkId`: Bio link ID
  * `updates`: Update data

  **Returns**: `Promise<BioLink>` - Updated bio link
</Expandable>

<Expandable title="deleteBioLink(bioLinkId)">
  **Description**: Deletes a bio link.

  **Parameters**:

  * `bioLinkId`: Bio link ID

  **Returns**: `Promise<void>`
</Expandable>

<Expandable title="trackBioLinkClick(bioLinkId, clickData)">
  **Description**: Tracks bio link clicks for analytics.

  **Parameters**:

  * `bioLinkId`: Bio link ID
  * `clickData`: Click tracking data

  **Returns**: `Promise<void>`
</Expandable>

## Content Analytics

### Performance Tracking

Content analytics provide insights into content performance and engagement.

#### Get Content Performance

```typescript theme={null}
// Get content performance metrics
const performance = await contentService.getContentPerformance(
  organizationId,
  {
    dateRange: {
      start: "2024-01-01",
      end: "2024-01-31"
    },
    platforms: ["FACEBOOK", "INSTAGRAM"],
    metrics: ["reach", "engagement", "clicks", "conversions"]
  }
);
```

#### Get Top Performing Content

```typescript theme={null}
// Get top performing content
const topContent = await contentService.getTopPerformingContent(
  organizationId,
  {
    metric: "engagement_rate",
    limit: 10,
    dateRange: {
      start: "2024-01-01",
      end: "2024-01-31"
    }
  }
);
```

#### Get Content Insights

```typescript theme={null}
// Get detailed content insights
const insights = await contentService.getContentInsights(
  organizationId,
  {
    postId: "post_123",
    includeAudience: true,
    includeTiming: true,
    includeKeywords: true
  }
);
```

### Analytics Operations

<Expandable title="getContentPerformance(organizationId, options)">
  **Description**: Retrieves content performance metrics.

  **Parameters**:

  * `organizationId`: Organization ID
  * `options`: Performance analysis options

  **Returns**: `Promise<ContentPerformance>` - Performance metrics
</Expandable>

<Expandable title="getTopPerformingContent(organizationId, options)">
  **Description**: Retrieves top performing content.

  **Parameters**:

  * `organizationId`: Organization ID
  * `options`: Top content filtering options

  **Returns**: `Promise<ContentPost[]>` - Top performing content
</Expandable>

<Expandable title="getContentInsights(organizationId, options)">
  **Description**: Retrieves detailed content insights.

  **Parameters**:

  * `organizationId`: Organization ID
  * `options`: Insights configuration

  **Returns**: `Promise<ContentInsights>` - Detailed insights
</Expandable>

<Expandable title="getContentTrends(organizationId, options)">
  **Description**: Analyzes content trends over time.

  **Parameters**:

  * `organizationId`: Organization ID
  * `options`: Trend analysis options

  **Returns**: `Promise<ContentTrends>` - Trend analysis
</Expandable>

## Content Attribution

### Lead Generation Tracking

Content attribution tracks how content generates leads and conversions.

#### Track Content Interaction

```typescript theme={null}
// Track content interaction for attribution
await contentService.trackContentInteraction(
  organizationId,
  {
    contentPostId: "post_123",
    interactionType: "click",
    userId: "user_456",
    utmData: {
      source: "social_media",
      medium: "post",
      campaign: "summer_sale"
    }
  }
);
```

#### Get Content Attribution

```typescript theme={null}
// Get content attribution data
const attribution = await contentService.getContentAttribution(
  organizationId,
  {
    contentPostId: "post_123",
    dateRange: {
      start: "2024-01-01",
      end: "2024-01-31"
    },
    includeConversions: true
  }
);
```

#### Link Content to Lead

```typescript theme={null}
// Link content to lead for attribution
await contentService.linkContentToLead(
  organizationId,
  {
    contentPostId: "post_123",
    leadId: "lead_456",
    attributionType: "first_touch",
    attributionWeight: 1.0
  }
);
```

### Attribution Operations

<Expandable title="trackContentInteraction(organizationId, interactionData)">
  **Description**: Tracks content interactions for attribution.

  **Parameters**:

  * `organizationId`: Organization ID
  * `interactionData`: Interaction tracking data

  **Returns**: `Promise<void>`
</Expandable>

<Expandable title="getContentAttribution(organizationId, options)">
  **Description**: Retrieves content attribution data.

  **Parameters**:

  * `organizationId`: Organization ID
  * `options`: Attribution analysis options

  **Returns**: `Promise<ContentAttribution>` - Attribution data
</Expandable>

<Expandable title="linkContentToLead(organizationId, linkData)">
  **Description**: Links content to lead for attribution tracking.

  **Parameters**:

  * `organizationId`: Organization ID
  * `linkData`: Content-lead link data

  **Returns**: `Promise<void>`
</Expandable>

<Expandable title="getAttributionReport(organizationId, options)">
  **Description**: Generates comprehensive attribution report.

  **Parameters**:

  * `organizationId`: Organization ID
  * `options`: Report configuration

  **Returns**: `Promise<AttributionReport>` - Attribution report
</Expandable>

## Integration Examples

### Complete Content Creation Flow

```typescript theme={null}
// Complete content creation and publishing workflow
async function createAndPublishContent(
  organizationId: string,
  contentData: any
) {
  try {
    // 1. Create content post
    const contentPost = await contentService.createContentPost(
      organizationId,
      contentData
    );

    // 2. Sync with social media platform
    const syncResult = await contentSyncService.syncContent(
      organizationId,
      {
        socialAccountId: contentData.socialAccountId,
        platform: contentData.platform,
        syncType: "posts",
        createTrackingRecords: true
      }
    );

    // 3. Track for attribution
    await contentService.trackContentInteraction(
      organizationId,
      {
        contentPostId: contentPost.id,
        interactionType: "created",
        userId: contentData.userId
      }
    );

    // 4. Set up analytics tracking
    await contentService.setupAnalyticsTracking(
      contentPost.id,
      {
        trackClicks: true,
        trackEngagement: true,
        trackConversions: true
      }
    );

    return {
      contentPost,
      syncResult,
      success: true
    };
  } catch (error) {
    // Handle content creation errors
    throw error;
  }
}
```

### Live Data Synchronization Flow

```typescript theme={null}
// Live data synchronization workflow
async function syncLiveData(organizationId: string, options: any) {
  try {
    // 1. Get existing posts
    const existingPosts = await contentService.getContentPosts(
      organizationId,
      {
        socialAccountId: options.socialAccountId,
        platform: options.platform,
        includeLiveData: false
      }
    );

    // 2. Fetch live data from platform
    const liveData = await contentSyncService.fetchLiveData(
      organizationId,
      {
        postIds: existingPosts.map(p => p.id),
        includeMetrics: true,
        includeComments: true,
        includeReactions: true
      }
    );

    // 3. Merge live data with existing posts
    const mergedPosts = await contentSyncService.mergeLiveData(
      existingPosts,
      liveData
    );

    // 4. Update posts with live data
    for (const post of mergedPosts) {
      await contentService.updateContentPost(post.id, {
        liveMetrics: post.liveMetrics,
        lastSyncedAt: new Date().toISOString()
      });
    }

    // 5. Check for new posts and sync them
    const newPosts = await contentSyncService.autoSyncNewPosts(
      organizationId,
      {
        socialAccountId: options.socialAccountId,
        platform: options.platform,
        batchSize: 20,
        createTrackingRecords: true
      }
    );

    return {
      updatedPosts: mergedPosts,
      newPosts,
      success: true
    };
  } catch (error) {
    // Handle sync errors
    throw error;
  }
}
```

### Content Performance Analysis Flow

```typescript theme={null}
// Content performance analysis workflow
async function analyzeContentPerformance(
  organizationId: string,
  analysisOptions: any
) {
  try {
    // 1. Get performance metrics
    const performance = await contentService.getContentPerformance(
      organizationId,
      analysisOptions
    );

    // 2. Get top performing content
    const topContent = await contentService.getTopPerformingContent(
      organizationId,
      {
        metric: "engagement_rate",
        limit: 10,
        dateRange: analysisOptions.dateRange
      }
    );

    // 3. Get content insights
    const insights = await Promise.all(
      topContent.map(post =>
        contentService.getContentInsights(organizationId, {
          postId: post.id,
          includeAudience: true,
          includeTiming: true,
          includeKeywords: true
        })
      )
    );

    // 4. Get attribution data
    const attribution = await contentService.getAttributionReport(
      organizationId,
      {
        dateRange: analysisOptions.dateRange,
        includeConversions: true,
        includeRevenue: true
      }
    );

    // 5. Generate recommendations
    const recommendations = await contentService.generateRecommendations(
      organizationId,
      {
        performance,
        topContent,
        insights,
        attribution
      }
    );

    return {
      performance,
      topContent,
      insights,
      attribution,
      recommendations,
      success: true
    };
  } catch (error) {
    // Handle analysis errors
    throw error;
  }
}
```

## Error Handling

### Common Error Scenarios

<Expandable title="Sync Failures">
  ```typescript theme={null}
  try {
    const syncResult = await contentSyncService.syncContent(orgId, options);
  } catch (error) {
    if (error.code === 'PLATFORM_API_ERROR') {
      // Handle platform API errors
      await retrySyncWithBackoff(orgId, options);
    } else if (error.code === 'RATE_LIMIT_EXCEEDED') {
      // Handle rate limiting
      await delaySync(orgId, options, 60000); // Wait 1 minute
    }
  }
  ```
</Expandable>

<Expandable title="Content Creation Errors">
  ```typescript theme={null}
  try {
    const contentPost = await contentService.createContentPost(orgId, data);
  } catch (error) {
    if (error.code === 'INVALID_CONTENT') {
      throw new BadRequestError('Invalid content format');
    } else if (error.code === 'DUPLICATE_CONTENT') {
      throw new ConflictError('Content already exists');
    }
  }
  ```
</Expandable>

<Expandable title="Analytics Errors">
  ```typescript theme={null}
  try {
    const analytics = await contentService.getContentAnalytics(orgId, options);
  } catch (error) {
    if (error.code === 'INSUFFICIENT_DATA') {
      return { analytics: null, message: 'Insufficient data for analysis' };
    } else if (error.code === 'ANALYTICS_UNAVAILABLE') {
      // Fallback to basic metrics
      return await contentService.getBasicMetrics(orgId, options);
    }
  }
  ```
</Expandable>

## Performance Optimization

### Caching Strategy

```typescript theme={null}
// Implement caching for content data
const cachedContent = await contentCache.get(`content:${organizationId}:${postId}`);
if (!cachedContent) {
  const content = await contentService.getContentPost(postId);
  await contentCache.set(`content:${organizationId}:${postId}`, content, 3600); // 1 hour
}
```

### Batch Operations

```typescript theme={null}
// Batch content operations for better performance
const batchResults = await Promise.allSettled(
  contentPosts.map(post =>
    contentService.updateContentPost(post.id, updateData)
  )
);
```

### Rate Limiting

```typescript theme={null}
// Implement rate limiting for platform APIs
const rateLimiter = new RateLimiter({
  windowMs: 60000, // 1 minute
  max: 60 // 60 requests per minute
});

const syncWithRateLimit = rateLimiter.wrap(contentSyncService.syncContent);
```

## Monitoring and Analytics

### Content Metrics

```typescript theme={null}
// Track content metrics
const contentMetrics = {
  totalPosts: await contentService.getTotalPosts(organizationId),
  averageEngagement: await contentService.getAverageEngagement(organizationId),
  topPlatform: await contentService.getTopPlatform(organizationId),
  contentVelocity: await contentService.getContentVelocity(organizationId)
};

await analyticsService.track('content_metrics_updated', contentMetrics);
```

### Sync Metrics

```typescript theme={null}
// Track sync performance
const syncMetrics = {
  syncSuccessRate: await contentSyncService.getSyncSuccessRate(organizationId),
  averageSyncTime: await contentSyncService.getAverageSyncTime(organizationId),
  failedSyncs: await contentSyncService.getFailedSyncs(organizationId),
  newPostsDiscovered: await contentSyncService.getNewPostsCount(organizationId)
};

await analyticsService.track('sync_metrics_updated', syncMetrics);
```
