Skip to content
Shell
12.1 KB
Raw Blame
/**
 * Notion Sync Integration
 * Automatically pushes insights to Notion database
 */

import { execFileNoThrow } from '../utils/execFileNoThrow.js';
import type { GoldmineScore, MarketInsight, ThreadData } from '../types.js';

export interface NotionConfig {
  apiKey: string;
  databaseId?: string;
  parentPageId?: string;
}

interface NotionPage {
  id: string;
  url: string;
}

/**
 * Make Notion API request
 */
async function notionRequest(
  apiKey: string,
  endpoint: string,
  method: string,
  body?: Record<string, unknown>
): Promise<{ success: boolean; data?: any; error?: string }> {
  const args = [
    '-s',
    '-X', method,
    `https://api.notion.com/v1${endpoint}`,
    '-H', `Authorization: Bearer ${apiKey}`,
    '-H', 'Content-Type: application/json',
    '-H', 'Notion-Version: 2022-06-28'
  ];

  if (body) {
    args.push('-d', JSON.stringify(body));
  }

  const result = await execFileNoThrow('curl', args);

  if (result.status === 'error') {
    return { success: false, error: result.stderr };
  }

  try {
    const data = JSON.parse(result.stdout);
    if (data.object === 'error') {
      return { success: false, error: data.message };
    }
    return { success: true, data };
  } catch {
    return { success: false, error: 'Invalid JSON response' };
  }
}

/**
 * Create a Notion page with thread data
 */
