feat: add API Dashboard + filled icons + pipeline improvements
- Add /api-dashboard page with API connection status, env var checker, pipeline flow diagram, and cost estimator - Add 15 new filled SVG icons (Shield, Database, Server, Bolt, Eye, Copy, Check, Cross, Warning, Refresh, Flow, Coin, LinkExternal etc.) - Follow INFINITH design system: no emoji, no line icons, semantic status colors, diagonal shadows, brand gradients, font-serif headings - Improve Vision Analysis with base64 encoding fix - Add SectionErrorBoundary for graceful section-level error handling - Add Google Places API utility (prepared for future migration) - Fix Edge Function auth headers and report generation pipeline Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
2ca9ec0306
commit
ec991057e6
20 files changed
+1397
-109
No files matched your search
@@ -0,0 +1,212 @@
|
||||
/**
|
||||
* Google Places API (New) — Direct REST client.
|
||||
*
|
||||
* Replaces Apify `compass~crawler-google-places` actor with official API.
|
||||
* Benefits: 1-2s latency (vs 30-120s), stable contract, ToS compliant.
|
||||
*
|
||||
* API docs: https://developers.google.com/maps/documentation/places/web-service/op-overview
|
||||
*
|
||||
* Pricing (per 1K calls):
|
||||
* - Text Search (Basic): $32 → but we use field mask to reduce
|
||||
* - Place Details (Basic): $0 (id-only fields)
|
||||
* - Place Details (Contact): $3 (phone, website)
|
||||
* - Place Details (Atmos): $5 (reviews, rating)
|
||||
*
|
||||
* Typical cost per clinic: ~$0.04 (1 Text Search + 1 Details)
|
||||
*/
|
||||
|
||||
import { fetchWithRetry } from "./retry.ts";
|
||||
|
||||
// ─── Types ───
|
||||
|
||||
export interface GooglePlaceResult {
|
||||
name: string; // e.g. "뷰성형외과의원"
|
||||
rating: number | null; // e.g. 4.3
|
||||
reviewCount: number; // e.g. 387
|
||||
address: string; // formatted address
|
||||
phone: string; // international format
|
||||
clinicWebsite: string; // clinic's own website
|
||||
mapsUrl: string; // Google Maps URL
|
||||
category: string; // primary type
|
||||
placeId: string; // for future lookups
|
||||
openingHours: Record<string, unknown> | null;
|
||||
topReviews: {
|
||||
stars: number;
|
||||
text: string;
|
||||
publishedAtDate: string;
|
||||
}[];
|
||||
}
|
||||
|
||||
// ─── Constants ───
|
||||
|
||||
const PLACES_BASE = "https://places.googleapis.com/v1";
|
||||
|
||||
// Fields we need from Text Search (covers Basic + Contact + Atmosphere tiers)
|
||||
const TEXT_SEARCH_FIELDS = [
|
||||
"places.id",
|
||||
"places.displayName",
|
||||
"places.formattedAddress",
|
||||
"places.rating",
|
||||
"places.userRatingCount",
|
||||
"places.nationalPhoneNumber",
|
||||
"places.internationalPhoneNumber",
|
||||
"places.websiteUri",
|
||||
"places.googleMapsUri",
|
||||
"places.primaryType",
|
||||
"places.primaryTypeDisplayName",
|
||||
"places.regularOpeningHours",
|
||||
"places.reviews",
|
||||
].join(",");
|
||||
|
||||
// ─── Main Function ───
|
||||
|
||||
/**
|
||||
* Search for a clinic on Google Places and return structured data.
|
||||
* Tries multiple queries in order until a match is found.
|
||||
*/
|
||||
export async function searchGooglePlace(
|
||||
clinicName: string,
|
||||
address: string | undefined,
|
||||
apiKey: string,
|
||||
): Promise<GooglePlaceResult | null> {
|
||||
const queries = [
|
||||
`${clinicName} 성형외과`,
|
||||
clinicName,
|
||||
`${clinicName} ${address || "강남"}`,
|
||||
];
|
||||
|
||||
for (const query of queries) {
|
||||
const result = await textSearch(query, apiKey);
|
||||
if (result) return result;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Google Places Text Search (New) API call.
|
||||
* Returns the first matching place with full details in a single call.
|
||||
*/
|
||||
async function textSearch(
|
||||
query: string,
|
||||
apiKey: string,
|
||||
): Promise<GooglePlaceResult | null> {
|
||||
const res = await fetchWithRetry(
|
||||
`${PLACES_BASE}/places:searchText`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"X-Goog-Api-Key": apiKey,
|
||||
"X-Goog-FieldMask": TEXT_SEARCH_FIELDS,
|
||||
},
|
||||
body: JSON.stringify({
|
||||
textQuery: query,
|
||||
languageCode: "ko",
|
||||
regionCode: "KR",
|
||||
maxResultCount: 3,
|
||||
}),
|
||||
},
|
||||
{
|
||||
maxRetries: 1,
|
||||
timeoutMs: 15000,
|
||||
label: `google-places:textSearch`,
|
||||
},
|
||||
);
|
||||
|
||||
if (!res.ok) {
|
||||
const errText = await res.text().catch(() => "");
|
||||
throw new Error(`Google Places Text Search ${res.status}: ${errText}`);
|
||||
}
|
||||
|
||||
const data = await res.json();
|
||||
const places = data.places as Record<string, unknown>[] | undefined;
|
||||
|
||||
if (!places || places.length === 0) return null;
|
||||
|
||||
// Use first result (most relevant)
|
||||
return mapPlaceToResult(places[0]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Map Google Places API response to our internal structure.
|
||||
* Maintains the same field names as the old Apify-based structure
|
||||
* for backward compatibility with transformReport.ts and UI components.
|
||||
*/
|
||||
function mapPlaceToResult(place: Record<string, unknown>): GooglePlaceResult {
|
||||
const displayName = place.displayName as Record<string, unknown> | undefined;
|
||||
const openingHours = place.regularOpeningHours as Record<string, unknown> | null;
|
||||
const reviews = (place.reviews as Record<string, unknown>[]) || [];
|
||||
const primaryTypeDisplay = place.primaryTypeDisplayName as Record<string, unknown> | undefined;
|
||||
|
||||
return {
|
||||
name: (displayName?.text as string) || "",
|
||||
rating: (place.rating as number) || null,
|
||||
reviewCount: (place.userRatingCount as number) || 0,
|
||||
address: (place.formattedAddress as string) || "",
|
||||
phone: (place.internationalPhoneNumber as string) || (place.nationalPhoneNumber as string) || "",
|
||||
clinicWebsite: (place.websiteUri as string) || "",
|
||||
mapsUrl: (place.googleMapsUri as string) || "",
|
||||
category: (primaryTypeDisplay?.text as string) || (place.primaryType as string) || "",
|
||||
placeId: (place.id as string) || "",
|
||||
openingHours: openingHours,
|
||||
topReviews: reviews.slice(0, 10).map((r) => {
|
||||
const authorAttribution = r.authorAttribution as Record<string, unknown> | undefined;
|
||||
const publishTime = r.publishTime as string || "";
|
||||
return {
|
||||
stars: (r.rating as number) || 0,
|
||||
text: ((r.text as Record<string, unknown>)?.text as string || "").slice(0, 500),
|
||||
publishedAtDate: publishTime,
|
||||
};
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Get Place Details by Place ID — for future use when we have cached placeIds
|
||||
* in the clinic_registry table. Cheaper than Text Search.
|
||||
*/
|
||||
export async function getPlaceDetails(
|
||||
placeId: string,
|
||||
apiKey: string,
|
||||
): Promise<GooglePlaceResult | null> {
|
||||
const fieldMask = [
|
||||
"id",
|
||||
"displayName",
|
||||
"formattedAddress",
|
||||
"rating",
|
||||
"userRatingCount",
|
||||
"nationalPhoneNumber",
|
||||
"internationalPhoneNumber",
|
||||
"websiteUri",
|
||||
"googleMapsUri",
|
||||
"primaryType",
|
||||
"primaryTypeDisplayName",
|
||||
"regularOpeningHours",
|
||||
"reviews",
|
||||
].join(",");
|
||||
|
||||
const res = await fetchWithRetry(
|
||||
`${PLACES_BASE}/places/${placeId}`,
|
||||
{
|
||||
method: "GET",
|
||||
headers: {
|
||||
"X-Goog-Api-Key": apiKey,
|
||||
"X-Goog-FieldMask": fieldMask,
|
||||
},
|
||||
},
|
||||
{
|
||||
maxRetries: 1,
|
||||
timeoutMs: 10000,
|
||||
label: `google-places:details`,
|
||||
},
|
||||
);
|
||||
|
||||
if (!res.ok) {
|
||||
const errText = await res.text().catch(() => "");
|
||||
throw new Error(`Google Places Details ${res.status}: ${errText}`);
|
||||
}
|
||||
|
||||
const place = await res.json();
|
||||
return mapPlaceToResult(place as Record<string, unknown>);
|
||||
}
|
||||
@@ -131,29 +131,46 @@ export function findRelevantPages(
|
||||
): { doctorPage?: string; surgeryPage?: string; aboutPage?: string } {
|
||||
const result: { doctorPage?: string; surgeryPage?: string; aboutPage?: string } = {};
|
||||
|
||||
// Phase 1: Classify each URL into one category (doctor > surgery > about priority)
|
||||
const doctorUrls: string[] = [];
|
||||
const surgeryUrls: string[] = [];
|
||||
const aboutUrls: string[] = [];
|
||||
|
||||
for (const url of siteMap) {
|
||||
const lower = url.toLowerCase();
|
||||
if (!result.doctorPage && (
|
||||
lower.includes('/doctor') || lower.includes('/team') || lower.includes('/staff') ||
|
||||
|
||||
const isDoctor = (
|
||||
lower.includes('/doctor') || lower.includes('/doctors') ||
|
||||
lower.includes('/team') || lower.includes('/staff') ||
|
||||
lower.includes('/specialist') || lower.includes('/professor') ||
|
||||
lower.includes('/의료진') || lower.includes('/원장')
|
||||
)) {
|
||||
result.doctorPage = url;
|
||||
}
|
||||
if (!result.surgeryPage && (
|
||||
lower.includes('/의료진') || lower.includes('/원장') ||
|
||||
lower.includes('meet-our-doctor') // 하이픈 패턴 (그랜드성형외과 등)
|
||||
);
|
||||
const isSurgery = (
|
||||
lower.includes('/surgery') || lower.includes('/service') || lower.includes('/procedure') ||
|
||||
lower.includes('/treatment') || lower.includes('/시술') || lower.includes('/수술')
|
||||
)) {
|
||||
result.surgeryPage = url;
|
||||
}
|
||||
if (!result.aboutPage && (
|
||||
);
|
||||
const isAbout = (
|
||||
lower.includes('/about') || lower.includes('/intro') || lower.includes('/소개') ||
|
||||
lower.includes('/greeting')
|
||||
)) {
|
||||
result.aboutPage = url;
|
||||
lower.includes('/greeting') || lower.includes('/인사말') || lower.includes('/history') ||
|
||||
lower.includes('/연혁')
|
||||
);
|
||||
|
||||
// Priority: specific page type > generic /about
|
||||
if (isDoctor) {
|
||||
doctorUrls.push(url);
|
||||
} else if (isSurgery) {
|
||||
surgeryUrls.push(url);
|
||||
} else if (isAbout) {
|
||||
aboutUrls.push(url);
|
||||
}
|
||||
}
|
||||
|
||||
// Phase 2: Pick best URL per category
|
||||
result.doctorPage = doctorUrls[0];
|
||||
result.surgeryPage = surgeryUrls[0];
|
||||
result.aboutPage = aboutUrls[0];
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -205,13 +222,72 @@ export async function captureAllScreenshots(
|
||||
}
|
||||
}
|
||||
|
||||
// Instagram EN (두 번째 계정이 있는 경우)
|
||||
if (igList.length > 1) {
|
||||
const igEn = igList[1];
|
||||
const handleEn = (igEn.handle as string || '').replace(/^@/, '');
|
||||
if (handleEn) {
|
||||
captureTargets.push({ id: 'instagram-en', url: `https://www.instagram.com/${handleEn}/`, channel: 'Instagram', caption: `Instagram @${handleEn} (EN)` });
|
||||
}
|
||||
}
|
||||
|
||||
// Facebook
|
||||
const fb = verifiedChannels.facebook as Record<string, unknown> | null;
|
||||
if (fb?.verified || fb?.verified === 'unverifiable') {
|
||||
const fbUrl = (fb.url as string) || `https://www.facebook.com/${fb.handle}`;
|
||||
captureTargets.push({ id: 'facebook-page', url: fbUrl, channel: 'Facebook', caption: 'Facebook 페이지' });
|
||||
}
|
||||
|
||||
// TikTok
|
||||
const tt = verifiedChannels.tiktok as Record<string, unknown> | null;
|
||||
if (tt?.handle) {
|
||||
const ttHandle = (tt.handle as string).replace(/^@/, '');
|
||||
captureTargets.push({ id: 'tiktok-landing', url: `https://www.tiktok.com/@${ttHandle}`, channel: 'TikTok', caption: `TikTok @${ttHandle}` });
|
||||
}
|
||||
|
||||
// 강남언니
|
||||
const gu = verifiedChannels.gangnamUnni as Record<string, unknown> | null;
|
||||
if (gu?.url) {
|
||||
captureTargets.push({ id: 'gangnamunni-page', url: gu.url as string, channel: '강남언니', caption: '강남언니 병원 페이지' });
|
||||
}
|
||||
|
||||
// Capture all in parallel (max 6 concurrent)
|
||||
// 네이버 블로그
|
||||
const nb = verifiedChannels.naverBlog as Record<string, unknown> | null;
|
||||
if (nb?.handle) {
|
||||
captureTargets.push({ id: 'naver-blog', url: `https://blog.naver.com/${nb.handle}`, channel: '네이버 블로그', caption: '공식 네이버 블로그' });
|
||||
}
|
||||
|
||||
// 네이버 플레이스
|
||||
const np = verifiedChannels.naverPlace as Record<string, unknown> | null;
|
||||
if (np?.url) {
|
||||
captureTargets.push({ id: 'naver-place', url: np.url as string, channel: '네이버 플레이스', caption: '네이버 플레이스' });
|
||||
}
|
||||
|
||||
// Google Maps
|
||||
const gm = verifiedChannels.googleMaps as Record<string, unknown> | null;
|
||||
if (gm?.url) {
|
||||
captureTargets.push({ id: 'google-maps', url: gm.url as string, channel: 'Google Maps', caption: 'Google Maps' });
|
||||
}
|
||||
|
||||
// 전후사진/갤러리 페이지 (siteMap에서 탐색)
|
||||
const galleryPage = siteMap.find(u => {
|
||||
const l = u.toLowerCase();
|
||||
return l.includes('/gallery') || l.includes('/before') || l.includes('/전후')
|
||||
|| l.includes('/photos') || l.includes('/case') || l.includes('/사례');
|
||||
});
|
||||
if (galleryPage) {
|
||||
captureTargets.push({ id: 'website-gallery', url: galleryPage, channel: '웹사이트', caption: '전후사진/갤러리' });
|
||||
}
|
||||
|
||||
// 영문 웹사이트
|
||||
const enSite = verifiedChannels.websiteEn as string | null;
|
||||
if (enSite) {
|
||||
captureTargets.push({ id: 'website-en', url: enSite, channel: '웹사이트(EN)', caption: '영문 웹사이트' });
|
||||
}
|
||||
|
||||
console.log(`[vision] Capture targets: ${captureTargets.length} pages (${captureTargets.map(t => t.id).join(', ')})`);
|
||||
|
||||
// Capture all in parallel
|
||||
const capturePromises = captureTargets.map(async (target) => {
|
||||
const result = await captureScreenshot(target.url, firecrawlKey);
|
||||
if (result) {
|
||||
@@ -248,7 +324,11 @@ export async function analyzeScreenshot(
|
||||
"SINCE 2004" → 2004
|
||||
"20년 전통" → 2026 - 20 = 2006
|
||||
"개원 15주년" → 2026 - 15 = 2011
|
||||
배너, 이벤트 팝업, 로고 옆 텍스트, 하단 footer 등 모든 곳을 확인해줘.
|
||||
"2004년개원" → 2004
|
||||
"2004년 개원" → 2004
|
||||
"2004년개원 이래" → 2004
|
||||
"설립 2004년" → 2004
|
||||
배너, 이벤트 팝업, 로고 옆 텍스트, 하단 footer, 원장 인사말, 병원 소개 섹션 등 페이지 전체를 꼼꼼히 확인해줘. 특히 스크롤 아래쪽도 확인할 것!
|
||||
- operationYears: 운영 기간 (숫자만. "22주년"이면 22)
|
||||
- certifications: 인증 마크 (JCI, 보건복지부, 의료관광 등)
|
||||
- socialIcons: 보이는 소셜 미디어 아이콘 (Instagram, YouTube, Facebook, Blog, KakaoTalk 등)
|
||||
@@ -268,6 +348,9 @@ export async function analyzeScreenshot(
|
||||
"22년 동안" → 2026 - 22 = 2004
|
||||
"SINCE 2004" → 2004
|
||||
"2004년 개원" → 2004
|
||||
"2004년개원" → 2004
|
||||
"2004년개원 이래" → 2004
|
||||
"설립 2004년" → 2004
|
||||
"20년 전통" → 2026 - 20 = 2006
|
||||
연혁, 소개글, 대표원장 인사말 등 모든 텍스트를 꼼꼼히 확인해줘.
|
||||
- operationYears: 운영 기간 (숫자만)
|
||||
@@ -288,6 +371,30 @@ export async function analyzeScreenshot(
|
||||
'gangnamunni-page': `이 강남언니 병원 페이지를 분석해줘. JSON으로 추출:
|
||||
- gangnamUnniStats: {rating: "평점 텍스트", reviews: "리뷰 수 텍스트", doctors: 의사 수(숫자)}
|
||||
- doctors: [{name: "이름", specialty: "전문 분야"}] (보이는 의사 정보)`,
|
||||
|
||||
'facebook-page': `이 Facebook 페이지 스크린샷을 분석해줘. JSON으로 추출:
|
||||
- facebookStats: {followers: "팔로워 수 텍스트", likes: "좋아요 수 텍스트", rating: "평점 (있으면)", category: "카테고리", recentPost: "최근 게시물 요약"}`,
|
||||
|
||||
'tiktok-landing': `이 TikTok 프로필 스크린샷을 분석해줘. JSON으로 추출:
|
||||
- tiktokStats: {followers: "팔로워 수", likes: "총 좋아요 수", videos: "영상 수", bio: "바이오 텍스트", recentVideo: "최근 영상 설명"}`,
|
||||
|
||||
'naver-blog': `이 네이버 블로그 스크린샷을 분석해줘. JSON으로 추출:
|
||||
- naverBlogStats: {neighbors: "이웃 수 텍스트", visitors: "방문자 수 텍스트 (있으면)", recentTitle: "최근 글 제목", blogName: "블로그 이름"}`,
|
||||
|
||||
'naver-place': `이 네이버 플레이스 페이지를 분석해줘. JSON으로 추출:
|
||||
- naverPlaceStats: {rating: "별점", reviews: "리뷰 수", visitorReviews: "방문자 리뷰 수", address: "주소", hours: "영업시간", category: "카테고리"}`,
|
||||
|
||||
'google-maps': `이 Google Maps 페이지를 분석해줘. JSON으로 추출:
|
||||
- googleMapsStats: {rating: "별점", reviews: "리뷰 수", address: "주소", hours: "영업시간 (있으면)", photos: "사진 수 (있으면)"}`,
|
||||
|
||||
'website-gallery': `이 성형외과 전후사진/갤러리 페이지를 분석해줘. JSON으로 추출:
|
||||
- galleryStats: {estimatedPhotoCount: 추정 사진 수(숫자), categories: ["보이는 시술 카테고리 목록"]}`,
|
||||
|
||||
'website-en': `Analyze this English version of a Korean plastic surgery clinic website. Extract JSON:
|
||||
- enSiteStats: {languages: ["supported languages visible"], targetMarkets: ["target countries/regions mentioned"], keyServices: ["listed services in English"]}`,
|
||||
|
||||
'instagram-en': `이 Instagram 프로필(글로벌/영문 계정)을 분석해줘. JSON으로 추출:
|
||||
- instagramEnStats: {followers: "팔로워 수 텍스트", posts: "게시물 수 텍스트", bio: "바이오 텍스트", language: "주 사용 언어"}`,
|
||||
};
|
||||
|
||||
const prompt = prompts[pageType] || `이 웹페이지 스크린샷을 분석해줘. 보이는 모든 텍스트와 정보를 JSON으로 추출해줘.`;
|
||||
|
||||
@@ -4,6 +4,7 @@ import type { VerifiedChannels } from "../_shared/verifyHandles.ts";
|
||||
import { PERPLEXITY_MODEL } from "../_shared/config.ts";
|
||||
import { captureAllScreenshots, runVisionAnalysis, screenshotErrors, type ScreenshotResult } from "../_shared/visionAnalysis.ts";
|
||||
import { fetchWithRetry, fetchJsonWithRetry, wrapChannelTask, type ChannelTaskResult } from "../_shared/retry.ts";
|
||||
import { searchGooglePlace } from "../_shared/googlePlaces.ts";
|
||||
|
||||
const corsHeaders = {
|
||||
"Access-Control-Allow-Origin": "*",
|
||||
@@ -77,6 +78,7 @@ Deno.serve(async (req) => {
|
||||
const PERPLEXITY_API_KEY = Deno.env.get("PERPLEXITY_API_KEY") || "";
|
||||
const NAVER_CLIENT_ID = Deno.env.get("NAVER_CLIENT_ID") || "";
|
||||
const NAVER_CLIENT_SECRET = Deno.env.get("NAVER_CLIENT_SECRET") || "";
|
||||
const GOOGLE_PLACES_API_KEY = Deno.env.get("GOOGLE_PLACES_API_KEY") || "";
|
||||
|
||||
const channelData: Record<string, unknown> = {};
|
||||
const analysisData: Record<string, unknown> = {};
|
||||
@@ -116,6 +118,74 @@ Deno.serve(async (req) => {
|
||||
}));
|
||||
}
|
||||
|
||||
// ─── 1b. Instagram Posts (최근 20개 포스트 상세) ───
|
||||
const igPrimaryHandle = igCandidates[0]?.handle as string | undefined;
|
||||
if (APIFY_TOKEN && igPrimaryHandle) {
|
||||
channelTasks.push(wrapChannelTask("instagramPosts", async () => {
|
||||
const handle = igPrimaryHandle.replace(/^@/, '');
|
||||
const items = await runApifyActor(
|
||||
"apify~instagram-post-scraper",
|
||||
{ directUrls: [`https://www.instagram.com/${handle}/`], resultsLimit: 20 },
|
||||
APIFY_TOKEN,
|
||||
);
|
||||
const posts = (items as Record<string, unknown>[]).map(p => ({
|
||||
id: p.id,
|
||||
type: p.type,
|
||||
shortCode: p.shortCode,
|
||||
url: p.url,
|
||||
caption: ((p.caption as string) || '').slice(0, 500),
|
||||
hashtags: p.hashtags || [],
|
||||
mentions: p.mentions || [],
|
||||
likesCount: (p.likesCount as number) || 0,
|
||||
commentsCount: (p.commentsCount as number) || 0,
|
||||
timestamp: p.timestamp,
|
||||
displayUrl: p.displayUrl,
|
||||
}));
|
||||
const totalLikes = posts.reduce((sum, p) => sum + p.likesCount, 0);
|
||||
const totalComments = posts.reduce((sum, p) => sum + p.commentsCount, 0);
|
||||
channelData.instagramPosts = {
|
||||
posts,
|
||||
totalPosts: posts.length,
|
||||
avgLikes: posts.length > 0 ? Math.round(totalLikes / posts.length) : 0,
|
||||
avgComments: posts.length > 0 ? Math.round(totalComments / posts.length) : 0,
|
||||
};
|
||||
}));
|
||||
}
|
||||
|
||||
// ─── 1c. Instagram Reels (최근 15개 릴스 상세) ───
|
||||
if (APIFY_TOKEN && igPrimaryHandle) {
|
||||
channelTasks.push(wrapChannelTask("instagramReels", async () => {
|
||||
const handle = igPrimaryHandle.replace(/^@/, '');
|
||||
const items = await runApifyActor(
|
||||
"apify~instagram-reel-scraper",
|
||||
{ directUrls: [`https://www.instagram.com/${handle}/reels/`], resultsLimit: 15 },
|
||||
APIFY_TOKEN,
|
||||
);
|
||||
const reels = (items as Record<string, unknown>[]).map(r => ({
|
||||
id: r.id,
|
||||
shortCode: r.shortCode,
|
||||
url: r.url,
|
||||
caption: ((r.caption as string) || '').slice(0, 500),
|
||||
hashtags: r.hashtags || [],
|
||||
likesCount: (r.likesCount as number) || 0,
|
||||
commentsCount: (r.commentsCount as number) || 0,
|
||||
videoViewCount: (r.videoViewCount as number) || 0,
|
||||
videoPlayCount: (r.videoPlayCount as number) || 0,
|
||||
videoDuration: (r.videoDuration as number) || 0,
|
||||
timestamp: r.timestamp,
|
||||
musicInfo: r.musicInfo || null,
|
||||
}));
|
||||
const totalViews = reels.reduce((sum, r) => sum + r.videoViewCount, 0);
|
||||
const totalPlays = reels.reduce((sum, r) => sum + r.videoPlayCount, 0);
|
||||
channelData.instagramReels = {
|
||||
reels,
|
||||
totalReels: reels.length,
|
||||
avgViews: reels.length > 0 ? Math.round(totalViews / reels.length) : 0,
|
||||
avgPlays: reels.length > 0 ? Math.round(totalPlays / reels.length) : 0,
|
||||
};
|
||||
}));
|
||||
}
|
||||
|
||||
// ─── 2. YouTube ───
|
||||
const ytVerified = verified.youtube as Record<string, unknown> | null;
|
||||
if (YOUTUBE_API_KEY && (ytVerified?.verified === true || ytVerified?.verified === "unverifiable")) {
|
||||
@@ -307,28 +377,19 @@ Deno.serve(async (req) => {
|
||||
}));
|
||||
}
|
||||
|
||||
// ─── 6. Google Maps ───
|
||||
if (APIFY_TOKEN && clinicName) {
|
||||
// ─── 6. Google Maps (Google Places API New) ───
|
||||
if (GOOGLE_PLACES_API_KEY && clinicName) {
|
||||
channelTasks.push(wrapChannelTask("googleMaps", async () => {
|
||||
const queries = [`${clinicName} 성형외과`, clinicName, `${clinicName} ${address || "강남"}`];
|
||||
let items: unknown[] = [];
|
||||
for (const q of queries) {
|
||||
items = await runApifyActor("compass~crawler-google-places", {
|
||||
searchStringsArray: [q], maxCrawledPlacesPerSearch: 3, language: "ko", maxReviews: 10,
|
||||
}, APIFY_TOKEN);
|
||||
if ((items as Record<string, unknown>[]).length > 0) break;
|
||||
}
|
||||
const place = (items as Record<string, unknown>[])[0];
|
||||
const place = await searchGooglePlace(clinicName, address || undefined, GOOGLE_PLACES_API_KEY);
|
||||
if (place) {
|
||||
channelData.googleMaps = {
|
||||
name: place.title, rating: place.totalScore, reviewCount: place.reviewsCount,
|
||||
name: place.name, rating: place.rating, reviewCount: place.reviewCount,
|
||||
address: place.address, phone: place.phone,
|
||||
clinicWebsite: place.website, // clinic's own website (not Maps URL)
|
||||
mapsUrl: place.url || (place.title ? `https://www.google.com/maps/search/${encodeURIComponent(String(place.title))}` : ''),
|
||||
category: place.categoryName, openingHours: place.openingHours,
|
||||
topReviews: ((place.reviews as Record<string, unknown>[]) || []).slice(0, 10).map(r => ({
|
||||
stars: r.stars, text: r.text, publishedAtDate: r.publishedAtDate,
|
||||
})),
|
||||
clinicWebsite: place.clinicWebsite,
|
||||
mapsUrl: place.mapsUrl,
|
||||
placeId: place.placeId,
|
||||
category: place.category, openingHours: place.openingHours,
|
||||
topReviews: place.topReviews,
|
||||
};
|
||||
} else {
|
||||
throw new Error("Google Maps: no matching place found");
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import "@supabase/functions-js/edge-runtime.d.ts";
|
||||
import { createClient } from "https://esm.sh/@supabase/supabase-js@2";
|
||||
import { normalizeInstagramHandle, normalizeYouTubeChannel } from "../_shared/normalizeHandles.ts";
|
||||
import { searchGooglePlace } from "../_shared/googlePlaces.ts";
|
||||
|
||||
const corsHeaders = {
|
||||
"Access-Control-Allow-Origin": "*",
|
||||
@@ -59,6 +60,7 @@ Deno.serve(async (req) => {
|
||||
|
||||
const APIFY_TOKEN = Deno.env.get("APIFY_API_TOKEN");
|
||||
if (!APIFY_TOKEN) throw new Error("APIFY_API_TOKEN not configured");
|
||||
const GOOGLE_PLACES_API_KEY = Deno.env.get("GOOGLE_PLACES_API_KEY") || "";
|
||||
|
||||
const enrichment: Record<string, unknown> = {};
|
||||
|
||||
@@ -135,50 +137,28 @@ Deno.serve(async (req) => {
|
||||
);
|
||||
}
|
||||
|
||||
// 2. Google Maps / Place Reviews
|
||||
if (clinicName || address) {
|
||||
// 2. Google Maps / Place Reviews (Google Places API New)
|
||||
if ((clinicName || address) && GOOGLE_PLACES_API_KEY) {
|
||||
tasks.push(
|
||||
(async () => {
|
||||
// Try multiple search queries for better hit rate
|
||||
const queries = [
|
||||
`${clinicName} 성형외과`,
|
||||
clinicName,
|
||||
`${clinicName} ${address || "강남"}`,
|
||||
];
|
||||
|
||||
let items: unknown[] = [];
|
||||
for (const query of queries) {
|
||||
items = await runApifyActor(
|
||||
"compass~crawler-google-places",
|
||||
{
|
||||
searchStringsArray: [query],
|
||||
maxCrawledPlacesPerSearch: 3,
|
||||
language: "ko",
|
||||
maxReviews: 10,
|
||||
},
|
||||
APIFY_TOKEN
|
||||
);
|
||||
if ((items as Record<string, unknown>[]).length > 0) break;
|
||||
}
|
||||
const place = (items as Record<string, unknown>[])[0];
|
||||
const place = await searchGooglePlace(
|
||||
clinicName || "",
|
||||
address || undefined,
|
||||
GOOGLE_PLACES_API_KEY,
|
||||
);
|
||||
if (place) {
|
||||
enrichment.googleMaps = {
|
||||
name: place.title,
|
||||
rating: place.totalScore,
|
||||
reviewCount: place.reviewsCount,
|
||||
name: place.name,
|
||||
rating: place.rating,
|
||||
reviewCount: place.reviewCount,
|
||||
address: place.address,
|
||||
phone: place.phone,
|
||||
clinicWebsite: place.website,
|
||||
mapsUrl: place.url || (place.title ? `https://www.google.com/maps/search/${encodeURIComponent(String(place.title))}` : ''),
|
||||
category: place.categoryName,
|
||||
clinicWebsite: place.clinicWebsite,
|
||||
mapsUrl: place.mapsUrl,
|
||||
placeId: place.placeId,
|
||||
category: place.category,
|
||||
openingHours: place.openingHours,
|
||||
topReviews: ((place.reviews as Record<string, unknown>[]) || [])
|
||||
.slice(0, 10)
|
||||
.map((r) => ({
|
||||
stars: r.stars,
|
||||
text: (r.text as string || "").slice(0, 200),
|
||||
publishedAtDate: r.publishedAtDate,
|
||||
})),
|
||||
topReviews: place.topReviews,
|
||||
};
|
||||
}
|
||||
})()
|
||||
|
||||
@@ -134,14 +134,19 @@ ${JSON.stringify(scrapeData.branding || {}, null, 2).slice(0, 1000)}
|
||||
// ─── Post-processing: Inject Vision Analysis data directly ───
|
||||
// Perplexity may ignore Vision data in prompt, so we force-inject critical fields
|
||||
const vision = channelData.visionAnalysis as Record<string, unknown> | undefined;
|
||||
const isEstablishedMissing = (val: unknown): boolean => {
|
||||
if (!val) return true;
|
||||
const s = String(val).trim().toLowerCase();
|
||||
return s === '' || s === '데이터 없음' || s === '데이터없음' || s === 'n/a' || s === '확인불가' || s === '미확인' || s === '정보없음' || s === '정보 없음';
|
||||
};
|
||||
if (vision) {
|
||||
// Force-inject foundingYear if Vision found it but Perplexity didn't
|
||||
if (vision.foundingYear && (!report.clinicInfo?.established || report.clinicInfo.established === "데이터 없음")) {
|
||||
if (vision.foundingYear && isEstablishedMissing(report.clinicInfo?.established)) {
|
||||
report.clinicInfo = report.clinicInfo || {};
|
||||
report.clinicInfo.established = String(vision.foundingYear);
|
||||
console.log(`[report] Injected foundingYear from Vision: ${vision.foundingYear}`);
|
||||
}
|
||||
if (vision.operationYears && (!report.clinicInfo?.established || report.clinicInfo.established === "데이터 없음")) {
|
||||
if (vision.operationYears && isEstablishedMissing(report.clinicInfo?.established)) {
|
||||
const year = new Date().getFullYear() - Number(vision.operationYears);
|
||||
report.clinicInfo = report.clinicInfo || {};
|
||||
report.clinicInfo.established = String(year);
|
||||
@@ -202,6 +207,78 @@ ${JSON.stringify(scrapeData.branding || {}, null, 2).slice(0, 1000)}
|
||||
caption: ss.caption,
|
||||
sourceUrl: ss.sourceUrl,
|
||||
}));
|
||||
|
||||
// 채널별 스크린샷 그룹핑 (프론트엔드에서 각 채널 섹션에 증거 이미지 표시)
|
||||
report.channelScreenshots = screenshots.reduce((acc: Record<string, unknown[]>, ss: Record<string, unknown>) => {
|
||||
const channel = ss.channel as string || 'etc';
|
||||
if (!acc[channel]) acc[channel] = [];
|
||||
acc[channel].push({ url: ss.url, caption: ss.caption, id: ss.id, sourceUrl: ss.sourceUrl });
|
||||
return acc;
|
||||
}, {} as Record<string, unknown[]>);
|
||||
}
|
||||
|
||||
// Instagram Posts/Reels 분석 (engagement rate, 콘텐츠 성과)
|
||||
const igProfile = channelData.instagram as Record<string, unknown> | undefined;
|
||||
const igPosts = channelData.instagramPosts as Record<string, unknown> | undefined;
|
||||
const igReels = channelData.instagramReels as Record<string, unknown> | undefined;
|
||||
if (igProfile && (igPosts || igReels)) {
|
||||
const followers = (igProfile.followers as number) || 0;
|
||||
const avgLikes = (igPosts?.avgLikes as number) || 0;
|
||||
const avgComments = (igPosts?.avgComments as number) || 0;
|
||||
|
||||
// 해시태그 빈도 분석
|
||||
const hashtagCounts: Record<string, number> = {};
|
||||
const allPosts = [...((igPosts?.posts as Record<string, unknown>[]) || []), ...((igReels?.reels as Record<string, unknown>[]) || [])];
|
||||
for (const post of allPosts) {
|
||||
for (const tag of (post.hashtags as string[]) || []) {
|
||||
const lower = tag.toLowerCase();
|
||||
hashtagCounts[lower] = (hashtagCounts[lower] || 0) + 1;
|
||||
}
|
||||
}
|
||||
const topHashtags = Object.entries(hashtagCounts)
|
||||
.sort((a, b) => b[1] - a[1])
|
||||
.slice(0, 10)
|
||||
.map(([tag, count]) => ({ tag, count }));
|
||||
|
||||
// 게시 빈도 (최근 포스트 간 평균 간격)
|
||||
const postTimestamps = ((igPosts?.posts as Record<string, unknown>[]) || [])
|
||||
.map(p => new Date(p.timestamp as string).getTime())
|
||||
.filter(t => !isNaN(t))
|
||||
.sort((a, b) => b - a);
|
||||
let postFrequency = 'N/A';
|
||||
if (postTimestamps.length >= 2) {
|
||||
const spanDays = (postTimestamps[0] - postTimestamps[postTimestamps.length - 1]) / (1000 * 60 * 60 * 24);
|
||||
const postsPerWeek = spanDays > 0 ? (postTimestamps.length / spanDays * 7).toFixed(1) : 'N/A';
|
||||
postFrequency = `${postsPerWeek}회/주`;
|
||||
}
|
||||
|
||||
// 최고 성과 포스트
|
||||
const bestPost = ((igPosts?.posts as Record<string, unknown>[]) || [])
|
||||
.sort((a, b) => ((b.likesCount as number) || 0) - ((a.likesCount as number) || 0))[0] || null;
|
||||
|
||||
report.instagramAnalysis = {
|
||||
engagementRate: followers > 0 ? ((avgLikes + avgComments) / followers * 100).toFixed(2) + '%' : 'N/A',
|
||||
avgLikes,
|
||||
avgComments,
|
||||
topHashtags,
|
||||
postFrequency,
|
||||
bestPerformingPost: bestPost ? {
|
||||
url: bestPost.url,
|
||||
likes: bestPost.likesCount,
|
||||
comments: bestPost.commentsCount,
|
||||
caption: ((bestPost.caption as string) || '').slice(0, 200),
|
||||
} : null,
|
||||
reelsPerformance: igReels ? {
|
||||
totalReels: igReels.totalReels,
|
||||
avgViews: igReels.avgViews,
|
||||
avgPlays: igReels.avgPlays,
|
||||
viewToFollowerRatio: followers > 0
|
||||
? (((igReels.avgViews as number) || 0) / followers * 100).toFixed(1) + '%'
|
||||
: 'N/A',
|
||||
} : null,
|
||||
totalPostsAnalyzed: (igPosts?.totalPosts as number) || 0,
|
||||
totalReelsAnalyzed: (igReels?.totalReels as number) || 0,
|
||||
};
|
||||
}
|
||||
|
||||
// Embed verified handles
|
||||
|
||||
Reference in new issue
Block a user