### Install Supabase CLI Source: https://github.com/superbeats1/new-gen/blob/main/STRIPE_WEBHOOK_SETUP.md Installs the Supabase Command Line Interface globally using npm. This tool is necessary for managing Supabase projects, including deploying functions and setting secrets. ```bash npm install -g supabase ``` -------------------------------- ### Link Supabase CLI to Project Source: https://github.com/superbeats1/new-gen/blob/main/STRIPE_WEBHOOK_SETUP.md Connects the Supabase CLI to a specific Supabase project using its unique project reference ID. This ensures subsequent commands target the correct project. ```bash supabase link --project-ref YOUR_PROJECT_ID ``` -------------------------------- ### Login to Supabase CLI Source: https://github.com/superbeats1/new-gen/blob/main/STRIPE_WEBHOOK_SETUP.md Authenticates the Supabase CLI with your Supabase account. This command prompts for an access token, which can be generated from your Supabase account settings. ```bash supabase login ``` -------------------------------- ### Testing URL Opening in Browser Console Source: https://github.com/superbeats1/new-gen/blob/main/DEBUG_LINKS.md Provides JavaScript examples to test the opening of different types of URLs in a new browser tab. Includes testing real Reddit and HackerNews URLs, as well as how to catch errors for invalid URL formats. ```javascript // Test real Reddit URL window.open('https://reddit.com/r/entrepreneur/comments/abc123/test', '_blank'); // Test real HackerNews URL window.open('https://news.ycombinator.com/item?id=123456', '_blank'); // Test invalid URL try { new URL('invalid-url'); } catch(e) { console.log('Expected error:', e); } ``` -------------------------------- ### Deploy Webhook Script Source: https://github.com/superbeats1/new-gen/blob/main/QUICK_TEST.md This bash script is used to deploy the webhook necessary for automatic Stripe to Supabase updates. It assumes the script is available in the project's root directory. ```bash ./deploy-webhook.sh ``` -------------------------------- ### View Supabase Function Logs Source: https://github.com/superbeats1/new-gen/blob/main/QUICK_TEST.md Command to view the logs for the 'stripe-webhook' Supabase function, useful for debugging issues with payment processing and webhook events. ```bash supabase functions logs stripe-webhook ``` -------------------------------- ### View Supabase Edge Function Logs Source: https://github.com/superbeats1/new-gen/blob/main/STRIPE_WEBHOOK_SETUP.md Retrieves logs for a specific Supabase Edge Function. This is crucial for debugging issues related to function execution and webhook processing. The `--follow` flag provides real-time log streaming. ```bash supabase functions logs stripe-webhook supabase functions logs stripe-webhook --follow ``` -------------------------------- ### Deploy Supabase Edge Function Source: https://github.com/superbeats1/new-gen/blob/main/STRIPE_WEBHOOK_SETUP.md Deploys an Edge Function named 'stripe-webhook' to your Supabase project. This function will handle incoming Stripe webhook events. ```bash supabase functions deploy stripe-webhook ``` -------------------------------- ### Set Supabase Environment Secrets Source: https://github.com/superbeats1/new-gen/blob/main/STRIPE_WEBHOOK_SETUP.md Configures essential environment variables as secrets within your Supabase project. These include the Stripe webhook signing secret and Supabase project credentials for secure access. ```bash # Set your Stripe webhook secret (get this from Stripe Dashboard) supabase secrets set STRIPE_WEBHOOK_SECRET=whsec_your_webhook_secret_here # Set your Supabase URL and Service Role Key supabase secrets set SUPABASE_URL=https://your-project.supabase.co supabase secrets set SUPABASE_SERVICE_ROLE_KEY=your_service_role_key_here ``` -------------------------------- ### Demo Pattern Detection for URLs Source: https://github.com/superbeats1/new-gen/blob/main/DEBUG_LINKS.md Identifies if a URL matches a predefined list of demo URLs or contains specific patterns indicative of a demo or internal link. It also checks if the URL starts with 'http' to distinguish between web URLs and other types of identifiers. ```typescript const isDemoPattern = demoUrls.includes(sourceUrl) || sourceUrl.includes('activity-demo-') || sourceUrl.includes('realistic-profile') || !sourceUrl.startsWith('http'); ``` -------------------------------- ### Enhanced Logging for Link Clicking Debugging Source: https://github.com/superbeats1/new-gen/blob/main/DEBUG_LINKS.md Logs the source URL, source, and prospect name when attempting to open a URL. This helps in identifying the context of the link clicking operation and diagnosing issues related to missing or incorrect data. ```typescript console.log('Attempting to open URL:', { sourceUrl, source, prospectName }); ``` -------------------------------- ### Fallback Values for Link Click Handler Source: https://github.com/superbeats1/new-gen/blob/main/DEBUG_LINKS.md Provides default or fallback values for `sourceUrl`, `source`, and `prospectName` if they are not provided. This prevents errors when these properties are missing in the lead object, ensuring the click handler can still execute. ```typescript onClick={() => handleSourceClick( lead.sourceUrl || '', lead.source || 'Unknown', lead.prospectName || 'Anonymous' )} ``` -------------------------------- ### AI Outreach Message Generator with Google Gemini (TypeScript) Source: https://context7.com/superbeats1/new-gen/llms.txt This TypeScript code snippet demonstrates how to generate personalized outreach messages using Google Gemini AI. It imports a `generateOutreach` function from a `geminiService` and utilizes a `Lead` type. The example shows how to structure lead data and a personal profile to create tailored outreach messages, which are then logged to the console. Dependencies include `geminiService` and `types` modules. ```typescript import { generateOutreach } from './geminiService'; import { Lead } from './types'; const lead: Lead = { id: "lead_002", prospectName: "Michael Chen", username: "@mchen", requestSummary: "Seeking React developer for e-commerce platform redesign", postedAt: "1 day ago", source: "Upwork", location: "Remote", fitScore: 9, budget: "High", budgetAmount: "$8,000", urgency: "Medium", contactInfo: "Apply on Upwork", sourceUrl: "https://upwork.com/jobs/~012345", status: "New" }; const myProfile = ` I'm a senior React developer with 5 years of experience specializing in e-commerce platforms. I've built shopping carts, payment integrations, and responsive UIs for brands like Shopify merchants and direct-to-consumer startups. `; const outreachMessage = await generateOutreach(lead, myProfile); console.log(outreachMessage); // "Subject: Experienced React Developer for Your E-commerce Redesign // // Hi Michael, // // I noticed your post about redesigning your e-commerce platform, and it caught // my attention because I've specialized in exactly this type of work for the past // 5 years. I've built responsive shopping experiences and integrated payment systems // for Shopify merchants and D2C brands. // // I'd love to discuss your specific requirements and share some relevant case studies. // Would you be open to a quick 15-minute call this week? // // Best regards" ``` -------------------------------- ### Type Guard for Validating sourceUrl Source: https://github.com/superbeats1/new-gen/blob/main/DEBUG_LINKS.md Ensures that the `sourceUrl` is a non-empty string before proceeding with URL operations. This prevents 'TypeError: Cannot read properties of undefined' errors by validating the type and existence of the URL. ```typescript if (!sourceUrl || typeof sourceUrl !== 'string') { console.warn('No valid sourceUrl provided:', sourceUrl); return; } ``` -------------------------------- ### Set Supabase Environment Secrets for Stripe Webhook Source: https://github.com/superbeats1/new-gen/blob/main/QUICK_TEST.md Configures Supabase secrets for handling Stripe webhooks. Requires the Stripe webhook signing secret and Supabase project credentials. These secrets are essential for securely processing payment events from Stripe. ```bash supabase secrets set STRIPE_WEBHOOK_SECRET=whsec_your_secret supabase secrets set SUPABASE_URL=https://your-project.supabase.co supabase secrets set SUPABASE_SERVICE_ROLE_KEY=your_service_role_key ``` -------------------------------- ### Approach Comparison: Mock vs. Real Data Source: https://github.com/superbeats1/new-gen/blob/main/REAL_DATA_INTEGRATION.md Illustrates the shift from a purely AI-driven mock data approach in v1.0 to a real data integration strategy with AI supplementation in v2.0. ```typescript // Old approach: Pure AI simulation User Query → Gemini AI → Mock Lead Data → Display ``` ```typescript // New approach: Real data + AI enhancement User Query → Live API Scanning → Real Leads + AI Supplementation → Display ``` -------------------------------- ### Create Subscription Checkout Sessions with Stripe (TypeScript) Source: https://context7.com/superbeats1/new-gen/llms.txt Facilitates user upgrades to a Pro plan by creating Stripe subscription checkout sessions. It handles the initiation of the checkout process and provides a mechanism to manage the success redirect within the application. Dependencies include './lib/stripe'. Inputs are implicit user context, outputs are Stripe checkout session initiation and UI feedback. ```typescript import { createCheckoutSession } from './lib/stripe'; // Create checkout session and redirect to Stripe try { await createCheckoutSession(); // User is automatically redirected to Stripe checkout page // Success URL: https://your-app.com/?payment=success // Cancel URL: https://your-app.com/ } catch (error) { console.error('Checkout failed:', error); alert('Failed to start upgrade process. Please try again.'); } // Handle success redirect in application useEffect(() => { const urlParams = new URLSearchParams(window.location.search); const paymentSuccess = urlParams.get('payment'); if (paymentSuccess === 'success') { // Clear URL parameters window.history.replaceState({}, document.title, window.location.pathname); // Refresh user profile to get updated Pro status fetchProfile(session.user.id); // Show success message setShowSuccessPage(true); } }, [session]); ``` -------------------------------- ### Manage User Authentication and Profiles with Supabase (TypeScript) Source: https://context7.com/superbeats1/new-gen/llms.txt Handles user authentication (sign-up, sign-in, sign-out), session management, and user profile data retrieval and updates. It integrates with Supabase for database operations and tracks user credits. Dependencies include './lib/supabase'. Inputs are user credentials and profile data, outputs include session objects and profile data. ```typescript import { supabase } from './lib/supabase'; // Sign up new user const { data: signUpData, error: signUpError } = await supabase.auth.signUp({ email: 'user@example.com', password: 'securepassword123', options: { data: { first_name: 'Jane', last_name: 'Doe' } } }); // Sign in existing user const { data: signInData, error: signInError } = await supabase.auth.signInWithPassword({ email: 'user@example.com', password: 'securepassword123' }); // Get current session const { data: { session } } = await supabase.auth.getSession(); console.log(session); // { // access_token: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...", // user: { // id: "uuid-12345", // email: "user@example.com", // user_metadata: { first_name: "Jane", last_name: "Doe" } // } // } // Fetch user profile with credits const { data: profile, error } = await supabase .from('profiles') .select('*') .eq('id', session.user.id) .single(); console.log(profile); // { // id: "uuid-12345", // email: "user@example.com", // first_name: "Jane", // last_name: "Doe", // credits: 10, // is_pro: false, // total_credits_used: 0, // created_at: "2025-01-01T00:00:00.000Z", // updated_at: "2025-01-06T10:45:00.000Z" // } // Deduct credit after successful search const { error: updateError } = await supabase .from('profiles') .update({ credits: profile.credits - 1, total_credits_used: profile.total_credits_used + 1, updated_at: new Date().toISOString() }) .eq('id', profile.id); // Sign out await supabase.auth.signOut(); ``` -------------------------------- ### Supabase Authentication API Source: https://context7.com/superbeats1/new-gen/llms.txt Manages user authentication, session handling, and profile data with credit tracking for free and pro users. ```APIDOC ## Supabase Authentication API ### Description Manages user authentication, session handling, and profile data with credit tracking for free and pro users using Supabase. ### Method POST /auth/v1/signup (for sign up) POST /auth/v1/token?grant_type=password (for sign in) GET /auth/v1/user (for getting current session) GET /rest/v1/profiles (for fetching profile) PUT /rest/v1/profiles (for updating profile) POST /auth/v1/logout (for sign out) ### Endpoint `/auth/v1/*` and `/rest/v1/*` (Supabase specific endpoints) ### Parameters #### Sign Up ##### Request Body - **email** (string) - Required - User's email address. - **password** (string) - Required - User's password. - **options.data** (object) - Optional - Additional user metadata. - **first_name** (string) - Optional - User's first name. - **last_name** (string) - Optional - User's last name. #### Sign In ##### Request Body - **email** (string) - Required - User's email address. - **password** (string) - Required - User's password. #### Fetch User Profile ##### Query Parameters - **id** (string) - Required - The ID of the user profile to fetch. #### Deduct Credit ##### Path Parameters - **id** (string) - Required - The ID of the user profile to update. ##### Request Body - **credits** (number) - Required - The new credit balance (current credits - 1). - **total_credits_used** (number) - Required - The updated total credits used. - **updated_at** (string) - Required - Current timestamp in ISO 8601 format. ### Request Example ```typescript // Sign up new user await supabase.auth.signUp({ email: 'user@example.com', password: 'securepassword123', options: { data: { first_name: 'Jane', last_name: 'Doe' } } }); // Sign in existing user await supabase.auth.signInWithPassword({ email: 'user@example.com', password: 'securepassword123' }); // Fetch user profile const session = await supabase.auth.getSession(); const { data: profile } = await supabase.from('profiles').select('*').eq('id', session.data.session.user.id).single(); // Deduct credit await supabase.from('profiles').update({ credits: profile.credits - 1, total_credits_used: profile.total_credits_used + 1, updated_at: new Date().toISOString() }).eq('id', profile.id); ``` ### Response #### Success Response (200) - **session** (object) - Contains access token and user information. - **access_token** (string) - JWT for authenticated requests. - **user** (object) - User details. - **id** (string) - Unique user ID. - **email** (string) - User's email address. - **user_metadata** (object) - User-defined metadata (e.g., first_name, last_name). - **profile** (object) - User profile data from the 'profiles' table. - **id** (string) - User ID. - **email** (string) - User's email address. - **first_name** (string) - User's first name. - **last_name** (string) - User's last name. - **credits** (number) - Remaining credits. - **is_pro** (boolean) - Indicates if the user is a Pro member. - **total_credits_used** (number) - Total credits consumed. - **created_at** (string) - Timestamp of profile creation. - **updated_at** (string) - Timestamp of last profile update. #### Response Example ```json { "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...", "user": { "id": "uuid-12345", "email": "user@example.com", "user_metadata": { "first_name": "Jane", "last_name": "Doe" } } } ``` ```json { "id": "uuid-12345", "email": "user@example.com", "first_name": "Jane", "last_name": "Doe", "credits": 10, "is_pro": false, "total_credits_used": 0, "created_at": "2025-01-01T00:00:00.000Z", "updated_at": "2025-01-06T10:45:00.000Z" } ``` ``` -------------------------------- ### Analyze User Queries with Gemini AI for Leads or Opportunities (TypeScript) Source: https://context7.com/superbeats1/new-gen/llms.txt This TypeScript code snippet demonstrates how to use the `analyzeQuery` function from `geminiService` to process user input. It automatically determines whether the query is for finding business opportunities or active leads. The function returns a structured object containing the analysis mode, original query, a summary, and either lead or opportunity details. ```typescript import { analyzeQuery } from './geminiService'; import { WorkflowMode } from './types'; // Analyze a query for lead discovery const result = await analyzeQuery("Find clients who need a video editor for YouTube creators"); // Result structure console.log(result); // { // mode: WorkflowMode.LEAD, // query: "Find clients who need a video editor for YouTube creators", // summary: "Found 5 active leads from Reddit, HackerNews, and GitHub", // timestamp: "2025-01-06T10:30:00.000Z", // leads: [ // { // id: "lead_001", // prospectName: "Sarah Johnson", // username: "@sarahjvideo", // requestSummary: "Looking for experienced video editor for weekly YouTube content", // postedAt: "2 hours ago", // source: "Reddit", // location: "Austin, TX", // fitScore: 9, // budget: "High", // budgetAmount: "$3,500", // urgency: "High", // contactInfo: "DM on Reddit", // sourceUrl: "https://reddit.com/r/forhire/comments/abc123", // status: "New" // } // ] // } // Analyze a query for opportunity discovery const oppResult = await analyzeQuery("Find business opportunities in AI for legal firms"); console.log(oppResult); // { // mode: WorkflowMode.OPPORTUNITY, // query: "Find business opportunities in AI for legal firms", // summary: "Identified 4 potential opportunities through market analysis", // timestamp: "2025-01-06T10:35:00.000Z", // opportunities: [ // { // id: "opp-1", // problemStatement: "Legal firms struggle with contract analysis automation", // overallScore: 8, // demandSignal: 9, // marketReadiness: 7, // competition: "Underserved", // entryDifficulty: "Medium", // evidence: ["Growing AI adoption in legal sector", "High manual review costs"], // whyItMatters: "Legal teams spend 60% of time on document review", // redFlags: "Requires legal industry expertise and compliance knowledge", // nextSteps: ["Interview 5 legal professionals", "Build MVP contract parser"] // } // ] // } ``` -------------------------------- ### Parallel Real Data Collection Source: https://github.com/superbeats1/new-gen/blob/main/REAL_DATA_INTEGRATION.md Concurrently scans multiple live data sources (Reddit, HackerNews, GitHub) for relevant leads based on the user's query using Promise.all for efficient asynchronous operations. ```typescript // Parallel scanning of live sources const [redditLeads, hnLeads, githubLeads] = await Promise.all([ scanRedditForLeads(query), scanHackerNewsForLeads(query), scanGitHubForLeads(query) ]); ``` -------------------------------- ### Implement Credit-Based Usage Tracking with Automatic Deduction (TypeScript) Source: https://context7.com/superbeats1/new-gen/llms.txt This TypeScript code implements a credit management system for tracking user usage. It includes functions to check if a user has sufficient credits before performing an action, deduct credits after a successful action, and manage unlimited access for Pro users. It interacts with Supabase for profile data updates. Dependencies include 'supabase' from './lib/supabase' and a 'profile' object. ```typescript import { supabase } from './lib/supabase'; // Check if user has credits before search const canSearch = (profile: any): boolean => { if (profile.is_pro) { return true; // Pro users have unlimited searches } return profile.credits > 0; // Free users need credits }; // Deduct credit after successful search const deductCredit = async (profile: any): Promise => { if (!profile) return false; // Safety check for free users if (!profile.is_pro && profile.credits <= 0) { console.error('No credits remaining'); return false; } const newTotalUsed = (profile.total_credits_used || 0) + 1; const newCredits = profile.is_pro ? profile.credits : Math.max(0, profile.credits - 1); const { error } = await supabase .from('profiles') .update({ credits: newCredits, total_credits_used: newTotalUsed, updated_at: new Date().toISOString() }) .eq('id', profile.id); if (!error) { setProfile({ ...profile, credits: newCredits, total_credits_used: newTotalUsed }); return true; } console.error('Failed to deduct credit:', error); return false; }; // Search workflow with credit management const handleSearch = async (query: string) => { if (!canSearch(profile)) { alert("Out of credits! Please upgrade to Pro for unlimited neural scans."); return; } setIsSearching(true); try { const result = await analyzeQuery(query); // Only deduct credit after successful search const credited = await deductCredit(profile); if (!credited) { throw new Error('Failed to process credit'); } setResults(result); setView('results'); } catch (error) { console.error('Search failed:', error); alert('Search failed. Please try again.'); } finally { setIsSearching(false); } }; ``` -------------------------------- ### Lead Detection Keywords Source: https://github.com/superbeats1/new-gen/blob/main/REAL_DATA_INTEGRATION.md Defines a list of keywords commonly associated with lead generation opportunities, used for filtering and identifying potential leads. ```typescript const LEAD_KEYWORDS = [ 'looking for', 'need help with', 'seeking', 'hiring', 'freelancer needed', 'contractor needed', 'budget', 'pay', 'rate', 'urgent', 'asap' ]; ``` -------------------------------- ### Real-Time Lead Discovery API (TypeScript) Source: https://context7.com/superbeats1/new-gen/llms.txt This TypeScript code utilizes a `RealDataCollector` from `./services/realDataService` to find leads from live data sources like Reddit, HackerNews, and GitHub. The `findRealLeads` method takes a search query and a `WorkflowMode` (e.g., `WorkflowMode.LEAD`) as input. The output is an array of lead objects, each containing details such as prospect name, request summary, source, and contact information. This snippet requires the `RealDataCollector` class and `WorkflowMode` enum. ```typescript import { RealDataCollector } from './services/realDataService'; const collector = new RealDataCollector(); // Search for real leads from live sources const leads = await collector.findRealLeads( "Find clients who need a mobile app developer", WorkflowMode.LEAD ); console.log(leads); // [ // { // id: "reddit_abc123", // prospectName: "User from r/forhire", // username: "@startup_founder", // requestSummary: "Need iOS developer for fitness tracking app with HealthKit integration", // postedAt: "4 hours ago", // source: "Reddit", // location: "Boston, MA", // fitScore: 8, // budget: "Medium", // budgetAmount: "$4,000", // urgency: "High", // contactInfo: "Send DM on Reddit", // sourceUrl: "https://reddit.com/r/forhire/comments/abc123/hiring", // status: "New", // notes: "Real lead from Reddit r/forhire" // }, // { // id: "hn_item_456789", // prospectName: "HN User", // username: "techfounder", // requestSummary: "Looking for React Native developer for cross-platform app", // postedAt: "1 day ago", // source: "HackerNews", // fitScore: 7, // budget: "High", // urgency: "Medium", // contactInfo: "Email in HN profile", // sourceUrl: "https://news.ycombinator.com/item?id=456789", // status: "New", // notes: "Real lead from HackerNews" // } // ] ``` -------------------------------- ### Stripe Checkout API Source: https://context7.com/superbeats1/new-gen/llms.txt Creates subscription checkout sessions for upgrading users to Pro plan with unlimited searches. ```APIDOC ## Stripe Checkout API ### Description Creates subscription checkout sessions for upgrading users to the Pro plan with unlimited searches via Stripe. ### Method POST /api/create-checkout-session (Hypothetical) ### Endpoint `/api/create-checkout-session` (Hypothetical) ### Parameters No specific parameters are detailed in the provided code, implying it uses authenticated user context or default plan settings. ### Request Example ```typescript // Initiate Stripe checkout session try { await createCheckoutSession(); // User is automatically redirected to Stripe checkout page } catch (error) { console.error('Checkout failed:', error); alert('Failed to start upgrade process. Please try again.'); } ``` ### Response #### Success Response Upon successful session creation, the user is typically redirected to Stripe's checkout page. The API itself might return a session ID or a redirect URL. #### Handling Redirects - **Success URL**: `https://your-app.com/?payment=success` - **Cancel URL**: `https://your-app.com/` ### Response Example (Client-side Handling) ```javascript // Example of handling the success redirect in the browser useEffect(() => { const urlParams = new URLSearchParams(window.location.search); const paymentSuccess = urlParams.get('payment'); if (paymentSuccess === 'success') { // Clear URL parameters window.history.replaceState({}, document.title, window.location.pathname); // Refresh user profile to get updated Pro status fetchProfile(session.user.id); // Show success message setShowSuccessPage(true); } }, [session]); ``` ``` -------------------------------- ### Manage Leads with Status Updates and Local Storage Persistence (TypeScript) Source: https://context7.com/superbeats1/new-gen/llms.txt This TypeScript code manages saved leads, allowing for saving new leads, updating their status, and deleting them. It utilizes local storage for persistence and includes functions for handling these operations. Dependencies include 'SavedLead' and 'Lead' types, and assume 'savedLeads' and 'setSavedLeads' are state variables. ```typescript import { SavedLead, Lead } from './types'; // Save a new lead const handleSaveLead = (lead: Lead) => { const alreadySaved = savedLeads.find(l => l.id === lead.id); if (alreadySaved) { console.log("Lead already saved"); return; } const newLead: SavedLead = { ...lead, savedDate: new Date().toISOString(), status: 'New' }; const updated = [...savedLeads, newLead]; setSavedLeads(updated); localStorage.setItem('signal_saved_leads', JSON.stringify(updated)); }; // Update lead status const handleUpdateLeadStatus = (id: string, status: 'New' | 'Contacted' | 'In Discussion' | 'Won' | 'Lost') => { const updated = savedLeads.map(lead => lead.id === id ? { ...lead, status } : lead ); setSavedLeads(updated); localStorage.setItem('signal_saved_leads', JSON.stringify(updated)); }; // Delete lead const handleDeleteLead = (id: string) => { const updated = savedLeads.filter(lead => lead.id !== id); setSavedLeads(updated); localStorage.setItem('signal_saved_leads', JSON.stringify(updated)); }; // Load saved leads on app initialization useEffect(() => { const stored = localStorage.getItem('signal_saved_leads'); if (stored) { setSavedLeads(JSON.parse(stored)); } }, []); // Example: Update lead after making contact handleUpdateLeadStatus('lead_001', 'Contacted'); // Example: Mark lead as won after closing deal handleUpdateLeadStatus('lead_001', 'Won'); ``` -------------------------------- ### Smart Text Analysis for Information Extraction Source: https://github.com/superbeats1/new-gen/blob/main/REAL_DATA_INTEGRATION.md Extracts key information such as budget, urgency, location, and contact details from unstructured text data, aiding in lead qualification. ```typescript // Extract key information from posts - Budget: "$5,000" → High budget - Urgency: "ASAP" → High urgency - Location: "NYC" → New York, NY - Contact: Reddit username, GitHub profile ``` -------------------------------- ### Enrich Lead Data with Hunter.io and Pattern Inference (TypeScript) Source: https://context7.com/superbeats1/new-gen/llms.txt Enriches lead data by fetching verified email addresses, company information, and social profiles. It utilizes Hunter.io for direct enrichment and pattern-based inference for email guessing. Dependencies include './services/enrichmentService' and './types'. Inputs are Lead objects, and outputs are EnrichedLead objects or email results. ```typescript import { enrichLead, hunterEnrichEmail, guessEmailFromName } from './services/enrichmentService'; import { Lead, EnrichedLead } from './types'; // Enrich a single lead const lead: Lead = { id: "lead_001", prospectName: "John Smith", username: "@johnsmith", requestSummary: "Need developer for React app at TechCorp startup", postedAt: "3 hours ago", source: "LinkedIn", location: "San Francisco, CA", fitScore: 8, budget: "High", budgetAmount: "$5,000", urgency: "High", contactInfo: "john@techcorp.com", sourceUrl: "https://linkedin.com/posts/activity-12345", status: "New" }; const enrichedLead: EnrichedLead = await enrichLead(lead); console.log(enrichedLead); // { // ...lead, // verifiedEmail: "john.smith@techcorp.com", // emailConfidence: 85, // companyData: { // name: "TechCorp", // domain: "techcorp.com", // website: "https://techcorp.com", // description: "Company based on domain techcorp.com" // }, // socialProfiles: [ // { platform: "LinkedIn", url: "https://linkedin.com/in/johnsmith" }, // { platform: "Twitter", url: "https://twitter.com/johnsmith" }, // { platform: "GitHub", url: "https://github.com/johnsmith" } // ], // lastEnriched: "2025-01-06T10:40:00.000Z" // } // Use Hunter.io API directly (free tier: 25 searches/month) const emailResult = await hunterEnrichEmail("techcorp.com", "John", "Smith"); console.log(emailResult); // { email: "john.smith@techcorp.com", confidence: 92 } // Use free email pattern guessing (no API calls) const emailGuesses = guessEmailFromName("John", "Smith", "techcorp.com"); console.log(emailGuesses); // [ // { email: "john.smith@techcorp.com", confidence: 85 }, // { email: "john@techcorp.com", confidence: 75 }, // { email: "johnsmith@techcorp.com", confidence: 70 } // ] ``` -------------------------------- ### AI Enhancement for Insufficient Data Source: https://github.com/superbeats1/new-gen/blob/main/REAL_DATA_INTEGRATION.md Supplements the collected real data with AI-generated leads if the initial real data count is below a specified threshold (e.g., 3 leads). ```typescript // If insufficient real data, supplement with AI if (realLeads.length < 3) { const aiLeads = await generateSupplementalLeads(query, 3 - realLeads.length); allLeads.push(...aiLeads); } ``` -------------------------------- ### Mode Detection for User Intent Source: https://github.com/superbeats1/new-gen/blob/main/REAL_DATA_INTEGRATION.md Determines the user's intent by analyzing their query, categorizing it into modes like LEAD (client acquisition) or OPPORTUNITY (market analysis). ```typescript // AI determines user intent "Find web developers" → LEAD mode (find clients) "Web development opportunities" → OPPORTUNITY mode (market analysis) ``` -------------------------------- ### Lead Enrichment API Source: https://context7.com/superbeats1/new-gen/llms.txt Enriches lead data with verified email addresses, company information, and social profiles using Hunter.io and pattern-based inference. ```APIDOC ## Lead Enrichment API ### Description Enriches lead data with verified email addresses, company information, and social profiles using Hunter.io and pattern-based inference. ### Method POST (Implied by `enrichLead` function call) ### Endpoint `/api/enrich-lead` (Hypothetical) ### Parameters #### Request Body - **id** (string) - Required - Unique identifier for the lead. - **prospectName** (string) - Required - The name of the prospect. - **username** (string) - Optional - The username or handle of the prospect. - **requestSummary** (string) - Required - A summary of the lead's request or need. - **postedAt** (string) - Required - Timestamp of when the lead was posted. - **source** (string) - Required - The platform or source where the lead was found. - **location** (string) - Optional - The geographical location of the prospect. - **fitScore** (number) - Optional - A score indicating how well the lead fits the criteria. - **budget** (string) - Optional - The budget range for the opportunity. - **budgetAmount** (string) - Optional - The specific budget amount. - **urgency** (string) - Optional - The urgency level of the lead's need. - **contactInfo** (string) - Optional - Initial contact information provided. - **sourceUrl** (string) - Optional - The URL of the original lead source. - **status** (string) - Optional - The current status of the lead. ### Request Example ```json { "id": "lead_001", "prospectName": "John Smith", "username": "@johnsmith", "requestSummary": "Need developer for React app at TechCorp startup", "postedAt": "3 hours ago", "source": "LinkedIn", "location": "San Francisco, CA", "fitScore": 8, "budget": "High", "budgetAmount": "$5,000", "urgency": "High", "contactInfo": "john@techcorp.com", "sourceUrl": "https://linkedin.com/posts/activity-12345", "status": "New" } ``` ### Response #### Success Response (200) - **...lead** (object) - All original lead properties. - **verifiedEmail** (string) - The verified email address of the lead. - **emailConfidence** (number) - The confidence score for the verified email. - **companyData** (object) - Information about the lead's company. - **name** (string) - Company name. - **domain** (string) - Company domain. - **website** (string) - Company website URL. - **description** (string) - A brief description of the company. - **socialProfiles** (array) - A list of social media profiles for the lead. - **platform** (string) - The social media platform (e.g., LinkedIn, Twitter). - **url** (string) - The URL of the social media profile. - **lastEnriched** (string) - ISO 8601 timestamp of when the lead was last enriched. #### Response Example ```json { "id": "lead_001", "prospectName": "John Smith", "username": "@johnsmith", "requestSummary": "Need developer for React app at TechCorp startup", "postedAt": "3 hours ago", "source": "LinkedIn", "location": "San Francisco, CA", "fitScore": 8, "budget": "High", "budgetAmount": "$5,000", "urgency": "High", "contactInfo": "john@techcorp.com", "sourceUrl": "https://linkedin.com/posts/activity-12345", "status": "New", "verifiedEmail": "john.smith@techcorp.com", "emailConfidence": 85, "companyData": { "name": "TechCorp", "domain": "techcorp.com", "website": "https://techcorp.com", "description": "Company based on domain techcorp.com" }, "socialProfiles": [ { "platform": "LinkedIn", "url": "https://linkedin.com/in/johnsmith" }, { "platform": "Twitter", "url": "https://twitter.com/johnsmith" }, { "platform": "GitHub", "url": "https://github.com/johnsmith" } ], "lastEnriched": "2025-01-06T10:40:00.000Z" } ``` ``` -------------------------------- ### Calculating Relevance Fit Score Source: https://github.com/superbeats1/new-gen/blob/main/REAL_DATA_INTEGRATION.md Calculates a smart relevance score for data points against a user's query, considering factors like keyword matches, budget mentions, and urgency indicators. ```typescript // Smart relevance scoring const fitScore = calculateFitScore(text, query); // Factors: keyword match, budget mentions, urgency indicators ``` -------------------------------- ### Stripe Webhook Handler for Supabase Edge Function (TypeScript) Source: https://context7.com/superbeats1/new-gen/llms.txt This TypeScript code defines a Stripe webhook handler for a Supabase Edge Function. It's designed to process 'checkout.session.completed' events to update user subscription status. The handler automatically verifies webhook signatures, finds users by email, and updates their 'is_pro' status. It requires Stripe's webhook URL and secret for configuration. ```typescript // Deployed at: supabase/functions/stripe-webhook/index.ts // Webhook endpoint configuration const WEBHOOK_URL = "https://nogdapsjblqmoicarrbg.supabase.co/functions/v1/stripe-webhook"; const WEBHOOK_SECRET = "whsec_xxxxxxxxxxxxx"; // From Stripe Dashboard // Webhook payload example { "type": "checkout.session.completed", "data": { "object": { "id": "cs_test_xxxxx", "customer": "cus_xxxxx", "customer_email": "user@example.com", "payment_status": "paid", "subscription": "sub_xxxxx" } } } // Server-side processing (automatic) // 1. Verifies webhook signature // 2. Finds user by customer email // 3. Updates profile: is_pro = true // 4. Returns success response // Test webhook locally curl -X POST https://your-app.supabase.co/functions/v1/stripe-webhook \ -H "Content-Type: application/json" \ -H "stripe-signature: t=timestamp,v1=signature" \ -d '{ "type": "checkout.session.completed", "data": { "object": { "customer_email": "test@example.com", "payment_status": "paid" } } }' ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.