async function createThreadPage(
  apiKey: string,
  parentId: string,
  thread: GoldmineScore,
  insights?: MarketInsight
): Promise<NotionPage | null> {
  // Build rich text content
  const content: any[] = [
    {
      object: 'block',
      type: 'heading_2',
      heading_2: {
        rich_text: [{ type: 'text', text: { content: 'Thread Info' } }]
      }
    },
    {
      object: 'block',
      type: 'bulleted_list_item',
      bulleted_list_item: {
        rich_text: [{ type: 'text', text: { content: `Subreddit: r/${thread.subreddit}` } }]
      }
    },
    {
      object: 'block',
      type: 'bulleted_list_item',
      bulleted_list_item: {
        rich_text: [{ type: 'text', text: { content: `Score: ${thread.score} pts` } }]
      }
    },
    {
      object: 'block',
      type: 'bulleted_list_item',
      bulleted_list_item: {
        rich_text: [{ type: 'text', text: { content: `Comments: ${thread.numComments}` } }]
      }
    },
    {
      object: 'block',
      type: 'bulleted_list_item',
      bulleted_list_item: {
        rich_text: [{ type: 'text', text: { content: `Goldmine Score: ${thread.goldmineScore}` } }]
      }
    },
    {
      object: 'block',
      type: 'bookmark',
      bookmark: { url: thread.url }
    }
  ];

  // Add insights if available
  if (insights) {
    // Summary
    content.push({
      object: 'block',
      type: 'heading_2',
      heading_2: {
        rich_text: [{ type: 'text', text: { content: 'Summary' } }]
      }
    });
    content.push({
      object: 'block',
      type: 'callout',
      callout: {
        icon: { emoji: 'πŸ“Š' },
        rich_text: [{ type: 'text', text: { content: insights.summary } }]
      }
    });

    // Pain Points
    if (insights.painPoints.length > 0) {
      content.push({
        object: 'block',
        type: 'heading_2',
        heading_2: {
          rich_text: [{ type: 'text', text: { content: 'πŸ”΄ Pain Points' } }]
        }
      });
      for (const pp of insights.painPoints) {
        content.push({
          object: 'block',
          type: 'bulleted_list_item',
          bulleted_list_item: {
            rich_text: [
              { type: 'text', text: { content: pp.description } },
              { type: 'text', text: { content: ` (${pp.sentiment}, freq: ${pp.frequency})` }, annotations: { color: 'gray' } }
            ]
          }
        });
      }
    }

    // Opportunities
    if (insights.opportunities.length > 0) {
      content.push({
        object: 'block',
        type: 'heading_2',
        heading_2: {
          rich_text: [{ type: 'text', text: { content: 'πŸ’‘ Opportunities' } }]
        }
      });
      for (const opp of insights.opportunities) {
        content.push({
          object: 'block',
          type: 'bulleted_list_item',
          bulleted_list_item: {
            rich_text: [
              { type: 'text', text: { content: `[${opp.confidence}] ` }, annotations: { bold: true } },
              { type: 'text', text: { content: opp.description } },
              { type: 'text', text: { content: ` β†’ ${opp.targetAudience}` }, annotations: { color: 'gray' } }
            ]
          }
        });
      }
    }

    // Competitor Mentions
    if (insights.competitorMentions.length > 0) {
      content.push({
        object: 'block',
        type: 'heading_2',
        heading_2: {
          rich_text: [{ type: 'text', text: { content: '🏒 Competitors' } }]
        }
      });
      for (const comp of insights.competitorMentions) {
        const emoji = comp.sentiment === 'positive' ? 'πŸ‘' : comp.sentiment === 'negative' ? 'πŸ‘Ž' : 'βž–';
        content.push({
          object: 'block',
          type: 'bulleted_list_item',
          bulleted_list_item: {
            rich_text: [
              { type: 'text', text: { content: `${emoji} ${comp.name}` }, annotations: { bold: true } },
              { type: 'text', text: { content: ` - ${comp.context}` } }
            ]
          }
        });
      }
    }

    // Buying Signals
    if (insights.buyingSignals.length > 0) {
      content.push({
        object: 'block',
        type: 'heading_2',
        heading_2: {
          rich_text: [{ type: 'text', text: { content: 'πŸ’° Buying Signals' } }]
        }
      });
      for (const signal of insights.buyingSignals) {
        content.push({
          object: 'block',
          type: 'quote',
          quote: {
            rich_text: [
              { type: 'text', text: { content: `"${signal.quote.slice(0, 200)}${signal.quote.length > 200 ? '...' : ''}"` } },
              { type: 'text', text: { content: ` β€” u/${signal.author}` }, annotations: { italic: true, color: 'gray' } }
            ]
          }
        });
      }
    }

    // Key Quotes
    if (insights.keyQuotes.length > 0) {
      content.push({
        object: 'block',
        type: 'heading_2',
        heading_2: {
          rich_text: [{ type: 'text', text: { content: 'πŸ’¬ Key Quotes' } }]
        }
      });
      for (const quote of insights.keyQuotes) {
        content.push({
          object: 'block',
          type: 'quote',
          quote: {
            rich_text: [
              { type: 'text', text: { content: `"${quote.text.slice(0, 300)}${quote.text.length > 300 ? '...' : ''}"` } },
              { type: 'text', text: { content: ` β€” u/${quote.author} (${quote.score} pts)` }, annotations: { italic: true, color: 'gray' } }
            ]
          }
        });
      }
    }
  }

  const response = await notionRequest(apiKey, '/pages', 'POST', {
    parent: { page_id: parentId },
    icon: { emoji: 'πŸ“Š' },
    properties: {
      title: {
        title: [{ text: { content: `${thread.title.slice(0, 100)}` } }]
      }
    },
    children: content.slice(0, 100) // Notion limit
  });

  if (!response.success) {
    console.error('Failed to create Notion page:', response.error);
    return null;
  }

  return {
    id: response.data.id,
    url: response.data.url
  };
}

/**
 * Notion Sync Manager
 */
export class NotionSync {
  private config: NotionConfig;
  private verbose: boolean;

  constructor(config: NotionConfig, options: { verbose?: boolean } = {}) {
    this.config = config;
    this.verbose = options.verbose ?? false;
  }

  /**
   * Check if Notion is properly configured
   */
  isConfigured(): boolean {
    return !!(this.config.apiKey && (this.config.parentPageId || this.config.databaseId));
  }

  /**
   * Sync a thread to Notion
   */
  async syncThread(thread: GoldmineScore, insights?: MarketInsight): Promise<NotionPage | null> {
    const parentId = this.config.parentPageId || this.config.databaseId;
    if (!parentId) {
      if (this.verbose) {
        console.error('No Notion parent page or database configured');
      }
      return null;
    }

    return createThreadPage(this.config.apiKey, parentId, thread, insights);
  }

