File size: 13,408 Bytes
a74b879 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 | /**
* βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
* MAHRAK GEO PLATFORM β API INTEGRATION
* βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
*
* This file connects the index.html UI with all backend APIs
* Handles: Smart Scan, Audit Form, Dashboard Data
*/
// βββ CONFIG βββ
const API_BASE = 'http://localhost:8001/api'; // Point to backend on port 8001
const API_ENDPOINTS = {
// Analysis & Crawling
jobs: `${API_BASE}/jobs`,
jobResults: (jobId) => `${API_BASE}/jobs/${jobId}/results`,
jobStatus: (jobId) => `${API_BASE}/jobs/${jobId}`,
// Keywords
keywords: (jobId) => `${API_BASE}/jobs/${jobId}/keywords`,
// Tavily Search (for Smart Scan)
tavilySearch: `${API_BASE}/tavily/search`,
// Competitor Intelligence
competitorIntel: `${API_BASE}/competitor/intelligence`,
// Health Check
health: `${API_BASE}/health`,
// Auth
auth: {
login: `${API_BASE}/auth/login`,
register: `${API_BASE}/auth/register`,
me: `${API_BASE}/users/me`,
}
};
// βββ UTILITY: Get Auth Token βββ
function getAuthToken() {
return localStorage.getItem('token') || null;
}
function setAuthToken(token) {
localStorage.setItem('token', token);
}
// βββ UTILITY: API Request Helper βββ
async function apiRequest(endpoint, options = {}) {
const token = getAuthToken();
const headers = {
'Content-Type': 'application/json',
...options.headers,
};
if (token) {
headers['Authorization'] = `Bearer ${token}`;
}
try {
const response = await fetch(endpoint, {
...options,
headers,
});
const data = await response.json();
if (!response.ok) {
console.error(`API Error [${response.status}]:`, data);
throw new Error(data.error || `HTTP ${response.status}`);
}
return data;
} catch (error) {
console.error('API Request Failed:', error);
throw error;
}
}
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// SMART SCAN β Connect to Real Backend
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
async function runSmartScanWithAPI(businessName) {
console.log('π Starting Smart Scan for:', businessName);
try {
// Step 1: Check API Health
console.log('π‘ Checking API health...');
const health = await apiRequest(API_ENDPOINTS.health);
console.log('β API Health:', health);
// Step 2: Run Tavily Search for AI Visibility
console.log('π€ Scanning AI Search Engines...');
const aiSearchResult = await apiRequest(API_ENDPOINTS.tavilySearch, {
method: 'POST',
body: JSON.stringify({
query: `"${businessName}" OR ${businessName} best recommendation`,
max_results: 5,
search_depth: 'advanced'
})
});
console.log('β AI Search Results:', aiSearchResult);
// Step 3: Run Tavily Search for Google Results
console.log('π Scanning Google Search...');
const googleSearchResult = await apiRequest(API_ENDPOINTS.tavilySearch, {
method: 'POST',
body: JSON.stringify({
query: businessName,
max_results: 10,
search_depth: 'basic'
})
});
console.log('β Google Search Results:', googleSearchResult);
// Step 4: Run Tavily Search for Social
console.log('π± Scanning Social Media...');
const socialSearchResult = await apiRequest(API_ENDPOINTS.tavilySearch, {
method: 'POST',
body: JSON.stringify({
query: `${businessName} site:tiktok.com OR site:instagram.com OR site:youtube.com`,
max_results: 5,
search_depth: 'basic'
})
});
console.log('β Social Search Results:', socialSearchResult);
// Step 5: Compile Results
const scanResults = {
businessName,
timestamp: new Date().toISOString(),
engines: {
aiSearch: {
name: 'AI Search (ChatGPT/Gemini/Perplexity)',
results: aiSearchResult.result?.results || [],
score: calculateScore(aiSearchResult.result?.results || []),
status: (aiSearchResult.result?.results || []).length > 0 ? 'found' : 'missing'
},
googleSearch: {
name: 'Google Search',
results: googleSearchResult.result?.results || [],
score: calculateScore(googleSearchResult.result?.results || []),
status: (googleSearchResult.result?.results || []).length > 0 ? 'found' : 'missing'
},
socialSearch: {
name: 'Social Media (TikTok/Instagram/YouTube)',
results: socialSearchResult.result?.results || [],
score: calculateScore(socialSearchResult.result?.results || []),
status: (socialSearchResult.result?.results || []).length > 0 ? 'found' : 'missing'
}
}
};
console.log('β Scan Complete:', scanResults);
return scanResults;
} catch (error) {
console.error('β Smart Scan Failed:', error);
throw error;
}
}
function calculateScore(results) {
if (!results || results.length === 0) return 0;
// Score based on number of results and relevance
return Math.min(100, results.length * 15);
}
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// AUDIT FORM β Connect to Analysis System
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
async function submitAuditForm(formData) {
console.log('π Submitting Audit Form:', formData);
try {
// Step 1: Create a new job/analysis
console.log('π Creating analysis job...');
const jobResponse = await apiRequest(API_ENDPOINTS.jobs, {
method: 'POST',
body: JSON.stringify({
url: formData.website,
org_name: formData.businessName,
org_url: formData.website,
max_pages: 10,
runs: 1,
metadata: {
contactName: formData.name,
contactEmail: formData.email,
contactPhone: formData.phone,
sector: formData.sector
}
})
});
if (!jobResponse.ok) {
throw new Error(jobResponse.error || 'Failed to create job');
}
const jobId = jobResponse.job_id;
console.log('β Job Created:', jobId);
// Step 2: Poll for job completion
console.log('β³ Waiting for analysis to complete...');
const analysisResult = await pollJobCompletion(jobId);
console.log('β Analysis Complete:', analysisResult);
// Step 3: Get detailed results
console.log('π Fetching detailed results...');
const detailedResults = await apiRequest(API_ENDPOINTS.jobResults(jobId));
console.log('β Detailed Results:', detailedResults);
return {
jobId,
formData,
analysisResult,
detailedResults
};
} catch (error) {
console.error('β Audit Form Submission Failed:', error);
throw error;
}
}
async function pollJobCompletion(jobId, maxAttempts = 40, interval = 3000) {
let attempts = 0;
return new Promise((resolve, reject) => {
const poll = async () => {
try {
const jobStatus = await apiRequest(API_ENDPOINTS.jobStatus(jobId));
console.log(`[Attempt ${attempts + 1}/${maxAttempts}] Job Status:`, jobStatus.status);
if (jobStatus.status === 'completed') {
resolve(jobStatus);
} else if (jobStatus.status === 'failed') {
reject(new Error('Job failed: ' + (jobStatus.error || 'Unknown error')));
} else if (attempts >= maxAttempts) {
reject(new Error('Job polling timeout'));
} else {
attempts++;
setTimeout(poll, interval);
}
} catch (error) {
reject(error);
}
};
poll();
});
}
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// DASHBOARD DATA β Load Real Data
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
async function loadDashboardData() {
console.log('π Loading Dashboard Data...');
try {
// Get all jobs
const jobsResponse = await apiRequest(API_ENDPOINTS.jobs);
const jobs = jobsResponse.jobs || [];
console.log('β Jobs Loaded:', jobs.length);
// Get latest completed job
const completedJobs = jobs.filter(j => j.status === 'completed');
if (completedJobs.length === 0) {
console.warn('β οΈ No completed jobs found');
return null;
}
const latestJob = completedJobs[completedJobs.length - 1];
console.log('β Latest Job:', latestJob.id);
// Get job results
const results = await apiRequest(API_ENDPOINTS.jobResults(latestJob.id));
console.log('β Job Results:', results);
// Get keywords
const keywords = await apiRequest(API_ENDPOINTS.keywords(latestJob.id));
console.log('β Keywords:', keywords);
return {
job: latestJob,
results,
keywords
};
} catch (error) {
console.error('β Dashboard Data Load Failed:', error);
return null;
}
}
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// COMPETITOR INTELLIGENCE
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
async function getCompetitorIntelligence(url, industry) {
console.log('π₯ Fetching Competitor Intelligence...');
try {
const result = await apiRequest(API_ENDPOINTS.competitorIntel, {
method: 'POST',
body: JSON.stringify({
url,
industry,
count: 5
})
});
console.log('β Competitor Intelligence:', result);
return result;
} catch (error) {
console.error('β Competitor Intelligence Failed:', error);
return null;
}
}
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// HEALTH CHECK β Test All Connections
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
async function testAllConnections() {
console.log('π Testing All API Connections...');
const results = {
timestamp: new Date().toISOString(),
endpoints: {}
};
// Test Health
try {
const health = await apiRequest(API_ENDPOINTS.health);
results.endpoints.health = { status: 'ok', data: health };
console.log('β Health:', health);
} catch (error) {
results.endpoints.health = { status: 'error', error: error.message };
console.error('β Health:', error.message);
}
// Test Auth (if token exists)
const token = getAuthToken();
if (token) {
try {
const me = await apiRequest(API_ENDPOINTS.auth.me);
results.endpoints.auth = { status: 'ok', data: me };
console.log('β Auth:', me);
} catch (error) {
results.endpoints.auth = { status: 'error', error: error.message };
console.error('β Auth:', error.message);
}
}
// Test Jobs
try {
const jobs = await apiRequest(API_ENDPOINTS.jobs);
results.endpoints.jobs = { status: 'ok', count: (jobs.jobs || []).length };
console.log('β Jobs:', jobs.jobs?.length || 0);
} catch (error) {
results.endpoints.jobs = { status: 'error', error: error.message };
console.error('β Jobs:', error.message);
}
console.log('π Connection Test Results:', results);
return results;
}
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// EXPORT FOR USE IN HTML
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
window.MahrakAPI = {
runSmartScanWithAPI,
submitAuditForm,
loadDashboardData,
getCompetitorIntelligence,
testAllConnections,
apiRequest,
getAuthToken,
setAuthToken,
API_ENDPOINTS
};
console.log('β Mahrak API Integration Loaded');
|