feat: 클리닉 전용 페이지 추가, PageContainer 도입, 불필요한 ui 주석처리

This commit is contained in:
minaChoi committed 2026-05-14 11:53:29 +09:00
1 parent e66b208318
commit 49367756ea
77 files changed
+3498 -924

No files matched your search

@@ -171,8 +171,9 @@ export default function ClinicSnapshot({ data }: ClinicSnapshotProps) {
{data.certifications.map((cert) => (
<span
key={cert}
className="rounded-full bg-white/60 backdrop-blur-sm border border-white/40 px-3 py-1 text-sm font-medium text-slate-700"
className="inline-flex items-center gap-1.5 rounded-full bg-brand-tint-purple border border-brand-tint-lavender px-3 py-1 text-sm font-medium text-brand-purple-muted"
>
<Award size={12} className="text-brand-purple" />
{cert}
</span>
))}
@@ -0,0 +1,65 @@
/**
* DownloadMenuButton — 리포트 다운로드 단일 진입점.
* 클릭하면 PDF / CSV 선택 메뉴가 드롭다운으로 열림.
*
* PDF: 브라우저 네이티브 인쇄(window.print) → "PDF로 저장"
* CSV: 리포트의 표 데이터를 다중 섹션 CSV 단일 파일로 다운로드
*/
import { Download, FileText, FileSpreadsheet, ChevronDown, Loader2 } from 'lucide-react';
import {
DropdownMenu,
DropdownMenuTrigger,
DropdownMenuContent,
DropdownMenuItem,
} from '@/shared/ui/dropdown-menu';
import { useExportPDF } from '@/features/report/hooks/useExportPDF';
import { useExportCSV } from '@/features/report/hooks/useExportCSV';
import type { MarketingReport } from '@/features/report/types/report';
interface DownloadMenuButtonProps {
/** 파일명 베이스. 자동으로 .pdf / .csv 확장자 붙음 */
filename: string;
/** 서버에서 받아온 리포트 전체 (CSV 생성에 사용) */
report: MarketingReport;
className?: string;
}
export function DownloadMenuButton({ filename, report, className }: DownloadMenuButtonProps) {
const { exportPDF, isExporting } = useExportPDF();
const { exportReportCSV } = useExportCSV();
return (
<DropdownMenu>
<DropdownMenuTrigger
disabled={isExporting}
className={
className ??
'inline-flex items-center gap-1.5 px-3.5 py-2 rounded-full text-xs font-medium text-slate-600 bg-slate-50 border border-slate-200 hover:bg-white hover:border-slate-300 transition-all disabled:opacity-60 disabled:cursor-wait'
}
>
{isExporting ? (
<>
<Loader2 size={12} className="animate-spin" />
생성 중...
</>
) : (
<>
<Download size={12} />
다운로드
<ChevronDown size={12} className="opacity-70" />
</>
)}
</DropdownMenuTrigger>
<DropdownMenuContent>
<DropdownMenuItem onSelect={() => exportPDF(filename)}>
<FileText size={14} className="text-slate-500" />
<span>PDF로 저장</span>
</DropdownMenuItem>
<DropdownMenuItem onSelect={() => exportReportCSV(filename, report)}>
<FileSpreadsheet size={14} className="text-slate-500" />
<span>CSV로 저장</span>
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
);
}
@@ -118,9 +118,6 @@ export default function OtherChannels({ channels, website }: OtherChannelsProps)
<p className={`text-sm font-medium ${pixel.installed ? 'text-[#4A3A7C]' : 'text-[#7C3A4B]'}`}>
{pixel.name}
</p>
{pixel.details && (
<p className="text-xs text-slate-500 truncate">{pixel.details}</p>
)}
</div>
</div>
))}
@@ -0,0 +1,51 @@
/**
* PdfDownloadButton — 리포트/플랜 PDF 다운로드 버튼.
*
* 브라우저 네이티브 인쇄 다이얼로그를 띄워 "PDF로 저장" 흐름을 사용합니다.
* `@media print` 규칙(`src/styles/custom.css`)이 레이아웃·색상·페이지 분할을 담당하며,
* `data-no-print`/`data-report-nav`/`data-plan-nav`/`data-cta-card`/`nav` 요소는
* 인쇄에서 자동 제외됩니다.
*/
import { Download, Loader2 } from 'lucide-react';
import { useExportPDF } from '@/features/report/hooks/useExportPDF';
interface PdfDownloadButtonProps {
/** PDF 파일명. 자동으로 .pdf 확장자 붙음. 'Plan' 포함 시 푸터 라벨도 변경 */
filename: string;
/** 버튼 표시 라벨. 기본: PDF */
label?: string;
className?: string;
}
export function PdfDownloadButton({
filename,
label = 'PDF',
className,
}: PdfDownloadButtonProps) {
const { exportPDF, isExporting } = useExportPDF();
return (
<button
type="button"
onClick={() => exportPDF(filename)}
disabled={isExporting}
className={
className ??
'inline-flex items-center gap-1.5 px-3.5 py-2 rounded-full text-xs font-medium text-slate-600 bg-slate-50 border border-slate-200 hover:bg-white hover:border-slate-300 transition-all disabled:opacity-60 disabled:cursor-wait'
}
title="PDF로 다운로드"
>
{isExporting ? (
<>
<Loader2 size={12} className="animate-spin" />
생성 중...
</>
) : (
<>
<Download size={12} />
{label}
</>
)}
</button>
);
}
@@ -0,0 +1,139 @@
/**
* ReportBody — 리포트 본문(헤더 + 모든 섹션) 순수 렌더링.
*
* 각 섹션은 데이터가 비어있으면 `EmptySection` 으로 fallback 되어
* "데이터가 없습니다" 안내가 표시됩니다. Guest / User 두 페이지 모두
* 동일한 동작.
*/
import type { MarketingReport } from '@/features/report/types/report';
import { SectionErrorBoundary } from '@/features/report/components/ui/SectionErrorBoundary';
import { EmptySection } from '@/features/report/components/ui/EmptySection';
import ReportHeader from '@/features/report/components/ReportHeader';
import ClinicSnapshot from '@/features/report/components/ClinicSnapshot';
import ChannelOverview from '@/features/report/components/ChannelOverview';
import YouTubeAudit from '@/features/report/components/YouTubeAudit';
import InstagramAudit from '@/features/report/components/InstagramAudit';
import FacebookAudit from '@/features/report/components/FacebookAudit';
import OtherChannels from '@/features/report/components/OtherChannels';
import ProblemDiagnosis from '@/features/report/components/ProblemDiagnosis';
import TransformationProposal from '@/features/report/components/TransformationProposal';
import RoadmapTimeline from '@/features/report/components/RoadmapTimeline';
import KPIDashboard from '@/features/report/components/KPIDashboard';
interface ReportBodyProps {
data: MarketingReport;
}
function hasValue<T>(v: T | null | undefined): v is T {
return v != null;
}
function nonEmpty<T>(arr: T[] | null | undefined): arr is T[] {
return Array.isArray(arr) && arr.length > 0;
}
export default function ReportBody({ data }: ReportBodyProps) {
// 각 audit에서 핸들 끌어와 헤더의 바로가기 버튼에 전달
const socialHandles = {
website: data.targetUrl || data.clinicSnapshot.domain || null,
youtube: data.youtubeAudit?.handle || null,
instagram: data.instagramAudit?.accounts?.[0]?.handle || null,
facebook: data.facebookAudit?.pages?.[0]?.url || data.facebookAudit?.pages?.[0]?.pageName || null,
};
return (
<div data-report-content>
<ReportHeader
overallScore={data.overallScore}
clinicName={data.clinicSnapshot.name}
clinicNameEn={data.clinicSnapshot.nameEn}
targetUrl={data.targetUrl}
date={data.createdAt}
location={data.clinicSnapshot.location}
logoImage={data.clinicSnapshot.logoImages?.horizontal}
brandColors={data.clinicSnapshot.brandColors}
socialHandles={socialHandles}
/>
<SectionErrorBoundary>
{hasValue(data.clinicSnapshot) && data.clinicSnapshot.name ? (
<ClinicSnapshot data={data.clinicSnapshot} />
) : (
<EmptySection id="clinic-snapshot" title="Clinic Overview" subtitle="병원 기본 정보" />
)}
</SectionErrorBoundary>
<SectionErrorBoundary>
{nonEmpty(data.channelScores) ? (
<ChannelOverview channels={data.channelScores} />
) : (
<EmptySection id="channel-overview" title="Channel Overview" subtitle="채널 종합 진단" />
)}
</SectionErrorBoundary>
<SectionErrorBoundary>
{hasValue(data.youtubeAudit) && data.youtubeAudit.handle ? (
<YouTubeAudit data={data.youtubeAudit} />
) : (
<EmptySection id="youtube-audit" title="YouTube Analysis" subtitle="유튜브 채널 분석" />
)}
</SectionErrorBoundary>
<SectionErrorBoundary>
{hasValue(data.instagramAudit) && data.instagramAudit.handle ? (
<InstagramAudit data={data.instagramAudit} />
) : (
<EmptySection id="instagram-audit" title="Instagram Analysis" subtitle="인스타그램 분석" />
)}
</SectionErrorBoundary>
<SectionErrorBoundary>
{hasValue(data.facebookAudit) && (data.facebookAudit.handle || data.facebookAudit.followers > 0) ? (
<FacebookAudit data={data.facebookAudit} />
) : (
<EmptySection id="facebook-audit" title="Facebook Analysis" subtitle="페이스북 페이지 분석" />
)}
</SectionErrorBoundary>
<SectionErrorBoundary>
{nonEmpty(data.otherChannels) || hasValue(data.websiteAudit) ? (
<OtherChannels channels={data.otherChannels ?? []} website={data.websiteAudit} />
) : (
<EmptySection id="other-channels" title="Other Channels" subtitle="기타 채널 및 웹사이트" />
)}
</SectionErrorBoundary>
<SectionErrorBoundary>
{nonEmpty(data.problemDiagnosis) ? (
<ProblemDiagnosis diagnosis={data.problemDiagnosis} />
) : (
<EmptySection id="problem-diagnosis" title="Problem Diagnosis" subtitle="문제 진단" />
)}
</SectionErrorBoundary>
<SectionErrorBoundary>
{hasValue(data.transformation) ? (
<TransformationProposal data={data.transformation} />
) : (
<EmptySection id="transformation" title="Transformation" subtitle="개선 제안" />
)}
</SectionErrorBoundary>
<SectionErrorBoundary>
{nonEmpty(data.roadmap) ? (
<RoadmapTimeline months={data.roadmap} />
) : (
<EmptySection id="roadmap" title="Roadmap" subtitle="실행 로드맵" />
)}
</SectionErrorBoundary>
<SectionErrorBoundary>
{nonEmpty(data.kpiDashboard) ? (
<KPIDashboard metrics={data.kpiDashboard} clinicName={data.clinicSnapshot.name} />
) : (
<EmptySection id="kpi-dashboard" title="KPI Dashboard" subtitle="핵심 지표" />
)}
</SectionErrorBoundary>
</div>
);
}
@@ -1,6 +1,8 @@
import { motion } from 'motion/react';
import { Calendar, Globe, MapPin } from 'lucide-react';
import { ScoreRing } from './ui/ScoreRing';
import { ChannelLinkButtons, type ChannelHandles } from '@/shared/ui/channel-link-buttons';
import { PageContainer } from '@/shared/ui/page-container';
function formatDate(raw: string): string {
try {
@@ -23,6 +25,8 @@ interface ReportHeaderProps {
location: string;
logoImage?: string;
brandColors?: { primary: string; accent: string; text: string };
/** 등록된 채널 핸들/URL — 외부 새 탭으로 이동 버튼 묶음을 렌더링 */
socialHandles?: ChannelHandles;
}
export default function ReportHeader({
@@ -34,6 +38,7 @@ export default function ReportHeader({
date,
targetUrl,
location,
socialHandles,
}: ReportHeaderProps) {
return (
<section className="relative overflow-hidden bg-[radial-gradient(ellipse_at_top_left,#e0e7ff,transparent_50%),radial-gradient(ellipse_at_bottom_right,#fce7f3,transparent_50%),radial-gradient(ellipse_at_center,#f5f3ff,transparent_60%)] py-20 px-6">
@@ -54,7 +59,7 @@ export default function ReportHeader({
transition={{ duration: 6, repeat: Infinity, ease: 'easeInOut' }}
/>
<div className="relative max-w-7xl mx-auto">
<PageContainer className="relative px-0">
<div className="flex flex-col md:flex-row items-center md:items-start justify-between gap-10">
{/* Left: Text content */}
<motion.div
@@ -131,6 +136,23 @@ export default function ReportHeader({
{location}
</span>
</motion.div>
{/* 등록된 채널 바로가기 */}
{socialHandles && (
<motion.div
className="mt-4"
initial={{ opacity: 0, y: 20 }}
whileInView={{ opacity: 1, y: 0 }}
viewport={{ once: true }}
transition={{ duration: 0.5, delay: 0.5 }}
>
<ChannelLinkButtons
handles={socialHandles}
variant="light"
className="justify-center md:justify-start"
/>
</motion.div>
)}
</motion.div>
{/* Right: Score ring */}
@@ -149,7 +171,7 @@ export default function ReportHeader({
</div>
</motion.div>
</div>
</div>
</PageContainer>
</section>
);
}
+46 -29
View File
@@ -1,11 +1,16 @@
import { useEffect, useRef, useState } from 'react';
import { useEffect, useRef, useState, type ReactNode } from 'react';
import { Button } from '@/shared/ui/button';
import { PageContainer } from '@/shared/ui/page-container';
interface ReportNavProps {
sections: { id: string; label: string }[];
/** 좌측 슬롯 — 보통 "워크스페이스로" 같은 뒤로가기 링크 */
leftSlot?: ReactNode;
/** 우측 슬롯 — 보통 리포트↔플랜 점프 버튼 등 보조 액션 */
rightSlot?: ReactNode;
}
export function ReportNav({ sections }: ReportNavProps) {
export function ReportNav({ sections, leftSlot, rightSlot }: ReportNavProps) {
const [activeId, setActiveId] = useState(sections[0]?.id ?? '');
const navRef = useRef<HTMLDivElement>(null);
const tabRefs = useRef<Map<string, HTMLButtonElement>>(new Map());
@@ -54,33 +59,45 @@ export function ReportNav({ sections }: ReportNavProps) {
return (
<nav data-report-nav className="sticky top-20 z-40 bg-white/95 border-b border-slate-100">
<div
ref={navRef}
className="max-w-7xl mx-auto flex overflow-x-auto scrollbar-hide"
style={{ scrollbarWidth: 'none', msOverflowStyle: 'none' }}
>
{sections.map(({ id, label }) => (
<Button
type="button"
variant="ghost"
key={id}
ref={(el) => {
if (el) tabRefs.current.set(id, el);
}}
onClick={() => handleClick(id)}
className={`
shrink-0 px-4 py-3 h-auto text-sm font-medium whitespace-nowrap
border-b-2 rounded-none hover:bg-transparent
${activeId === id
? 'border-brand-purple-vivid text-brand-navy hover:text-brand-navy'
: 'border-transparent text-slate-500 hover:text-slate-700'
}
`}
>
{label}
</Button>
))}
</div>
<PageContainer className="px-0 flex items-center gap-3">
{leftSlot && (
<div className="shrink-0 pl-4 md:pl-6" data-no-print>
{leftSlot}
</div>
)}
<div
ref={navRef}
className="flex-1 min-w-0 flex overflow-x-auto scrollbar-hide"
style={{ scrollbarWidth: 'none', msOverflowStyle: 'none' }}
>
{sections.map(({ id, label }) => (
<Button
type="button"
variant="ghost"
key={id}
ref={(el) => {
if (el) tabRefs.current.set(id, el);
}}
onClick={() => handleClick(id)}
className={`
shrink-0 px-4 py-3 h-auto text-sm font-medium whitespace-nowrap
border-b-2 rounded-none hover:bg-transparent
${activeId === id
? 'border-brand-purple-vivid text-brand-navy hover:text-brand-navy'
: 'border-transparent text-slate-500 hover:text-slate-700'
}
`}
>
{label}
</Button>
))}
</div>
{rightSlot && (
<div className="shrink-0 pr-4 md:pr-6" data-no-print>
{rightSlot}
</div>
)}
</PageContainer>
</nav>
);
}
@@ -1,5 +1,5 @@
import { motion } from 'motion/react';
import { Youtube, Users, Video, Eye, TrendingUp, ExternalLink } from 'lucide-react';
import { Youtube, Users, Video, Eye, TrendingUp, ExternalLink, ListVideo } from 'lucide-react';
import { SectionWrapper } from './ui/SectionWrapper';
import { EmptyState } from './ui/EmptyState';
import { MetricCard } from './ui/MetricCard';
@@ -123,8 +123,9 @@ export default function YouTubeAudit({ data }: YouTubeAuditProps) {
{data.playlists.map((pl) => (
<span
key={pl}
className="rounded-full bg-white/60 backdrop-blur-sm border border-white/40 px-3 py-1 text-sm font-medium text-slate-700"
className="inline-flex items-center gap-1.5 rounded-full bg-rose-50 border border-rose-200 px-3 py-1 text-sm font-medium text-rose-700"
>
<ListVideo size={12} className="text-rose-500" />
{pl}
</span>
))}
@@ -0,0 +1,21 @@
/**
* EmptySection — SectionWrapper + EmptyState 조합.
* 섹션 전체가 비었을 때 사용. 서브섹션은 `EmptyState` 단독 사용.
*/
import { SectionWrapper } from './SectionWrapper';
import { EmptyState } from '@/shared/ui/empty-state';
interface EmptySectionProps {
id: string;
title: string;
subtitle?: string;
hint?: string;
}
export function EmptySection({ id, title, subtitle, hint }: EmptySectionProps) {
return (
<SectionWrapper id={id} title={title} subtitle={subtitle}>
<EmptyState size="lg" hint={hint} />
</SectionWrapper>
);
}
@@ -57,8 +57,9 @@ export function ScoreRing({
strokeLinecap="round"
strokeDasharray={circumference}
initial={{ strokeDashoffset: circumference }}
animate={{ strokeDashoffset }}
transition={{ duration: 1, ease: 'easeOut' }}
whileInView={{ strokeDashoffset }}
viewport={{ once: true, margin: '-50px' }}
transition={{ duration: 1.2, ease: 'easeOut' }}
/>
</svg>
<div className="absolute inset-0 flex items-center justify-center">
@@ -1,4 +1,5 @@
import type { ReactNode } from 'react';
import { PageContainer } from '@/shared/ui/page-container';
interface SectionWrapperProps {
id: string;
@@ -32,7 +33,7 @@ export function SectionWrapper({
{dark && (
<div className="absolute inset-0 bg-[radial-gradient(ellipse_at_top_right,rgba(108,92,231,0.15),transparent_60%)]" />
)}
<div className="relative max-w-7xl mx-auto">
<PageContainer className="relative px-0">
<div className="mb-10">
<h2
className={`
@@ -54,7 +55,7 @@ export function SectionWrapper({
)}
</div>
{children}
</div>
</PageContainer>
</section>
);
}
+5 -5
View File
@@ -311,12 +311,12 @@ export const mockReport: MarketingReport = {
{ platform: 'Naver Cafe', url: 'https://cafe.naver.com/bluectcom2', location: 'Footer' },
],
trackingPixels: [
{ name: 'Facebook Pixel', installed: true, details: 'ID: 299151214739571' },
{ name: 'Facebook Domain Verification', installed: true, details: 'lm854gkic9948c6xk2ti76inryqk65' },
{ name: 'Google Site Verification', installed: true, details: 'A8vo9aOWSvGL5-yFKhbtlHPqJCkH-egNdWVqVd9gKac' },
{ name: 'Naver Site Verification', installed: true, details: 'a8cb4fab1fdf7277c0892eeddf457b5c939349e8' },
{ name: 'Facebook Pixel', installed: true },
{ name: 'Facebook Domain Verification', installed: true },
{ name: 'Google Site Verification', installed: true },
{ name: 'Naver Site Verification', installed: true },
{ name: 'Kakao Pixel', installed: true },
{ name: 'Google Tag Manager', installed: true, details: 'GTM-52RT6DMK' },
{ name: 'Google Tag Manager', installed: true },
],
mainCTA: '전화 + 카카오톡 상담 + 온라인 예약',
},
@@ -202,8 +202,8 @@ export const mockReportBanobagi: MarketingReport = {
{ platform: 'Naver Blog', url: 'https://blog.naver.com/banobagips', location: 'Footer' },
],
trackingPixels: [
{ name: 'Facebook Pixel', installed: true, details: '설치 확인' },
{ name: 'Google Analytics', installed: true, details: 'GA4 추정' },
{ name: 'Facebook Pixel', installed: true },
{ name: 'Google Analytics', installed: true },
{ name: 'Naver Site Verification', installed: true },
],
mainCTA: '전화 상담 + 온라인 예약',
+1 -1
View File
@@ -170,7 +170,7 @@ export const mockReportGrand: MarketingReport = {
{ platform: 'Naver Blog', url: 'https://blog.naver.com/grandprs', location: 'Footer' },
],
trackingPixels: [
{ name: 'Google Analytics', installed: true, details: 'GA4 추정' },
{ name: 'Google Analytics', installed: true },
{ name: 'Naver Site Verification', installed: true },
],
mainCTA: '전화 상담 + 온라인 예약',
+1 -1
View File
@@ -187,7 +187,7 @@ export const mockReportIrum: MarketingReport = {
{ platform: 'Naver Blog', url: 'https://blog.naver.com/seoulips', location: 'Footer' },
],
trackingPixels: [
{ name: 'Google Analytics', installed: true, details: 'GA4 추정' },
{ name: 'Google Analytics', installed: true },
],
mainCTA: '전화 상담 + 카카오톡',
},
+4 -4
View File
@@ -211,10 +211,10 @@ export const mockReportO2O: MarketingReport = {
{ platform: 'TikTok', url: 'https://www.tiktok.com/@o2oclinic', location: 'Footer' },
],
trackingPixels: [
{ name: 'Google Analytics 4', installed: true, details: 'GA4 + GTM 정상 운영' },
{ name: 'Meta Pixel', installed: true, details: 'Facebook/Instagram 광고 픽셀 설치 완료' },
{ name: 'Naver Analytics', installed: true, details: '네이버 검색광고 전환 추적' },
{ name: 'TikTok Pixel', installed: false, details: '미설치 — 도입 권장' },
{ name: 'Google Analytics 4', installed: true },
{ name: 'Meta Pixel', installed: true },
{ name: 'Naver Analytics', installed: true },
{ name: 'TikTok Pixel', installed: false },
],
mainCTA: '온라인 상담 예약 + 카카오톡 + WhatsApp (글로벌)',
},
+1 -1
View File
@@ -171,7 +171,7 @@ export const mockReportTs: MarketingReport = {
{ platform: 'Naver Blog', url: 'https://blog.naver.com/tsprs', location: 'Footer' },
],
trackingPixels: [
{ name: 'Google Analytics', installed: true, details: 'GA4 추정' },
{ name: 'Google Analytics', installed: true },
{ name: 'Naver Site Verification', installed: true },
],
mainCTA: '전화 상담 + 카카오톡 상담',
@@ -187,8 +187,8 @@ export const mockReportWonjin: MarketingReport = {
{ platform: 'Naver Blog', url: 'https://blog.naver.com/popokpop', location: 'Footer' },
],
trackingPixels: [
{ name: 'Facebook Pixel', installed: true, details: '설치 확인 (추정)' },
{ name: 'Google Analytics', installed: true, details: 'GA4 추정' },
{ name: 'Facebook Pixel', installed: true },
{ name: 'Google Analytics', installed: true },
],
mainCTA: '전화 상담 + 다국어 온라인 예약',
},
+248
View File
@@ -0,0 +1,248 @@
import { useCallback } from 'react';
import type { MarketingReport } from '@/features/report/types/report';
/**
* 리포트의 표 데이터 전체를 단일 CSV로 내보내는 훅.
* 섹션마다 `=== Section Title ===` 헤더로 구분.
* Excel/Numbers에서 한글이 깨지지 않도록 UTF-8 BOM 포함.
*/
type Cell = string | number | null | undefined;
type Row = Cell[];
type Section = { title: string; rows: Row[] };
function escapeCell(value: Cell): string {
const s = String(value ?? '');
if (/[",\n\r]/.test(s)) {
return `"${s.replace(/"/g, '""')}"`;
}
return s;
}
function buildReportCsv(report: MarketingReport): string {
const sections: Section[] = [];
// ─── KPI Dashboard ───
if (report.kpiDashboard?.length) {
sections.push({
title: 'KPI Dashboard',
rows: [
['Metric', 'Current', '3-Month Target', '12-Month Target'],
...report.kpiDashboard.map((m) => [m.metric, m.current, m.target3Month, m.target12Month]),
],
});
}
// ─── Channel Scores ───
if (report.channelScores?.length) {
sections.push({
title: 'Channel Scores',
rows: [
['Channel', 'Score', 'Max Score', 'Status', 'Headline'],
...report.channelScores.map((c) => [c.channel, c.score, c.maxScore, c.status, c.headline]),
],
});
}
// ─── Problem Diagnosis ───
if (report.problemDiagnosis?.length) {
sections.push({
title: 'Problem Diagnosis',
rows: [
['Category', 'Detail', 'Severity'],
...report.problemDiagnosis.map((d) => [d.category, d.detail, d.severity]),
],
});
}
// ─── Roadmap (월별 → 태스크 단위로 풀어 펼침) ───
if (report.roadmap?.length) {
const rows: Row[] = [['Month', 'Title', 'Subtitle', 'Task', 'Completed']];
report.roadmap.forEach((m) => {
if (m.tasks.length === 0) {
rows.push([m.month, m.title, m.subtitle, '', '']);
return;
}
m.tasks.forEach((t, i) => {
rows.push([
i === 0 ? m.month : '',
i === 0 ? m.title : '',
i === 0 ? m.subtitle : '',
t.task,
t.completed ? 'Y' : 'N',
]);
});
});
sections.push({ title: 'Roadmap', rows });
}
// ─── Transformation ───
const t = report.transformation;
const asIsToBe = (title: string, items: { area: string; asIs: string; toBe: string }[]) => {
if (!items?.length) return;
sections.push({
title,
rows: [['Area', 'As-Is', 'To-Be'], ...items.map((i) => [i.area, i.asIs, i.toBe])],
});
};
asIsToBe('Transformation: Brand Identity', t?.brandIdentity ?? []);
asIsToBe('Transformation: Content Strategy', t?.contentStrategy ?? []);
asIsToBe('Transformation: Website Improvements', t?.websiteImprovements ?? []);
if (t?.newChannelProposals?.length) {
sections.push({
title: 'Transformation: New Channel Proposals',
rows: [
['Channel', 'Priority', 'Rationale'],
...t.newChannelProposals.map((p) => [p.channel, p.priority, p.rationale]),
],
});
}
if (t?.platformStrategies?.length) {
const rows: Row[] = [['Platform', 'Current Metric', 'Target Metric', 'Strategy', 'Detail']];
t.platformStrategies.forEach((p) => {
if (p.strategies.length === 0) {
rows.push([p.platform, p.currentMetric, p.targetMetric, '', '']);
return;
}
p.strategies.forEach((s, i) => {
rows.push([
i === 0 ? p.platform : '',
i === 0 ? p.currentMetric : '',
i === 0 ? p.targetMetric : '',
s.strategy,
s.detail,
]);
});
});
sections.push({ title: 'Transformation: Platform Strategies', rows });
}
// ─── Channel diagnoses ───
const diagSection = (title: string, items: { category: string; detail: string; severity: string }[]) => {
if (!items?.length) return;
sections.push({
title,
rows: [['Category', 'Detail', 'Severity'], ...items.map((d) => [d.category, d.detail, d.severity])],
});
};
diagSection('YouTube Diagnosis', report.youtubeAudit?.diagnosis ?? []);
diagSection('Instagram Diagnosis', report.instagramAudit?.diagnosis ?? []);
diagSection('Facebook Diagnosis', report.facebookAudit?.diagnosis ?? []);
// ─── Facebook Brand Inconsistencies (채널별 값으로 풀어 펼침) ───
if (report.facebookAudit?.brandInconsistencies?.length) {
const rows: Row[] = [['Field', 'Channel', 'Value', 'Correct', 'Impact', 'Recommendation']];
report.facebookAudit.brandInconsistencies.forEach((b) => {
b.values.forEach((v, i) => {
rows.push([
i === 0 ? b.field : '',
v.channel,
v.value,
v.isCorrect ? 'Y' : 'N',
i === 0 ? b.impact : '',
i === 0 ? b.recommendation : '',
]);
});
});
sections.push({ title: 'Facebook Brand Inconsistencies', rows });
}
// ─── Instagram Accounts (요약 컬럼만) ───
if (report.instagramAudit?.accounts?.length) {
sections.push({
title: 'Instagram Accounts',
rows: [
['Handle', 'Language', 'Label', 'Followers', 'Following', 'Posts', 'Reels', 'Category'],
...report.instagramAudit.accounts.map((a) => [
a.handle,
a.language,
a.label,
a.followers,
a.following,
a.posts,
a.reelsCount,
a.category,
]),
],
});
}
// ─── Facebook Pages (요약 컬럼만) ───
if (report.facebookAudit?.pages?.length) {
sections.push({
title: 'Facebook Pages',
rows: [
['Page Name', 'Language', 'Label', 'Followers', 'Reviews', 'Category', 'URL'],
...report.facebookAudit.pages.map((p) => [
p.pageName,
p.language,
p.label,
p.followers,
p.reviews,
p.category,
p.url,
]),
],
});
}
// ─── Other Channels ───
if (report.otherChannels?.length) {
sections.push({
title: 'Other Channels',
rows: [
['Name', 'Status', 'Details', 'URL'],
...report.otherChannels.map((c) => [c.name, c.status, c.details, c.url ?? '']),
],
});
}
// ─── Website Audit (단일 행 요약) ───
if (report.websiteAudit) {
const w = report.websiteAudit;
sections.push({
title: 'Website Audit',
rows: [
['Primary Domain', 'Main CTA', 'SNS Links On Site'],
[w.primaryDomain, w.mainCTA, w.snsLinksOnSite ? 'Y' : 'N'],
],
});
if (w.trackingPixels?.length) {
sections.push({
title: 'Website: Tracking Pixels',
rows: [['Name', 'Installed'], ...w.trackingPixels.map((p) => [p.name, p.installed ? 'Y' : 'N'])],
});
}
}
// ─── 출력 조립: 섹션 사이 공백 행 한 줄 ───
const lines: string[] = [];
sections.forEach((sec, idx) => {
if (idx > 0) lines.push('');
lines.push(`=== ${sec.title} ===`);
sec.rows.forEach((row) => lines.push(row.map(escapeCell).join(',')));
});
return lines.join('\r\n');
}
export function useExportCSV() {
const exportReportCSV = useCallback((filename: string, report: MarketingReport) => {
const csv = '' + buildReportCsv(report); // Excel 한글 깨짐 방지 BOM
const blob = new Blob([csv], { type: 'text/csv;charset=utf-8' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `${filename}.csv`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
}, []);
return { exportReportCSV };
}
+32 -257
View File
@@ -1,284 +1,59 @@
import { useState, useCallback } from 'react';
/**
* PDF Export — 블록 기반 전략.
* Chrome(브라우저) 네이티브 인쇄 다이얼로그로 PDF 저장.
*
* 각 섹션은 페이지 간에 분할되지 않는 원자적 서브 블록으로 분리됨.
* framer-motion 애니메이션이 있는 다크 섹션은 별도 처리 필요:
* 모든 섹션을 뷰포트에 스크롤해서 `whileInView`를 트리거한 뒤,
* html2canvas 캡처 전에 인라인 opacity/transform을 최종 상태로 강제 설정.
* 레이아웃·색상·페이지 분할은 `@media print` CSS가 담당 (`src/styles/custom.css`).
* 호출 직전 framer-motion `whileInView` 잔여 요소(opacity:0/transform)를
* 최종 상태로 강제하여 사용자가 보지 못한 섹션이 빈 페이지로 인쇄되는 것을 방지.
*/
function isDarkSection(section: HTMLElement): boolean {
const bg = window.getComputedStyle(section).backgroundColor;
if (!bg || bg === 'rgba(0, 0, 0, 0)' || bg === 'transparent') return false;
// rgb(r, g, b) 파싱 — 휘도가 낮으면 다크로 판단
const match = bg.match(/(\d+),\s*(\d+),\s*(\d+)/);
if (!match) return section.classList.contains('bg-[#0A1128]');
const [, r, g, b] = match.map(Number);
return (r * 0.299 + g * 0.587 + b * 0.114) < 50;
}
function forceMotionFinalState(): () => void {
const root =
(document.querySelector('[data-report-content]') as HTMLElement | null) ||
(document.querySelector('[data-plan-content]') as HTMLElement | null);
if (!root) return () => {};
function collectSubBlocks(section: HTMLElement): HTMLElement[] {
// 다크 섹션은 통째로 캡처 — 서브 블록으로 나누면 다크 배경이 사라짐
if (isDarkSection(section)) return [section];
const saved: { el: HTMLElement; opacity: string; transform: string }[] = [];
if (section.offsetHeight <= 900) return [section];
const children = Array.from(section.children) as HTMLElement[];
if (children.length <= 1) return [section];
const blocks: HTMLElement[] = [];
for (const child of children) {
if (child.offsetHeight === 0 || child.offsetWidth === 0) continue;
blocks.push(child);
}
return blocks.length > 0 ? blocks : [section];
}
/**
* 모든 섹션을 스크롤하여 `whileInView` 애니메이션을 트리거한 뒤,
* 안정화될 때까지 대기. 스냅샷 캡처 전에 framer-motion이 최종
* 인라인 스타일을 적용하도록 보장.
*/
async function triggerAllAnimations(contentEl: HTMLElement): Promise<void> {
const sections = Array.from(contentEl.children) as HTMLElement[];
for (const section of sections) {
section.scrollIntoView({ behavior: 'instant' as ScrollBehavior });
// framer-motion이 intersection을 감지하고 스타일을 적용할 시간 부여
await new Promise((r) => setTimeout(r, 80));
// 중첩된 whileInView를 위해 서브 자식 요소도 뷰포트로 스크롤
const motionChildren = section.querySelectorAll('[style]');
for (let i = 0; i < Math.min(motionChildren.length, 20); i++) {
(motionChildren[i] as HTMLElement).scrollIntoView({ behavior: 'instant' as ScrollBehavior });
await new Promise((r) => setTimeout(r, 30));
}
}
// 최상단으로 스크롤하고 모두 안정화될 때까지 대기
window.scrollTo(0, 0);
await new Promise((r) => setTimeout(r, 200));
}
/**
* 모든 요소를 완전히 보이도록 강제 — opacity 1, transform 없음.
* whileInView가 도달하지 못한 잔여 요소를 처리.
*/
function forceVisible(contentEl: HTMLElement): (() => void) {
document.documentElement.style.setProperty('--motion-duration', '0s');
const saved: { el: HTMLElement; cssText: string }[] = [];
contentEl.querySelectorAll('*').forEach((node) => {
const el = node as HTMLElement;
root.querySelectorAll<HTMLElement>('*').forEach((el) => {
const s = el.style;
const opacityOff = s.opacity !== '' && parseFloat(s.opacity) < 1;
const transformOn = s.transform !== '' && s.transform !== 'none';
if (!opacityOff && !transformOn) return;
// 인라인과 computed 모두 확인
const needsFix =
(s.opacity !== '' && s.opacity !== '1') ||
(s.transform !== '' && s.transform !== 'none') ||
s.visibility === 'hidden';
if (needsFix) {
saved.push({ el, cssText: s.cssText });
s.opacity = '1';
s.transform = 'none';
s.visibility = 'visible';
}
});
// 2차 패스: computed opacity < 1 처리 (motion이 클래스로 설정했을 수도)
contentEl.querySelectorAll('*').forEach((node) => {
const el = node as HTMLElement;
const computed = window.getComputedStyle(el);
if (parseFloat(computed.opacity) < 0.99) {
if (!saved.find((s) => s.el === el)) {
saved.push({ el, cssText: el.style.cssText });
}
el.style.opacity = '1';
el.style.transform = 'none';
}
saved.push({ el, opacity: s.opacity, transform: s.transform });
if (opacityOff) s.opacity = '1';
if (transformOn) s.transform = 'none';
});
return () => {
saved.forEach(({ el, cssText }) => {
el.style.cssText = cssText;
saved.forEach(({ el, opacity, transform }) => {
el.style.opacity = opacity;
el.style.transform = transform;
});
document.documentElement.style.removeProperty('--motion-duration');
};
}
/**
* Export용 CSS 오버라이드: overflow 해제, 클리핑 방지.
*/
function addExportCSS(): (() => void) {
const style = document.createElement('style');
style.id = 'pdf-export-overrides';
style.textContent = `
[data-report-content] .overflow-x-auto,
[data-plan-content] .overflow-x-auto {
overflow: visible !important;
flex-wrap: wrap !important;
}
[data-report-content] .scrollbar-thin,
[data-plan-content] .scrollbar-thin {
overflow: visible !important;
}
[data-report-content] .shrink-0,
[data-plan-content] .shrink-0 {
flex-shrink: 1 !important;
min-width: 0 !important;
}
`;
document.head.appendChild(style);
return () => style.remove();
}
export function useExportPDF() {
const [isExporting, setIsExporting] = useState(false);
const exportPDF = useCallback(async (filename = 'INFINITH_Marketing_Intelligence_Report') => {
const exportPDF = useCallback((filename = 'INFINITH_Marketing_Intelligence_Report') => {
setIsExporting(true);
try {
const [{ default: html2canvas }, { jsPDF }] = await Promise.all([
import('html2canvas-pro'),
import('jspdf'),
]);
const originalTitle = document.title;
document.title = filename;
const restoreMotion = forceMotionFinalState();
const contentEl =
(document.querySelector('[data-report-content]') as HTMLElement) ||
(document.querySelector('[data-plan-content]') as HTMLElement);
if (!contentEl) throw new Error('Report content element not found');
// Step 1: whileInView 애니메이션 트리거를 위해 모든 섹션 스크롤
await triggerAllAnimations(contentEl);
// Step 2: 모든 요소를 강제로 visible 처리 (잔여 요소 처리)
const restoreVisible = forceVisible(contentEl);
// Step 3: CSS 오버라이드
const restoreCSS = addExportCSS();
// Step 4: UI 요소 숨기기
const hideSelectors = [
'[data-report-nav]',
'[data-plan-nav]',
'nav',
'[data-cta-card]',
'[data-no-print]',
];
const hiddenEls: { el: HTMLElement; display: string }[] = [];
hideSelectors.forEach((sel) => {
document.querySelectorAll(sel).forEach((el) => {
const htmlEl = el as HTMLElement;
hiddenEls.push({ el: htmlEl, display: htmlEl.style.display });
htmlEl.style.display = 'none';
});
});
await new Promise((r) => setTimeout(r, 150));
// Step 5: PDF 생성
const pdf = new jsPDF('p', 'mm', 'a4');
const pageWidth = 210;
const pageHeight = 297;
const margin = 8;
const usableWidth = pageWidth - margin * 2;
const footerSpace = 10;
const maxContentY = pageHeight - margin - footerSpace;
let currentY = margin;
const sections = Array.from(contentEl.children) as HTMLElement[];
for (const section of sections) {
if (section.offsetHeight === 0 || section.offsetWidth === 0) continue;
if (window.getComputedStyle(section).display === 'none') continue;
const blocks = collectSubBlocks(section);
for (const block of blocks) {
if (block.offsetHeight === 0) continue;
const canvas = await html2canvas(block, {
scale: 2,
useCORS: true,
logging: false,
backgroundColor: null,
windowWidth: 1280,
removeContainer: true,
});
const blockHeightMM = (canvas.height * usableWidth) / canvas.width;
// 블록이 안 들어가면 새 페이지
if (currentY + blockHeightMM > maxContentY && currentY > margin + 5) {
pdf.addPage();
currentY = margin;
}
// 긴 블록: 페이지 단위로 슬라이싱
if (blockHeightMM > maxContentY - margin) {
const pxPerMM = canvas.width / usableWidth;
let srcY = 0;
let remainPx = canvas.height;
let isFirst = true;
while (remainPx > 0) {
if (!isFirst) { pdf.addPage(); currentY = margin; }
isFirst = false;
const availPx = (maxContentY - currentY) * pxPerMM;
const sliceH = Math.min(remainPx, availPx);
const sliceCanvas = document.createElement('canvas');
sliceCanvas.width = canvas.width;
sliceCanvas.height = Math.ceil(sliceH);
const ctx = sliceCanvas.getContext('2d');
if (ctx) {
ctx.drawImage(canvas, 0, srcY, canvas.width, Math.ceil(sliceH), 0, 0, canvas.width, Math.ceil(sliceH));
}
const sliceMM = sliceH / pxPerMM;
pdf.addImage(sliceCanvas.toDataURL('image/jpeg', 0.9), 'JPEG', margin, currentY, usableWidth, sliceMM);
currentY += sliceMM;
srcY += sliceH;
remainPx -= sliceH;
}
} else {
pdf.addImage(canvas.toDataURL('image/jpeg', 0.9), 'JPEG', margin, currentY, usableWidth, blockHeightMM);
currentY += blockHeightMM;
}
}
currentY += 2; // 섹션 간 여백
}
// Step 6: 복원
hiddenEls.forEach(({ el, display }) => { el.style.display = display; });
restoreCSS();
restoreVisible();
// Step 7: 푸터
const totalPages = pdf.getNumberOfPages();
const footerLabel = filename.includes('Plan')
? 'INFINITH Marketing Plan'
: 'INFINITH Marketing Intelligence Report';
for (let i = 1; i <= totalPages; i++) {
pdf.setPage(i);
pdf.setFontSize(7);
pdf.setTextColor(180);
pdf.text(`${footerLabel} | Page ${i} / ${totalPages}`, pageWidth / 2, pageHeight - 5, { align: 'center' });
}
pdf.save(`${filename}.pdf`);
} catch (err) {
console.error('PDF export failed:', err);
} finally {
const cleanup = () => {
restoreMotion();
document.title = originalTitle;
setIsExporting(false);
}
window.removeEventListener('afterprint', cleanup);
};
window.addEventListener('afterprint', cleanup);
window.print();
}, []);
return { exportPDF, isExporting };
@@ -0,0 +1,66 @@
/**
* useReportPageData — Guest / User 리포트 페이지가 공통으로 쓰는 데이터 훅.
*
* 단순히 기존 `useReport` + `useEnrichment` 조합을 한 곳에 묶어
* 페이지 wrapper 두 곳에서 동일한 코드를 반복하지 않도록 합니다.
*/
import { useMemo } from 'react';
import { useLocation } from 'react-router';
import type { MarketingReport } from '@/features/report/types/report';
import { useReport } from '@/features/report/hooks/useReport';
import { useEnrichment } from '@/features/channels/hooks/useEnrichment';
interface UseReportPageDataResult {
data: MarketingReport | null;
isLoading: boolean;
error: string | null;
enrichStatus: ReturnType<typeof useEnrichment>['status'];
}
export function useReportPageData(id: string | undefined): UseReportPageDataResult {
const location = useLocation();
const {
data: baseData,
isLoading,
error,
isEnriched,
socialHandles: dbSocialHandles,
} = useReport(id);
const enrichmentParams = useMemo(() => {
if (!baseData || isEnriched) return null;
const state = location.state as Record<string, unknown> | undefined;
const metadata = state?.metadata as Record<string, unknown> | undefined;
const stateSocialHandles = metadata?.socialHandles as Record<string, string | null> | undefined;
const handles = stateSocialHandles || dbSocialHandles;
const igHandles: string[] = Array.isArray(handles?.instagram)
? (handles.instagram.filter(Boolean) as string[])
: handles?.instagram
? [handles.instagram as string]
: [];
const ytHandle = handles?.youtube || baseData.youtubeAudit?.handle || undefined;
const fbHandle = handles?.facebook || undefined;
return {
reportId: baseData.id,
clinicName: baseData.clinicSnapshot.name,
instagramHandles: igHandles.length > 0 ? igHandles : undefined,
youtubeChannelId: ytHandle || undefined,
facebookHandle: fbHandle as string | undefined,
address: baseData.clinicSnapshot.location || undefined,
};
}, [baseData, isEnriched, dbSocialHandles, location.state]);
const { status: enrichStatus, enrichedReport } = useEnrichment(baseData, enrichmentParams);
return {
data: enrichedReport || baseData,
isLoading,
error,
enrichStatus,
};
}
@@ -0,0 +1,104 @@
/**
* GuestReportPage — `/report/:id`
*
* 손님(랜딩에서 분석을 실행한 비계약 방문자)이 보는 리포트 화면.
* 본문은 UserReportPage 와 동일하나, 하단에 도입 문의 CTA가 추가되고
* 워크스페이스용 액션바는 노출되지 않습니다.
*/
import { Link, useParams } from 'react-router';
import { ArrowRight, Sparkles } from 'lucide-react';
import { useReportPageData } from '../hooks/useReportPageData';
import { ReportNav } from '../components/ReportNav';
import { ScreenshotProvider } from '../stores/ScreenshotContext';
import { REPORT_SECTIONS } from '@/shared/constants/reportSections';
import { buildContactMailto } from '@/shared/lib/contact';
import ReportBody from '../components/ReportBody';
import { DownloadMenuButton } from '../components/DownloadMenuButton';
export default function GuestReportPage() {
const { id } = useParams<{ id: string }>();
const { data, isLoading, error, enrichStatus } = useReportPageData(id);
if (isLoading) {
return (
<div className="min-h-screen flex items-center justify-center pt-20">
<div className="flex flex-col items-center gap-4">
<div className="w-10 h-10 border-4 border-[#6C5CE7] border-t-transparent rounded-full animate-spin" />
<p className="text-slate-500 text-sm">리포트를 불러오는 중...</p>
</div>
</div>
);
}
if (error || !data) {
return (
<div className="min-h-screen flex items-center justify-center pt-20">
<div className="text-center">
<p className="text-[#7C3A4B] font-medium mb-2">오류가 발생했습니다</p>
<p className="text-slate-500 text-sm">{error ?? '리포트를 찾을 수 없습니다.'}</p>
</div>
</div>
);
}
return (
<ScreenshotProvider screenshots={data.screenshots ?? []}>
<div className="pt-20">
<ReportNav
sections={REPORT_SECTIONS}
rightSlot={
<div className="flex items-center gap-2">
<DownloadMenuButton
filename={`${data.clinicSnapshot.name}_Marketing_Intelligence_Report`}
report={data}
/>
<Link
to={`/plan/${id}`}
className="inline-flex items-center gap-1.5 px-4 py-2 rounded-full text-xs font-semibold text-brand-purple bg-brand-tint-purple/60 border border-brand-tint-lavender hover:bg-brand-tint-purple transition-colors"
>
<Sparkles size={12} />
마케팅 기획 보기
<ArrowRight size={11} className="opacity-80" />
</Link>
</div>
}
/>
{enrichStatus === 'loading' && (
<div className="fixed bottom-6 right-6 z-50 flex items-center gap-3 px-4 py-3 bg-white rounded-xl shadow-[3px_4px_12px_rgba(0,0,0,0.06)] border border-slate-100">
<div className="w-4 h-4 border-2 border-[#6C5CE7] border-t-transparent rounded-full animate-spin" />
<span className="text-xs text-slate-500">채널 데이터 보강 중...</span>
</div>
)}
<ReportBody data={data} />
{/* Guest 전용 — 도입 문의 CTA */}
<section className="px-6 py-16 bg-gradient-to-b from-white to-[#F3F0FF]/30">
<div className="max-w-3xl mx-auto rounded-3xl bg-[#0A1128] p-10 text-center relative overflow-hidden">
<div className="absolute top-0 right-0 w-[300px] h-[300px] rounded-full bg-[#7B2D8E]/20 blur-[120px]" aria-hidden />
<div className="relative">
<p className="text-xs uppercase tracking-wider text-purple-300/70 mb-3">
INFINITH 도입 안내
</p>
<h2 className="font-serif text-2xl md:text-3xl font-bold text-white mb-3 leading-snug">
이 리포트의 다음 단계 — 마케팅 기획
</h2>
<p className="text-sm text-purple-200/70 break-keep leading-relaxed mb-7 max-w-xl mx-auto">
계약 병원 전용 워크스페이스에서 본 분석을 기반으로 콘텐츠 캘린더,
자산 관리, 워크플로우 추적까지 한 곳에서 운영할 수 있습니다.
</p>
<a
href={buildContactMailto(`도입 문의 — ${data.clinicSnapshot.name} 리포트`)}
className="inline-flex items-center gap-2 px-6 py-3 text-sm font-semibold text-[#0A1128] bg-white rounded-full shadow-sm hover:opacity-90 transition-all"
>
도입 문의하기
<ArrowRight className="w-4 h-4" />
</a>
</div>
</div>
</section>
</div>
</ScreenshotProvider>
);
}
-144
View File
@@ -1,144 +0,0 @@
import { useMemo } from 'react';
import { useParams, useLocation } from 'react-router';
import { useReport } from '../hooks/useReport';
import { useEnrichment } from '@/features/channels/hooks/useEnrichment';
import { ReportNav } from '@/features/report/components/ReportNav';
import { ScreenshotProvider } from '@/features/report/stores/ScreenshotContext';
import { REPORT_SECTIONS } from '@/shared/constants/reportSections';
import { SectionErrorBoundary } from '@/features/report/components/ui/SectionErrorBoundary';
import ReportHeader from '@/features/report/components/ReportHeader';
import ClinicSnapshot from '@/features/report/components/ClinicSnapshot';
import ChannelOverview from '@/features/report/components/ChannelOverview';
import YouTubeAudit from '@/features/report/components/YouTubeAudit';
import InstagramAudit from '@/features/report/components/InstagramAudit';
import FacebookAudit from '@/features/report/components/FacebookAudit';
import OtherChannels from '@/features/report/components/OtherChannels';
import ProblemDiagnosis from '@/features/report/components/ProblemDiagnosis';
import TransformationProposal from '@/features/report/components/TransformationProposal';
import RoadmapTimeline from '@/features/report/components/RoadmapTimeline';
import KPIDashboard from '@/features/report/components/KPIDashboard';
export default function ReportPage() {
const { id } = useParams<{ id: string }>();
const location = useLocation();
const {
data: baseData,
isLoading,
error,
isEnriched,
socialHandles: dbSocialHandles,
} = useReport(id);
// 보강 파라미터 생성 — 이미 보강된 경우(DB 데이터) 스킵
const enrichmentParams = useMemo(() => {
if (!baseData || isEnriched) return null;
// 우선순위: location.state socialHandles > DB socialHandles > 변환된 데이터
const state = location.state as Record<string, unknown> | undefined;
const metadata = state?.metadata as Record<string, unknown> | undefined;
const stateSocialHandles = metadata?.socialHandles as Record<string, string | null> | undefined;
const handles = stateSocialHandles || dbSocialHandles;
// Instagram: 다중 계정(배열) 또는 단일 핸들 모두 지원
const igHandles: string[] = Array.isArray(handles?.instagram)
? handles.instagram.filter(Boolean) as string[]
: handles?.instagram ? [handles.instagram as string] : [];
const ytHandle =
handles?.youtube ||
baseData.youtubeAudit?.handle ||
undefined;
const fbHandle = handles?.facebook || undefined;
return {
reportId: baseData.id,
clinicName: baseData.clinicSnapshot.name,
instagramHandles: igHandles.length > 0 ? igHandles : undefined,
youtubeChannelId: ytHandle || undefined,
facebookHandle: fbHandle as string | undefined,
address: baseData.clinicSnapshot.location || undefined,
};
}, [baseData, isEnriched, dbSocialHandles, location.state]);
const { status: enrichStatus, enrichedReport } = useEnrichment(baseData, enrichmentParams);
// 보강 데이터가 있으면 사용, 없으면 베이스 데이터 사용
const data = enrichedReport || baseData;
if (isLoading) {
return (
<div className="min-h-screen flex items-center justify-center pt-20">
<div className="flex flex-col items-center gap-4">
<div className="w-10 h-10 border-4 border-[#6C5CE7] border-t-transparent rounded-full animate-spin" />
<p className="text-slate-500 text-sm">리포트를 불러오는 중...</p>
</div>
</div>
);
}
if (error || !data) {
return (
<div className="min-h-screen flex items-center justify-center pt-20">
<div className="text-center">
<p className="text-[#7C3A4B] font-medium mb-2">오류가 발생했습니다</p>
<p className="text-slate-500 text-sm">{error ?? '리포트를 찾을 수 없습니다.'}</p>
</div>
</div>
);
}
return (
<ScreenshotProvider screenshots={data.screenshots ?? []}>
<div className="pt-20">
<ReportNav sections={REPORT_SECTIONS} />
{/* Enrichment status indicator */}
{enrichStatus === 'loading' && (
<div className="fixed bottom-6 right-6 z-50 flex items-center gap-3 px-4 py-3 bg-white rounded-xl shadow-[3px_4px_12px_rgba(0,0,0,0.06)] border border-slate-100">
<div className="w-4 h-4 border-2 border-[#6C5CE7] border-t-transparent rounded-full animate-spin" />
<span className="text-xs text-slate-500">채널 데이터 보강 중...</span>
</div>
)}
<div data-report-content>
<ReportHeader
overallScore={data.overallScore}
clinicName={data.clinicSnapshot.name}
clinicNameEn={data.clinicSnapshot.nameEn}
targetUrl={data.targetUrl}
date={data.createdAt}
location={data.clinicSnapshot.location}
logoImage={data.clinicSnapshot.logoImages?.horizontal}
brandColors={data.clinicSnapshot.brandColors}
/>
<SectionErrorBoundary><ClinicSnapshot data={data.clinicSnapshot} /></SectionErrorBoundary>
<SectionErrorBoundary><ChannelOverview channels={data.channelScores} /></SectionErrorBoundary>
<SectionErrorBoundary><YouTubeAudit data={data.youtubeAudit} /></SectionErrorBoundary>
<SectionErrorBoundary><InstagramAudit data={data.instagramAudit} /></SectionErrorBoundary>
<SectionErrorBoundary><FacebookAudit data={data.facebookAudit} /></SectionErrorBoundary>
<SectionErrorBoundary><OtherChannels
channels={data.otherChannels}
website={data.websiteAudit}
/></SectionErrorBoundary>
<SectionErrorBoundary><ProblemDiagnosis diagnosis={data.problemDiagnosis} /></SectionErrorBoundary>
<SectionErrorBoundary><TransformationProposal data={data.transformation} /></SectionErrorBoundary>
<SectionErrorBoundary><RoadmapTimeline months={data.roadmap} /></SectionErrorBoundary>
<SectionErrorBoundary><KPIDashboard metrics={data.kpiDashboard} clinicName={data.clinicSnapshot.name} /></SectionErrorBoundary>
</div>
</div>
</ScreenshotProvider>
);
}
@@ -0,0 +1,93 @@
/**
* UserReportPage — `/clinics/:clinicId/report/:id`
*
* 계약된 병원 유저가 워크스페이스 안에서 보는 리포트 화면.
* 본문은 GuestReportPage 와 동일하지만:
* - 상단에 워크스페이스 액션바 (워크스페이스로 돌아가기, 플랜 생성, 다시 분석)
* - 하단의 도입 문의 CTA 없음
*/
import { Link, useParams } from 'react-router';
import { ArrowLeft, Sparkles, RefreshCw } from 'lucide-react';
import { useReportPageData } from '../hooks/useReportPageData';
import { ReportNav } from '../components/ReportNav';
import { ScreenshotProvider } from '../stores/ScreenshotContext';
import { REPORT_SECTIONS } from '@/shared/constants/reportSections';
import ReportBody from '../components/ReportBody';
import { DownloadMenuButton } from '../components/DownloadMenuButton';
export default function UserReportPage() {
const { clinicId, id } = useParams<{ clinicId: string; id: string }>();
const { data, isLoading, error, enrichStatus } = useReportPageData(id);
if (isLoading) {
return (
<div className="min-h-screen flex items-center justify-center pt-20">
<div className="flex flex-col items-center gap-4">
<div className="w-10 h-10 border-4 border-[#6C5CE7] border-t-transparent rounded-full animate-spin" />
<p className="text-slate-500 text-sm">리포트를 불러오는 중...</p>
</div>
</div>
);
}
if (error || !data) {
return (
<div className="min-h-screen flex items-center justify-center pt-20">
<div className="text-center">
<p className="text-[#7C3A4B] font-medium mb-2">오류가 발생했습니다</p>
<p className="text-slate-500 text-sm">{error ?? '리포트를 찾을 수 없습니다.'}</p>
</div>
</div>
);
}
return (
<ScreenshotProvider screenshots={data.screenshots ?? []}>
<div className="pt-20">
<ReportNav
sections={REPORT_SECTIONS}
leftSlot={
<Link
to={`/clinics/${clinicId}`}
className="inline-flex items-center gap-1.5 text-xs font-medium text-slate-500 hover:text-primary-900 transition-colors"
>
<ArrowLeft size={14} />
워크스페이스로
</Link>
}
rightSlot={
<div className="flex items-center gap-2">
<DownloadMenuButton
filename={`${data.clinicSnapshot.name}_Marketing_Intelligence_Report`}
report={data}
/>
<Link
to={`/report/loading`}
className="inline-flex items-center gap-1.5 px-3.5 py-2 rounded-full text-xs font-medium text-slate-600 bg-slate-50 border border-slate-200 hover:bg-white hover:border-slate-300 transition-all"
>
<RefreshCw size={12} />
다시 분석
</Link>
<Link
to={`/clinics/${clinicId}/plan/${id}`}
className="inline-flex items-center gap-1.5 px-4 py-2 rounded-full text-xs font-semibold text-white bg-gradient-to-r from-[#4F1DA1] to-[#021341] shadow-sm hover:opacity-90 transition-all"
>
<Sparkles size={12} />
마케팅 기획 보기
</Link>
</div>
}
/>
{enrichStatus === 'loading' && (
<div className="fixed bottom-6 right-6 z-50 flex items-center gap-3 px-4 py-3 bg-white rounded-xl shadow-[3px_4px_12px_rgba(0,0,0,0.06)] border border-slate-100">
<div className="w-4 h-4 border-2 border-[#6C5CE7] border-t-transparent rounded-full animate-spin" />
<span className="text-xs text-slate-500">채널 데이터 보강 중...</span>
</div>
)}
<ReportBody data={data} />
</div>
</ScreenshotProvider>
);
}
+3 -2
View File
@@ -1,11 +1,12 @@
import { lazy } from 'react'
import type { RouteObject } from 'react-router'
const ReportPage = lazy(() => import('./pages/ReportPage'))
const GuestReportPage = lazy(() => import('./pages/GuestReportPage'))
const AnalysisLoadingPage = lazy(() => import('./pages/AnalysisLoadingPage'))
export const reportRoutes: RouteObject[] = [
{ path: 'report/loading', element: <AnalysisLoadingPage /> },
{ path: 'report/loading/:reportId', element: <AnalysisLoadingPage /> },
{ path: 'report/:id', element: <ReportPage /> },
// 손님(랜딩→분석) 흐름. 유저 워크스페이스 경로는 features/clinics/routes.tsx 참조.
{ path: 'report/:id', element: <GuestReportPage /> },
]
-1
View File
@@ -166,7 +166,6 @@ export interface OtherChannel {
export interface TrackingPixel {
name: string;
installed: boolean;
details?: string;
}
export interface WebsiteAudit {