  /**
   * Sync multiple threads (simple format - just threads)
   */
  async syncThreads(threads: GoldmineScore[]): Promise<NotionPage[]> {
    const pages: NotionPage[] = [];

    for (const thread of threads) {
      const page = await this.syncThread(thread);
      if (page) {
        pages.push(page);
        if (this.verbose) {
          console.log(`Synced to Notion: ${thread.title.slice(0, 40)}...`);
        }
      }
      // Rate limit: 3 requests per second
      await new Promise(resolve => setTimeout(resolve, 350));
    }

    return pages;
  }

  /**
   * Sync multiple threads with insights
   */
  async syncThreadsWithInsights(threads: Array<{ thread: GoldmineScore; insights?: MarketInsight }>): Promise<NotionPage[]> {
    const pages: NotionPage[] = [];

    for (const { thread, insights } of threads) {
      const page = await this.syncThread(thread, insights);
      if (page) {
        pages.push(page);
      }
      // Rate limit: 3 requests per second
      await new Promise(resolve => setTimeout(resolve, 350));
    }

    return pages;
  }

  /**
   * Create a daily digest page
   */
  async createDigest(date: string, stats: {
    threadsScanned: number;
    insightsFound: number;
    topThreads: GoldmineScore[];
    topPainPoints: string[];
    topOpportunities: string[];
  }): Promise<NotionPage | null> {
    const parentId = this.config.parentPageId || this.config.databaseId;
    if (!parentId) {
      return null;
    }

    const content: any[] = [
      {
        object: 'block',
        type: 'callout',
        callout: {
          icon: { emoji: 'πŸ“ˆ' },
          rich_text: [{
            type: 'text',
            text: { content: `Scanned ${stats.threadsScanned} threads, found ${stats.insightsFound} insights` }
          }]
        }
      },
      {
        object: 'block',
        type: 'heading_2',
        heading_2: { rich_text: [{ type: 'text', text: { content: 'Top Threads' } }] }
      }
    ];

    for (const thread of stats.topThreads.slice(0, 5)) {
      content.push({
        object: 'block',
        type: 'bulleted_list_item',
        bulleted_list_item: {
          rich_text: [
            { type: 'text', text: { content: `[${thread.goldmineScore}] ` }, annotations: { bold: true } },
            { type: 'text', text: { content: thread.title.slice(0, 60), link: { url: thread.url } } }
          ]
        }
      });
    }

    if (stats.topPainPoints.length > 0) {
      content.push({
        object: 'block',
        type: 'heading_2',
        heading_2: { rich_text: [{ type: 'text', text: { content: 'πŸ”΄ Top Pain Points' } }] }
      });
      for (const pp of stats.topPainPoints.slice(0, 5)) {
        content.push({
          object: 'block',
          type: 'bulleted_list_item',
          bulleted_list_item: { rich_text: [{ type: 'text', text: { content: pp } }] }
        });
      }
    }

    if (stats.topOpportunities.length > 0) {
      content.push({
        object: 'block',
        type: 'heading_2',
        heading_2: { rich_text: [{ type: 'text', text: { content: 'πŸ’‘ Top Opportunities' } }] }
      });
      for (const opp of stats.topOpportunities.slice(0, 5)) {
        content.push({
          object: 'block',
          type: 'bulleted_list_item',
          bulleted_list_item: { rich_text: [{ type: 'text', text: { content: opp } }] }
        });
      }
    }

    const response = await notionRequest(this.config.apiKey, '/pages', 'POST', {
      parent: { page_id: parentId },
      icon: { emoji: 'πŸ“…' },
      properties: {
        title: { title: [{ text: { content: `Research Digest - ${date}` } }] }
      },
      children: content
    });

    if (!response.success) {
      return null;
    }

    return { id: response.data.id, url: response.data.url };
  }
}

/**
 * Create Notion sync from environment
 */
export function createNotionSync(options: { verbose?: boolean } = {}): NotionSync | null {
  const apiKey = process.env.NOTION_API_KEY;
  if (!apiKey) {
    return null;
  }

  return new NotionSync({
    apiKey,
    parentPageId: process.env.NOTION_PARENT_PAGE_ID,
    databaseId: process.env.NOTION_DATABASE_ID
  }, options);
}