fix: add Authorization header to all Edge Function calls + fix Vision Analysis
- All fetch calls to Supabase Edge Functions now include Authorization: Bearer <anon_key> (was missing → 401 errors) - Fix Firecrawl screenshot API: remove invalid screenshotOptions, use "screenshot@fullPage" format (v2 API compatibility) - Fix screenshot response handling: v2 returns URL not base64, now downloads and converts to base64 for Gemini Vision - Add about page to Vision Analysis capture targets - Add retry utility, channel error tracking, pipeline resume, enrichment retry, EmptyState improvements (Sprint 2-3) Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
1 parent
2f2aa5a5b6
commit
79950925a1
12 files changed
+961
-214
No files matched your search
@@ -3,6 +3,7 @@ import { createClient } from "https://esm.sh/@supabase/supabase-js@2";
|
||||
import type { VerifiedChannels } from "../_shared/verifyHandles.ts";
|
||||
import { PERPLEXITY_MODEL } from "../_shared/config.ts";
|
||||
import { captureAllScreenshots, runVisionAnalysis, type ScreenshotResult } from "../_shared/visionAnalysis.ts";
|
||||
import { fetchWithRetry, fetchJsonWithRetry, wrapChannelTask, type ChannelTaskResult } from "../_shared/retry.ts";
|
||||
|
||||
const corsHeaders = {
|
||||
"Access-Control-Allow-Origin": "*",
|
||||
@@ -18,15 +19,20 @@ interface CollectRequest {
|
||||
}
|
||||
|
||||
async function runApifyActor(actorId: string, input: Record<string, unknown>, token: string): Promise<unknown[]> {
|
||||
const res = await fetch(`${APIFY_BASE}/acts/${actorId}/runs?token=${token}&waitForFinish=120`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(input),
|
||||
});
|
||||
const res = await fetchWithRetry(
|
||||
`${APIFY_BASE}/acts/${actorId}/runs?token=${token}&waitForFinish=120`,
|
||||
{ method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(input) },
|
||||
{ maxRetries: 1, timeoutMs: 130000, label: `apify:${actorId.split('~')[1] || actorId}` },
|
||||
);
|
||||
if (!res.ok) throw new Error(`Apify ${actorId} returned ${res.status}`);
|
||||
const run = await res.json();
|
||||
const datasetId = run.data?.defaultDatasetId;
|
||||
if (!datasetId) return [];
|
||||
const itemsRes = await fetch(`${APIFY_BASE}/datasets/${datasetId}/items?token=${token}&limit=20`);
|
||||
if (!datasetId) throw new Error(`Apify ${actorId}: no dataset returned`);
|
||||
const itemsRes = await fetchWithRetry(
|
||||
`${APIFY_BASE}/datasets/${datasetId}/items?token=${token}&limit=20`,
|
||||
undefined,
|
||||
{ maxRetries: 1, timeoutMs: 30000, label: `apify-dataset:${actorId.split('~')[1] || actorId}` },
|
||||
);
|
||||
return itemsRes.json();
|
||||
}
|
||||
|
||||
@@ -74,12 +80,12 @@ Deno.serve(async (req) => {
|
||||
|
||||
const channelData: Record<string, unknown> = {};
|
||||
const analysisData: Record<string, unknown> = {};
|
||||
const tasks: Promise<void>[] = [];
|
||||
const channelTasks: Promise<ChannelTaskResult>[] = [];
|
||||
|
||||
// ─── 1. Instagram (multi-account) — try ALL candidates including unverified ───
|
||||
const igCandidates = (verified.instagram || []).filter((v: Record<string, unknown>) => v.handle);
|
||||
// ─── 1. Instagram (multi-account) — try ALL candidates including unverified/unverifiable ───
|
||||
const igCandidates = (verified.instagram || []).filter((v: Record<string, unknown>) => v.handle && v.verified !== false);
|
||||
if (APIFY_TOKEN && igCandidates.length > 0) {
|
||||
tasks.push((async () => {
|
||||
channelTasks.push(wrapChannelTask("instagram", async () => {
|
||||
const accounts: Record<string, unknown>[] = [];
|
||||
for (const ig of igCandidates) {
|
||||
const items = await runApifyActor("apify~instagram-profile-scraper", { usernames: [ig.handle], resultsLimit: 12 }, APIFY_TOKEN);
|
||||
@@ -104,14 +110,16 @@ Deno.serve(async (req) => {
|
||||
if (accounts.length > 0) {
|
||||
channelData.instagramAccounts = accounts;
|
||||
channelData.instagram = accounts[0];
|
||||
} else {
|
||||
throw new Error("No Instagram profiles found via Apify");
|
||||
}
|
||||
})());
|
||||
}));
|
||||
}
|
||||
|
||||
// ─── 2. YouTube ───
|
||||
const ytVerified = verified.youtube as Record<string, unknown> | null;
|
||||
if (YOUTUBE_API_KEY && ytVerified?.verified) {
|
||||
tasks.push((async () => {
|
||||
if (YOUTUBE_API_KEY && (ytVerified?.verified === true || ytVerified?.verified === "unverifiable")) {
|
||||
channelTasks.push(wrapChannelTask("youtube", async () => {
|
||||
const YT = "https://www.googleapis.com/youtube/v3";
|
||||
let channelId = (ytVerified?.channelId as string) || "";
|
||||
|
||||
@@ -129,24 +137,24 @@ Deno.serve(async (req) => {
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!channelId) return;
|
||||
if (!channelId) throw new Error("Could not resolve YouTube channel ID");
|
||||
|
||||
const chRes = await fetch(`${YT}/channels?part=snippet,statistics,brandingSettings&id=${channelId}&key=${YOUTUBE_API_KEY}`);
|
||||
const chRes = await fetchWithRetry(`${YT}/channels?part=snippet,statistics,brandingSettings&id=${channelId}&key=${YOUTUBE_API_KEY}`, undefined, { label: "youtube-api" });
|
||||
const chData = await chRes.json();
|
||||
const channel = chData.items?.[0];
|
||||
if (!channel) return;
|
||||
if (!channel) throw new Error("YouTube channel not found in API response");
|
||||
|
||||
const stats = channel.statistics || {};
|
||||
const snippet = channel.snippet || {};
|
||||
|
||||
// Popular videos
|
||||
const searchRes = await fetch(`${YT}/search?part=snippet&channelId=${channelId}&order=viewCount&type=video&maxResults=10&key=${YOUTUBE_API_KEY}`);
|
||||
const searchRes = await fetchWithRetry(`${YT}/search?part=snippet&channelId=${channelId}&order=viewCount&type=video&maxResults=10&key=${YOUTUBE_API_KEY}`, undefined, { label: "youtube-search" });
|
||||
const searchData = await searchRes.json();
|
||||
const videoIds = (searchData.items || []).map((i: Record<string, unknown>) => (i.id as Record<string, string>)?.videoId).filter(Boolean).join(",");
|
||||
|
||||
let videos: Record<string, unknown>[] = [];
|
||||
if (videoIds) {
|
||||
const vRes = await fetch(`${YT}/videos?part=snippet,statistics,contentDetails&id=${videoIds}&key=${YOUTUBE_API_KEY}`);
|
||||
const vRes = await fetchWithRetry(`${YT}/videos?part=snippet,statistics,contentDetails&id=${videoIds}&key=${YOUTUBE_API_KEY}`, undefined, { label: "youtube-videos" });
|
||||
const vData = await vRes.json();
|
||||
videos = vData.items || [];
|
||||
}
|
||||
@@ -171,13 +179,13 @@ Deno.serve(async (req) => {
|
||||
};
|
||||
}),
|
||||
};
|
||||
})());
|
||||
}));
|
||||
}
|
||||
|
||||
// ─── 3. Facebook ───
|
||||
const fbVerified = verified.facebook as Record<string, unknown> | null;
|
||||
if (APIFY_TOKEN && fbVerified?.verified) {
|
||||
tasks.push((async () => {
|
||||
if (APIFY_TOKEN && (fbVerified?.verified === true || fbVerified?.verified === "unverifiable")) {
|
||||
channelTasks.push(wrapChannelTask("facebook", async () => {
|
||||
const fbUrl = (fbVerified.url as string) || `https://www.facebook.com/${fbVerified.handle}`;
|
||||
const items = await runApifyActor("apify~facebook-pages-scraper", { startUrls: [{ url: fbUrl }] }, APIFY_TOKEN);
|
||||
const page = (items as Record<string, unknown>[])[0];
|
||||
@@ -189,15 +197,17 @@ Deno.serve(async (req) => {
|
||||
address: page.address, intro: page.intro, rating: page.rating,
|
||||
profilePictureUrl: page.profilePictureUrl,
|
||||
};
|
||||
} else {
|
||||
throw new Error("Facebook page scraper returned no data");
|
||||
}
|
||||
})());
|
||||
}));
|
||||
}
|
||||
|
||||
// ─── 4. 강남언니 ───
|
||||
const guVerified = verified.gangnamUnni as Record<string, unknown> | null;
|
||||
if (FIRECRAWL_API_KEY && guVerified?.verified && guVerified.url) {
|
||||
tasks.push((async () => {
|
||||
const scrapeRes = await fetch("https://api.firecrawl.dev/v1/scrape", {
|
||||
channelTasks.push(wrapChannelTask("gangnamUnni", async () => {
|
||||
const scrapeRes = await fetchWithRetry("https://api.firecrawl.dev/v1/scrape", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json", Authorization: `Bearer ${FIRECRAWL_API_KEY}` },
|
||||
body: JSON.stringify({
|
||||
@@ -217,7 +227,8 @@ Deno.serve(async (req) => {
|
||||
},
|
||||
waitFor: 5000,
|
||||
}),
|
||||
});
|
||||
}, { label: "firecrawl-gangnamunni", timeoutMs: 60000 });
|
||||
if (!scrapeRes.ok) throw new Error(`Firecrawl 강남언니 scrape failed: ${scrapeRes.status}`);
|
||||
const data = await scrapeRes.json();
|
||||
const hospital = data.data?.json;
|
||||
if (hospital?.hospitalName) {
|
||||
@@ -230,22 +241,24 @@ Deno.serve(async (req) => {
|
||||
procedures: hospital.procedures || [], address: hospital.address,
|
||||
badges: hospital.badges || [], sourceUrl: guVerified!.url as string,
|
||||
};
|
||||
} else {
|
||||
throw new Error("강남언니 scrape returned no hospital data");
|
||||
}
|
||||
})());
|
||||
}));
|
||||
}
|
||||
|
||||
// ─── 5. Naver Blog + Place ───
|
||||
if (NAVER_CLIENT_ID && NAVER_CLIENT_SECRET && clinicName) {
|
||||
const naverHeaders = { "X-Naver-Client-Id": NAVER_CLIENT_ID, "X-Naver-Client-Secret": NAVER_CLIENT_SECRET };
|
||||
|
||||
tasks.push((async () => {
|
||||
channelTasks.push(wrapChannelTask("naverBlog", async () => {
|
||||
// Get verified Naver Blog handle from Phase 1 for official blog URL
|
||||
const nbVerified = verified.naverBlog as Record<string, unknown> | null;
|
||||
const officialBlogHandle = nbVerified?.handle ? String(nbVerified.handle) : null;
|
||||
|
||||
const query = encodeURIComponent(`${clinicName} 후기`);
|
||||
const res = await fetch(`https://openapi.naver.com/v1/search/blog.json?query=${query}&display=10&sort=sim`, { headers: naverHeaders });
|
||||
if (!res.ok) return;
|
||||
const res = await fetchWithRetry(`https://openapi.naver.com/v1/search/blog.json?query=${query}&display=10&sort=sim`, { headers: naverHeaders }, { label: "naver-blog" });
|
||||
if (!res.ok) throw new Error(`Naver Blog API returned ${res.status}`);
|
||||
const data = await res.json();
|
||||
channelData.naverBlog = {
|
||||
totalResults: data.total || 0, searchQuery: `${clinicName} 후기`,
|
||||
@@ -259,9 +272,9 @@ Deno.serve(async (req) => {
|
||||
link: item.link, bloggerName: item.bloggername, postDate: item.postdate,
|
||||
})),
|
||||
};
|
||||
})());
|
||||
}));
|
||||
|
||||
tasks.push((async () => {
|
||||
channelTasks.push(wrapChannelTask("naverPlace", async () => {
|
||||
// Try multiple queries to find the correct place (avoid same-name different clinics)
|
||||
const queries = [
|
||||
`${clinicName} 성형외과`,
|
||||
@@ -270,7 +283,7 @@ Deno.serve(async (req) => {
|
||||
];
|
||||
for (const q of queries) {
|
||||
const query = encodeURIComponent(q);
|
||||
const res = await fetch(`https://openapi.naver.com/v1/search/local.json?query=${query}&display=5&sort=comment`, { headers: naverHeaders });
|
||||
const res = await fetchWithRetry(`https://openapi.naver.com/v1/search/local.json?query=${query}&display=5&sort=comment`, { headers: naverHeaders }, { label: "naver-place" });
|
||||
if (!res.ok) continue;
|
||||
const data = await res.json();
|
||||
// Find the best match: prefer category containing 성형 or 피부
|
||||
@@ -291,12 +304,12 @@ Deno.serve(async (req) => {
|
||||
break;
|
||||
}
|
||||
}
|
||||
})());
|
||||
}));
|
||||
}
|
||||
|
||||
// ─── 6. Google Maps ───
|
||||
if (APIFY_TOKEN && clinicName) {
|
||||
tasks.push((async () => {
|
||||
channelTasks.push(wrapChannelTask("googleMaps", async () => {
|
||||
const queries = [`${clinicName} 성형외과`, clinicName, `${clinicName} ${address || "강남"}`];
|
||||
let items: unknown[] = [];
|
||||
for (const q of queries) {
|
||||
@@ -317,13 +330,15 @@ Deno.serve(async (req) => {
|
||||
stars: r.stars, text: r.text, publishedAtDate: r.publishedAtDate,
|
||||
})),
|
||||
};
|
||||
} else {
|
||||
throw new Error("Google Maps: no matching place found");
|
||||
}
|
||||
})());
|
||||
}));
|
||||
}
|
||||
|
||||
// ─── 7. Market Analysis (Perplexity) ───
|
||||
if (PERPLEXITY_API_KEY && services.length > 0) {
|
||||
tasks.push((async () => {
|
||||
channelTasks.push(wrapChannelTask("marketAnalysis", async () => {
|
||||
const queries = [
|
||||
{ id: "competitors", prompt: `${address || "강남"} 근처 ${services.slice(0, 3).join(", ")} 전문 성형외과/피부과 경쟁 병원 5곳을 분석해줘. 각 병원의 이름, 주요 시술, 온라인 평판, 마케팅 채널을 JSON 형식으로 제공해줘.` },
|
||||
{ id: "keywords", prompt: `한국 ${services.slice(0, 3).join(", ")} 관련 검색 키워드 트렌드. 네이버와 구글에서 월간 검색량이 높은 키워드 20개, 경쟁 강도, 추천 롱테일 키워드를 JSON 형식으로 제공해줘.` },
|
||||
@@ -332,7 +347,7 @@ Deno.serve(async (req) => {
|
||||
];
|
||||
|
||||
const results = await Promise.allSettled(queries.map(async q => {
|
||||
const res = await fetch("https://api.perplexity.ai/chat/completions", {
|
||||
const res = await fetchWithRetry("https://api.perplexity.ai/chat/completions", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json", Authorization: `Bearer ${PERPLEXITY_API_KEY}` },
|
||||
body: JSON.stringify({
|
||||
@@ -341,11 +356,12 @@ Deno.serve(async (req) => {
|
||||
{ role: "user", content: q.prompt },
|
||||
], temperature: 0.3,
|
||||
}),
|
||||
});
|
||||
}, { label: `perplexity:${q.id}`, timeoutMs: 60000 });
|
||||
const data = await res.json();
|
||||
return { id: q.id, content: data.choices?.[0]?.message?.content || "", citations: data.citations || [] };
|
||||
}));
|
||||
|
||||
let successCount = 0;
|
||||
for (const r of results) {
|
||||
if (r.status === "fulfilled") {
|
||||
const { id, content, citations } = r.value;
|
||||
@@ -353,9 +369,11 @@ Deno.serve(async (req) => {
|
||||
const jsonMatch = content.match(/```json\n?([\s\S]*?)```/);
|
||||
if (jsonMatch) { try { parsed = JSON.parse(jsonMatch[1]); } catch {} }
|
||||
analysisData[id] = { data: parsed, citations };
|
||||
successCount++;
|
||||
}
|
||||
}
|
||||
})());
|
||||
if (successCount === 0) throw new Error("All Perplexity queries failed");
|
||||
}));
|
||||
}
|
||||
|
||||
// ─── 8. Vision Analysis: Screenshots + Gemini Vision ───
|
||||
@@ -366,7 +384,7 @@ Deno.serve(async (req) => {
|
||||
const mainUrl = row.url || "";
|
||||
const siteMap: string[] = row.scrape_data?.siteMap || [];
|
||||
|
||||
tasks.push((async () => {
|
||||
channelTasks.push(wrapChannelTask("vision", async () => {
|
||||
// Capture screenshots of relevant pages + social channel landings
|
||||
screenshots = await captureAllScreenshots(mainUrl, siteMap, verified, FIRECRAWL_API_KEY);
|
||||
|
||||
@@ -386,17 +404,46 @@ Deno.serve(async (req) => {
|
||||
caption: ss.caption,
|
||||
sourceUrl: ss.sourceUrl,
|
||||
}));
|
||||
})());
|
||||
|
||||
if (screenshots.length === 0) throw new Error("No screenshots captured");
|
||||
}));
|
||||
}
|
||||
|
||||
// ─── Execute all tasks ───
|
||||
await Promise.allSettled(tasks);
|
||||
// ─── Execute all channel tasks ───
|
||||
const taskResults = await Promise.all(channelTasks);
|
||||
|
||||
// ─── Legacy: Save to marketing_reports ───
|
||||
// ─── Build channelErrors from task results ───
|
||||
const channelErrors: Record<string, { error: string; durationMs: number }> = {};
|
||||
let failedCount = 0;
|
||||
let successCount = 0;
|
||||
for (const result of taskResults) {
|
||||
if (result.success) {
|
||||
successCount++;
|
||||
} else {
|
||||
failedCount++;
|
||||
channelErrors[result.channel] = {
|
||||
error: result.error || "Unknown error",
|
||||
durationMs: result.durationMs,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const totalTasks = taskResults.length;
|
||||
const isPartial = failedCount > 0 && successCount > 0;
|
||||
const isFullFailure = failedCount > 0 && successCount === 0;
|
||||
const collectionStatus = isFullFailure ? "collection_failed" : isPartial ? "partial" : "collected";
|
||||
|
||||
console.log(`[collect] ${successCount}/${totalTasks} tasks succeeded. Status: ${collectionStatus}`);
|
||||
if (failedCount > 0) {
|
||||
console.warn(`[collect] Failed channels:`, JSON.stringify(channelErrors));
|
||||
}
|
||||
|
||||
// ─── UNCONDITIONAL Legacy Save: always persist whatever we have ───
|
||||
await supabase.from("marketing_reports").update({
|
||||
channel_data: channelData,
|
||||
analysis_data: { clinicName, services, address, analysis: analysisData, analyzedAt: new Date().toISOString() },
|
||||
status: "collected",
|
||||
channel_errors: channelErrors,
|
||||
status: collectionStatus,
|
||||
updated_at: new Date().toISOString(),
|
||||
}).eq("id", reportId);
|
||||
|
||||
@@ -479,12 +526,13 @@ Deno.serve(async (req) => {
|
||||
);
|
||||
}
|
||||
|
||||
// Update analysis_run
|
||||
// Update analysis_run with status + errors
|
||||
await supabase.from("analysis_runs").update({
|
||||
raw_channel_data: channelData,
|
||||
analysis_data: { clinicName, services, address, analysis: analysisData },
|
||||
vision_analysis: channelData.visionAnalysis || {},
|
||||
status: "collecting",
|
||||
channel_errors: channelErrors,
|
||||
status: collectionStatus,
|
||||
}).eq("id", runId);
|
||||
|
||||
} catch (e) {
|
||||
@@ -493,7 +541,16 @@ Deno.serve(async (req) => {
|
||||
}
|
||||
|
||||
return new Response(
|
||||
JSON.stringify({ success: true, channelData, analysisData, collectedAt: new Date().toISOString() }),
|
||||
JSON.stringify({
|
||||
success: !isFullFailure,
|
||||
status: collectionStatus,
|
||||
channelData,
|
||||
analysisData,
|
||||
channelErrors: Object.keys(channelErrors).length > 0 ? channelErrors : undefined,
|
||||
partialFailure: isPartial,
|
||||
taskSummary: { total: totalTasks, succeeded: successCount, failed: failedCount },
|
||||
collectedAt: new Date().toISOString(),
|
||||
}),
|
||||
{ headers: { ...corsHeaders, "Content-Type": "application/json" } },
|
||||
);
|
||||
} catch (error) {
|
||||
|
||||
Reference in new issue
Block a user