feat: real API integration + YouTube Data API v3 + progressive loading

- Replace mock useReport() with real Supabase API data pipeline
- Add transformReport.ts to map API responses to MarketingReport type
- Add useEnrichment() hook for background channel data enrichment
- Replace Apify YouTube scraper with YouTube Data API v3
- Add mergeEnrichment() for progressive data loading
- Add EmptyState component for graceful empty data handling
- Add socialHandles to generate-report metadata
- Graceful empty data in ClinicSnapshot, YouTube, Instagram, Facebook
- Add Supabase Edge Functions and DB migrations
- Add developer handoff documentation

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
Haewon KamandClaude Opus 4.6 committed 2026-04-02 10:57:14 +09:00
1 parent c6e18b6a67
commit 60cd055042
30 files changed
+2905 -142

No files matched your search

+80
View File
@@ -0,0 +1,80 @@
import { createClient } from "@supabase/supabase-js";
const supabaseUrl = import.meta.env.VITE_SUPABASE_URL;
const supabaseAnonKey = import.meta.env.VITE_SUPABASE_ANON_KEY;
export const supabase = createClient(supabaseUrl, supabaseAnonKey);
export async function generateMarketingReport(url: string, clinicName?: string) {
const response = await fetch(
`${supabaseUrl}/functions/v1/generate-report`,
{
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ url, clinicName }),
}
);
if (!response.ok) {
throw new Error(`Report generation failed: ${response.statusText}`);
}
return response.json();
}
export async function fetchReportById(reportId: string) {
const { data, error } = await supabase
.from("marketing_reports")
.select("*")
.eq("id", reportId)
.single();
if (error) throw new Error(`Failed to fetch report: ${error.message}`);
return data;
}
export interface EnrichChannelsRequest {
reportId: string;
clinicName: string;
instagramHandle?: string;
youtubeChannelId?: string;
address?: string;
}
/**
* Fire-and-forget: triggers background channel enrichment.
* Returns enrichment result when the Edge Function completes (~27s).
*/
export async function enrichChannels(params: EnrichChannelsRequest) {
const response = await fetch(
`${supabaseUrl}/functions/v1/enrich-channels`,
{
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(params),
}
);
if (!response.ok) {
throw new Error(`Channel enrichment failed: ${response.statusText}`);
}
return response.json();
}
export async function scrapeWebsite(url: string, clinicName?: string) {
const response = await fetch(
`${supabaseUrl}/functions/v1/scrape-website`,
{
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ url, clinicName }),
}
);
if (!response.ok) {
throw new Error(`Scraping failed: ${response.statusText}`);
}
return response.json();
}
+501
View File
@@ -0,0 +1,501 @@
import type { MarketingReport, Severity, ChannelScore, DiagnosisItem, TopVideo } from '../types/report';
/**
* API response from generate-report Edge Function.
* The `report` field is AI-generated JSON with varying structure.
*/
interface ApiReport {
clinicInfo?: {
name?: string;
address?: string;
phone?: string;
services?: string[];
doctors?: { name: string; specialty: string }[];
};
executiveSummary?: string;
overallScore?: number;
channelAnalysis?: Record<string, {
score?: number;
status?: string;
posts?: number;
followers?: number;
subscribers?: number;
rating?: number;
reviews?: number;
issues?: string[];
recommendation?: string;
}>;
competitors?: {
name: string;
strengths?: string[];
weaknesses?: string[];
marketingChannels?: string[];
}[];
keywords?: {
primary?: { keyword: string; monthlySearches?: number; competition?: string }[];
longTail?: { keyword: string; monthlySearches?: number }[];
};
targetAudience?: {
primary?: { ageRange?: string; gender?: string; interests?: string[]; channels?: string[] };
secondary?: { ageRange?: string; gender?: string; interests?: string[]; channels?: string[] };
};
recommendations?: {
priority?: string;
category?: string;
title?: string;
description?: string;
expectedImpact?: string;
}[];
marketTrends?: string[];
}
interface ApiMetadata {
url: string;
clinicName: string;
generatedAt: string;
dataSources?: Record<string, boolean>;
}
function scoreToSeverity(score: number | undefined): Severity {
if (score === undefined) return 'unknown';
if (score >= 80) return 'excellent';
if (score >= 60) return 'good';
if (score >= 40) return 'warning';
return 'critical';
}
function statusToSeverity(status: string | undefined): Severity {
switch (status) {
case 'active': return 'good';
case 'inactive': return 'critical';
case 'weak': return 'warning';
default: return 'unknown';
}
}
const CHANNEL_ICONS: Record<string, string> = {
naverBlog: 'blog',
instagram: 'instagram',
youtube: 'youtube',
naverPlace: 'map',
gangnamUnni: 'star',
website: 'globe',
facebook: 'facebook',
tiktok: 'video',
};
function buildChannelScores(channels: ApiReport['channelAnalysis']): ChannelScore[] {
if (!channels) return [];
return Object.entries(channels).map(([key, ch]) => ({
channel: key,
icon: CHANNEL_ICONS[key] || 'circle',
score: ch.score ?? 0,
maxScore: 100,
status: ch.score !== undefined ? scoreToSeverity(ch.score) : statusToSeverity(ch.status),
headline: ch.recommendation || '',
}));
}
function buildDiagnosis(report: ApiReport): DiagnosisItem[] {
const items: DiagnosisItem[] = [];
// Extract issues from channel analysis
if (report.channelAnalysis) {
for (const [channel, ch] of Object.entries(report.channelAnalysis)) {
if (ch.status === 'inactive' || ch.status === 'weak') {
items.push({
category: channel,
detail: ch.recommendation || `${channel} 채널이 ${ch.status === 'inactive' ? '비활성' : '약함'} 상태입니다`,
severity: statusToSeverity(ch.status),
});
}
if (ch.issues) {
for (const issue of ch.issues) {
items.push({ category: channel, detail: issue, severity: 'warning' });
}
}
}
}
// Extract from recommendations
if (report.recommendations) {
for (const rec of report.recommendations) {
if (rec.priority === 'high') {
items.push({
category: rec.category || '일반',
detail: `${rec.title}: ${rec.description}`,
severity: 'critical',
});
}
}
}
return items;
}
/**
* Transform raw API response into the MarketingReport shape
* that frontend components expect.
*/
export function transformApiReport(
reportId: string,
apiReport: ApiReport,
metadata: ApiMetadata,
): MarketingReport {
const r = apiReport;
const clinic = r.clinicInfo || {};
const doctor = clinic.doctors?.[0];
return {
id: reportId,
createdAt: metadata.generatedAt || new Date().toISOString(),
targetUrl: metadata.url,
overallScore: r.overallScore ?? 50,
clinicSnapshot: {
name: clinic.name || metadata.clinicName || '',
nameEn: '',
established: '',
yearsInBusiness: 0,
staffCount: 0,
leadDoctor: {
name: doctor?.name || '',
credentials: doctor?.specialty || '',
rating: 0,
reviewCount: 0,
},
overallRating: r.channelAnalysis?.gangnamUnni?.rating ?? 0,
totalReviews: r.channelAnalysis?.gangnamUnni?.reviews ?? 0,
priceRange: { min: '-', max: '-', currency: '₩' },
certifications: [],
mediaAppearances: [],
medicalTourism: [],
location: clinic.address || '',
nearestStation: '',
phone: clinic.phone || '',
domain: new URL(metadata.url).hostname,
},
channelScores: buildChannelScores(r.channelAnalysis),
youtubeAudit: {
channelName: clinic.name || '',
handle: '',
subscribers: r.channelAnalysis?.youtube?.subscribers ?? 0,
totalVideos: 0,
totalViews: 0,
weeklyViewGrowth: { absolute: 0, percentage: 0 },
estimatedMonthlyRevenue: { min: 0, max: 0 },
avgVideoLength: '-',
uploadFrequency: '-',
channelCreatedDate: '',
subscriberRank: '-',
channelDescription: '',
linkedUrls: [],
playlists: [],
topVideos: [],
diagnosis: (r.channelAnalysis?.youtube?.recommendation)
? [{ category: 'YouTube', detail: r.channelAnalysis.youtube.recommendation, severity: scoreToSeverity(r.channelAnalysis.youtube.score) }]
: [],
},
instagramAudit: {
accounts: r.channelAnalysis?.instagram ? [{
handle: '',
language: 'KR',
label: '메인',
posts: r.channelAnalysis.instagram.posts ?? 0,
followers: r.channelAnalysis.instagram.followers ?? 0,
following: 0,
category: '의료/건강',
profileLink: '',
highlights: [],
reelsCount: 0,
contentFormat: '',
profilePhoto: '',
bio: '',
}] : [],
diagnosis: (r.channelAnalysis?.instagram?.recommendation)
? [{ category: 'Instagram', detail: r.channelAnalysis.instagram.recommendation, severity: scoreToSeverity(r.channelAnalysis.instagram.score) }]
: [],
},
facebookAudit: {
pages: [],
diagnosis: [],
brandInconsistencies: [],
consolidationRecommendation: '',
},
otherChannels: [
...(r.channelAnalysis?.naverBlog ? [{
name: '네이버 블로그',
status: (r.channelAnalysis.naverBlog.status === 'active' ? 'active' : 'inactive') as 'active' | 'inactive',
details: r.channelAnalysis.naverBlog.recommendation || '',
}] : []),
...(r.channelAnalysis?.naverPlace ? [{
name: '네이버 플레이스',
status: (r.channelAnalysis.naverPlace.status === 'active' ? 'active' : 'inactive') as 'active' | 'inactive',
details: `평점: ${r.channelAnalysis.naverPlace.rating ?? '-'} / 리뷰: ${r.channelAnalysis.naverPlace.reviews ?? '-'}`,
}] : []),
...(r.channelAnalysis?.gangnamUnni ? [{
name: '강남언니',
status: (r.channelAnalysis.gangnamUnni.status === 'active' ? 'active' : 'inactive') as 'active' | 'inactive',
details: `평점: ${r.channelAnalysis.gangnamUnni.rating ?? '-'} / 리뷰: ${r.channelAnalysis.gangnamUnni.reviews ?? '-'}`,
}] : []),
],
websiteAudit: {
primaryDomain: new URL(metadata.url).hostname,
additionalDomains: [],
snsLinksOnSite: false,
trackingPixels: [],
mainCTA: '',
},
problemDiagnosis: buildDiagnosis(r),
transformation: {
brandIdentity: [],
contentStrategy: (r.recommendations || [])
.filter(rec => rec.category?.includes('콘텐츠') || rec.category?.includes('content'))
.map(rec => ({
area: rec.title || '',
asIs: rec.description || '',
toBe: rec.expectedImpact || '',
})),
platformStrategies: buildChannelScores(r.channelAnalysis).map(ch => ({
platform: ch.channel,
icon: ch.icon,
currentMetric: `점수: ${ch.score}`,
targetMetric: `목표: ${Math.min(ch.score + 20, 100)}`,
strategies: [],
})),
websiteImprovements: (r.channelAnalysis?.website?.issues || []).map(issue => ({
area: '웹사이트',
asIs: issue,
toBe: '개선 필요',
})),
newChannelProposals: [],
},
roadmap: [1, 2, 3].map(month => ({
month,
title: `${month}개월차`,
subtitle: month === 1 ? '기반 구축' : month === 2 ? '콘텐츠 강화' : '성과 최적화',
tasks: (r.recommendations || [])
.filter(rec => {
if (month === 1) return rec.priority === 'high';
if (month === 2) return rec.priority === 'medium';
return rec.priority === 'low';
})
.slice(0, 4)
.map(rec => ({ task: rec.title || rec.description || '', completed: false })),
})),
kpiDashboard: [
{ metric: '종합 점수', current: `${r.overallScore ?? '-'}`, target3Month: `${Math.min((r.overallScore ?? 50) + 15, 100)}`, target12Month: `${Math.min((r.overallScore ?? 50) + 30, 100)}` },
...(r.channelAnalysis?.instagram ? [
{ metric: 'Instagram 팔로워', current: `${r.channelAnalysis.instagram.followers ?? 0}`, target3Month: `${Math.round((r.channelAnalysis.instagram.followers ?? 0) * 1.3)}`, target12Month: `${Math.round((r.channelAnalysis.instagram.followers ?? 0) * 2)}` },
] : []),
...(r.channelAnalysis?.youtube ? [
{ metric: 'YouTube 구독자', current: `${r.channelAnalysis.youtube.subscribers ?? 0}`, target3Month: `${Math.round((r.channelAnalysis.youtube.subscribers ?? 0) * 1.5)}`, target12Month: `${Math.round((r.channelAnalysis.youtube.subscribers ?? 0) * 3)}` },
] : []),
],
screenshots: [],
};
}
/**
* Enrichment data shape from enrich-channels Edge Function.
*/
export interface EnrichmentData {
instagram?: {
username?: string;
followers?: number;
following?: number;
posts?: number;
bio?: string;
isBusinessAccount?: boolean;
externalUrl?: string;
latestPosts?: {
type?: string;
likes?: number;
comments?: number;
caption?: string;
timestamp?: string;
}[];
};
googleMaps?: {
name?: string;
rating?: number;
reviewCount?: number;
address?: string;
phone?: string;
website?: string;
category?: string;
openingHours?: unknown;
topReviews?: {
stars?: number;
text?: string;
publishedAtDate?: string;
}[];
};
youtube?: {
channelId?: string;
channelName?: string;
handle?: string;
description?: string;
publishedAt?: string;
thumbnailUrl?: string;
subscribers?: number;
totalViews?: number;
totalVideos?: number;
videos?: {
title?: string;
views?: number;
likes?: number;
comments?: number;
date?: string;
duration?: string;
url?: string;
thumbnail?: string;
}[];
};
}
/**
* Merge enrichment data into an existing MarketingReport.
* Returns a new object — does not mutate the original.
*/
export function mergeEnrichment(
report: MarketingReport,
enrichment: EnrichmentData,
): MarketingReport {
const merged = { ...report };
// Instagram enrichment
if (enrichment.instagram) {
const ig = enrichment.instagram;
const existingAccount = merged.instagramAudit.accounts[0];
merged.instagramAudit = {
...merged.instagramAudit,
accounts: [{
handle: ig.username || existingAccount?.handle || '',
language: 'KR',
label: '메인',
posts: ig.posts ?? existingAccount?.posts ?? 0,
followers: ig.followers ?? existingAccount?.followers ?? 0,
following: ig.following ?? existingAccount?.following ?? 0,
category: '의료/건강',
profileLink: ig.username ? `https://instagram.com/${ig.username}` : '',
highlights: [],
reelsCount: 0,
contentFormat: ig.isBusinessAccount ? '비즈니스 계정' : '일반 계정',
profilePhoto: '',
bio: ig.bio || '',
}],
};
// Update KPI with real follower data
merged.kpiDashboard = merged.kpiDashboard.map(kpi =>
kpi.metric === 'Instagram 팔로워' && ig.followers
? {
...kpi,
current: `${ig.followers.toLocaleString()}`,
target3Month: `${Math.round(ig.followers * 1.3).toLocaleString()}`,
target12Month: `${Math.round(ig.followers * 2).toLocaleString()}`,
}
: kpi
);
}
// YouTube enrichment (YouTube Data API v3)
if (enrichment.youtube) {
const yt = enrichment.youtube;
const videos = yt.videos || [];
// Parse ISO 8601 duration (PT1H2M3S) to readable format
const parseDuration = (iso?: string): string => {
if (!iso) return '-';
const match = iso.match(/PT(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?/);
if (!match) return iso;
const h = match[1] ? `${match[1]}:` : '';
const m = match[2] || '0';
const s = (match[3] || '0').padStart(2, '0');
return h ? `${h}${m.padStart(2, '0')}:${s}` : `${m}:${s}`;
};
// Check if video is a Short (< 60 seconds)
const isShort = (iso?: string): boolean => {
if (!iso) return false;
const match = iso.match(/PT(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?/);
if (!match) return false;
const totalSec = (parseInt(match[1] || '0') * 3600) + (parseInt(match[2] || '0') * 60) + parseInt(match[3] || '0');
return totalSec <= 60;
};
merged.youtubeAudit = {
...merged.youtubeAudit,
channelName: yt.channelName || merged.youtubeAudit.channelName,
handle: yt.handle || merged.youtubeAudit.handle,
subscribers: yt.subscribers ?? merged.youtubeAudit.subscribers,
totalVideos: yt.totalVideos ?? merged.youtubeAudit.totalVideos,
totalViews: yt.totalViews ?? merged.youtubeAudit.totalViews,
channelDescription: yt.description || merged.youtubeAudit.channelDescription,
channelCreatedDate: yt.publishedAt ? new Date(yt.publishedAt).toLocaleDateString('ko-KR') : merged.youtubeAudit.channelCreatedDate,
topVideos: videos.slice(0, 5).map((v): TopVideo => ({
title: v.title || '',
views: v.views || 0,
uploadedAgo: v.date ? new Date(v.date).toLocaleDateString('ko-KR') : '',
type: isShort(v.duration) ? 'Short' : 'Long',
duration: parseDuration(v.duration),
})),
};
// Update KPI with real subscriber data
if (yt.subscribers) {
merged.kpiDashboard = merged.kpiDashboard.map(kpi =>
kpi.metric === 'YouTube 구독자'
? {
...kpi,
current: `${yt.subscribers!.toLocaleString()}`,
target3Month: `${Math.round(yt.subscribers! * 1.5).toLocaleString()}`,
target12Month: `${Math.round(yt.subscribers! * 3).toLocaleString()}`,
}
: kpi
);
}
}
// Google Maps enrichment
if (enrichment.googleMaps) {
const gm = enrichment.googleMaps;
merged.clinicSnapshot = {
...merged.clinicSnapshot,
overallRating: gm.rating ?? merged.clinicSnapshot.overallRating,
totalReviews: gm.reviewCount ?? merged.clinicSnapshot.totalReviews,
phone: gm.phone || merged.clinicSnapshot.phone,
location: gm.address || merged.clinicSnapshot.location,
};
// Update or add Google Maps to otherChannels
const gmChannelIdx = merged.otherChannels.findIndex(c => c.name === '구글 지도');
const gmChannel = {
name: '구글 지도',
status: 'active' as const,
details: `평점: ${gm.rating ?? '-'} / 리뷰: ${gm.reviewCount ?? '-'}`,
url: '',
};
if (gmChannelIdx >= 0) {
merged.otherChannels[gmChannelIdx] = gmChannel;
} else {
merged.otherChannels = [...merged.otherChannels, gmChannel];
}
}
return merged;
}