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으로 추출해줘.`;
|
||||
|
||||
Reference in new issue
Block a user