이름: solution/front → solution/frontend
`backend` 옆에 `front` 가 있을 이유가 없었다. negosium 의 negodata/front 를 그대로 베꼈고 그게 왜 front 인지는 따져보지 않았다 — 근거 없이 들여온 이름이라 바로잡는다. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019uYhHQdssRubirPirrdJJC
This commit is contained in:
1 parent
06f6438d9b
commit
c85c577349
480 files changed
+22
-22
No files matched your search
@@ -0,0 +1,89 @@
|
||||
import {Check, ExternalLink, Loader2} from 'lucide-react';
|
||||
import type {LinkData} from '@/api';
|
||||
import {Badge} from '@/components/ui/badge';
|
||||
import {Button} from '@/components/ui/button';
|
||||
import {cn} from '@/lib/utils';
|
||||
import {CHANNEL_LABEL} from './useCollectFlow';
|
||||
|
||||
/**
|
||||
* 수집 잡이 찾아온 채널 URL 을 사장님이 확정하는 패널.
|
||||
*
|
||||
* ★ 이 화면이 파이프라인에서 사람이 반드시 개입해야 하는 지점이다.
|
||||
* 확정 없이 긁으면 이름이 비슷한 남의 가게 페이지가 이 가게의 공식 홈페이지에 실린다.
|
||||
* 그래서 기본값은 '확정 안 함'이고, 누른 것만 크롤링 대상이 된다.
|
||||
*/
|
||||
export function ChannelConfirmPanel({
|
||||
links,
|
||||
confirmedCount,
|
||||
confirmingId,
|
||||
onConfirm,
|
||||
}: {
|
||||
links: LinkData[];
|
||||
confirmedCount: number;
|
||||
confirmingId: string | null;
|
||||
onConfirm: (linkId: string) => void;
|
||||
}) {
|
||||
return (
|
||||
<div>
|
||||
<div className="mb-2 flex items-center justify-between">
|
||||
<span className="text-xs font-semibold">찾은 채널 URL</span>
|
||||
<Badge variant={confirmedCount > 0 ? 'success' : 'warning'} className="text-[10px]">
|
||||
확정 {confirmedCount} / {links.length}
|
||||
</Badge>
|
||||
</div>
|
||||
|
||||
<ul className="max-h-56 space-y-1.5 overflow-y-auto pr-1">
|
||||
{links.map((link) => {
|
||||
const isConfirmed = Boolean(link.confirmed_at);
|
||||
const isBusy = confirmingId === link.link_id;
|
||||
|
||||
return (
|
||||
<li
|
||||
key={link.link_id}
|
||||
className={cn(
|
||||
'rounded-lg border p-2.5 text-[11px]',
|
||||
isConfirmed ? 'border-success/40 bg-success/5' : 'border-border bg-muted/40',
|
||||
)}
|
||||
>
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<span className="font-semibold">
|
||||
{CHANNEL_LABEL[link.channel] ?? '기타 채널'}
|
||||
</span>
|
||||
{isConfirmed ? (
|
||||
<Badge variant="success" className="shrink-0 text-[10px]">
|
||||
확정됨
|
||||
</Badge>
|
||||
) : (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="primary"
|
||||
onClick={() => onConfirm(link.link_id)}
|
||||
disabled={isBusy}
|
||||
>
|
||||
{isBusy ? <Loader2 className="animate-spin" /> : <Check />}
|
||||
<span>내 채널 맞아요</span>
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<a
|
||||
href={link.url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="mt-1 flex items-center gap-1 break-all text-muted-foreground underline-offset-2 hover:text-foreground hover:underline"
|
||||
>
|
||||
<ExternalLink className="size-3 shrink-0" />
|
||||
<span className="min-w-0 break-all">{link.url}</span>
|
||||
</a>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
|
||||
<p className="mt-2 text-[11px] leading-relaxed text-muted-foreground">
|
||||
링크를 열어 <strong>내 가게가 맞는지 직접 확인</strong>한 뒤 확정해 주세요. 확정한 URL 만
|
||||
크롤링합니다 — 확정하지 않은 URL 은 건드리지 않습니다.
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
import {useState} from 'react';
|
||||
import {Link2, Loader2, MapPin, Plus} from 'lucide-react';
|
||||
import type {LinkChannel as LinkChannelCode} from '@/api';
|
||||
import {LinkChannel} from '@o2o/shared';
|
||||
import {Button} from '@/components/ui/button';
|
||||
import {Input} from '@/components/ui/input';
|
||||
|
||||
/**
|
||||
* 채널 URL 직접 등록 — **수집의 1순위 경로다.** 폴백이 아니다.
|
||||
*
|
||||
* ★ 왜 자동 발견보다 이게 먼저인가 (실측 2026-08-27)
|
||||
* · Perplexity 는 네이버 플레이스를 **한 건도** 못 찾았다(도플로·버터브루·힐튼 가든 인
|
||||
* 서울 강남 전부 야놀자만 물어옴). 도메인 필터를 넓혔더니 이번엔 네이버 도움말 페이지
|
||||
* (pages.map.naver.com/useful-tips)를 이 가게 채널로 등록했다. 그래서 기본 경로에서 뺐다.
|
||||
* · 상호로 place id 를 자동 해석하는 경로도 4곳 중 3곳만 성공한다('롯데호텔 서울' 실패).
|
||||
* · 반면 **네이버 플레이스 URL 만 있으면 100% 된다** — 어댑터가 fact 5~7건 + 사진 10장을
|
||||
* 안정적으로 가져온다(힐튼·스테이머뭄·롯데월드에서 검증).
|
||||
* 그리고 사장님은 자기 가게 주소를 이미 알고 있다. 추측하게 두는 것보다 물어보는 것이
|
||||
* 빠르고 정확하고 공짜다.
|
||||
*
|
||||
* 그래서 이 컴포넌트는 "네이버 지도 주소"를 전제로 말한다 — 다른 채널도 받지만,
|
||||
* 사장님이 따라 할 동작 하나는 네이버 지도에서 주소를 복사하는 것이다.
|
||||
*
|
||||
* 붙여넣은 URL 은 그 자체로 사장님이 확인한 값이므로 등록과 동시에 확정한다.
|
||||
*/
|
||||
|
||||
/** 호스트로 채널을 판정한다. 서버도 같은 규칙을 쓰지만, 화면이 먼저 라벨을 보여줘야 한다. */
|
||||
function guessChannel(url: string): {channel: LinkChannelCode; label: string} | null {
|
||||
const u = url.toLowerCase();
|
||||
if (u.includes('naver.com') || u.includes('naver.me')) {
|
||||
// 블로그·카페는 채널이 아니라 후기다 — 크롤링 대상이 아니므로 받지 않는다.
|
||||
if (u.includes('blog.naver') || u.includes('cafe.naver')) return null;
|
||||
return {channel: LinkChannel.NAVER_PLACE, label: '네이버 플레이스'};
|
||||
}
|
||||
if (u.includes('yanolja.com')) return {channel: LinkChannel.YANOLJA, label: '야놀자'};
|
||||
if (u.includes('goodchoice.kr') || u.includes('yeogi.com')) {
|
||||
return {channel: LinkChannel.GOODCHOICE, label: '여기어때'};
|
||||
}
|
||||
if (u.includes('instagram.com')) return {channel: LinkChannel.INSTAGRAM, label: '인스타그램'};
|
||||
return {channel: LinkChannel.OFFICIAL_SITE, label: '공식 홈페이지'};
|
||||
}
|
||||
|
||||
/** 주소를 어디서 복사해 오는지 — 사장님이 그대로 따라 할 수 있게 동작 단위로 쪼갠다. */
|
||||
const HOW_TO = [
|
||||
'네이버 지도(또는 네이버 검색)에서 내 가게를 찾습니다',
|
||||
'가게 이름 옆 [공유] 를 누릅니다',
|
||||
'[URL 복사] 를 눌러 주소를 복사합니다',
|
||||
'아래 칸에 붙여넣고 [추가] 를 누릅니다',
|
||||
];
|
||||
|
||||
export function ChannelUrlInput({
|
||||
onAdd,
|
||||
isBusy,
|
||||
}: {
|
||||
onAdd: (url: string, channel: LinkChannelCode, title: string) => Promise<void>;
|
||||
isBusy?: boolean;
|
||||
}) {
|
||||
const [url, setUrl] = useState('');
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const guess = url.trim() ? guessChannel(url.trim()) : null;
|
||||
const isNaver = guess?.channel === LinkChannel.NAVER_PLACE;
|
||||
|
||||
const submit = async () => {
|
||||
const value = url.trim();
|
||||
if (!value) return;
|
||||
if (!/^https?:\/\//i.test(value)) {
|
||||
setError('https:// 로 시작하는 주소를 붙여넣어 주세요.');
|
||||
return;
|
||||
}
|
||||
if (!guess) {
|
||||
setError('블로그·카페 글은 채널이 아니라 후기라 수집 대상이 아닙니다.');
|
||||
return;
|
||||
}
|
||||
setError(null);
|
||||
await onAdd(value, guess.channel, guess.label);
|
||||
setUrl('');
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="rounded-2xl border border-primary/40 bg-primary/5 p-5">
|
||||
<p className="flex items-center gap-1.5 text-sm font-bold">
|
||||
<MapPin className="size-4 text-primary" />
|
||||
네이버 지도에서 내 가게 주소를 복사해 붙여넣어 주세요
|
||||
</p>
|
||||
<p className="mt-1.5 text-[11px] leading-relaxed text-muted-foreground">
|
||||
가장 확실한 방법입니다. 주소 하나만 있으면 <strong>영업시간·전화·편의시설과 사진</strong>
|
||||
까지 그대로 가져옵니다.
|
||||
</p>
|
||||
|
||||
<ol className="mt-3 space-y-1.5">
|
||||
{HOW_TO.map((step, index) => (
|
||||
<li key={step} className="flex items-start gap-2 text-[11px] leading-relaxed">
|
||||
<span className="mt-px flex size-4 shrink-0 items-center justify-center rounded-full bg-primary text-[9px] font-bold text-primary-foreground">
|
||||
{index + 1}
|
||||
</span>
|
||||
<span>{step}</span>
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
|
||||
<div className="mt-3 flex items-center gap-1.5">
|
||||
<Input
|
||||
value={url}
|
||||
onChange={(e) => {
|
||||
setUrl(e.target.value);
|
||||
setError(null);
|
||||
}}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter') void submit();
|
||||
}}
|
||||
placeholder="https://map.naver.com/p/entry/place/1273971279"
|
||||
disabled={isBusy}
|
||||
/>
|
||||
<Button size="sm" variant="primary" onClick={() => void submit()} disabled={isBusy || !url.trim()}>
|
||||
{isBusy ? <Loader2 className="animate-spin" /> : <Plus />}
|
||||
<span>추가</span>
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<p
|
||||
className={`mt-1.5 text-[11px] leading-relaxed ${
|
||||
error ? 'text-destructive' : isNaver ? 'text-primary' : 'text-muted-foreground'
|
||||
}`}
|
||||
>
|
||||
{error ??
|
||||
(isNaver
|
||||
? '네이버 플레이스 주소입니다 — 이 경로가 가장 많이, 가장 정확하게 가져옵니다.'
|
||||
: guess
|
||||
? `${guess.label} 주소로 등록됩니다. 네이버 지도 주소가 있으면 그쪽이 더 많이 가져옵니다.`
|
||||
: 'naver.me 단축 주소도 됩니다. 야놀자·여기어때·공식 홈페이지 주소도 받습니다.')}
|
||||
</p>
|
||||
|
||||
<p className="mt-2 flex items-start gap-1 border-t border-primary/20 pt-2 text-[10px] leading-relaxed text-muted-foreground">
|
||||
<Link2 className="mt-px size-3 shrink-0" />
|
||||
<span>
|
||||
붙여넣은 주소는 사장님이 확인한 것으로 보고 <strong>바로 수집 대상</strong>이 됩니다.
|
||||
수집된 값은 그래도 전부 확인 대기로 들어갑니다.
|
||||
</span>
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
import {useState} from 'react';
|
||||
import {useQueryClient} from '@tanstack/react-query';
|
||||
import {ClipboardPaste, Loader2, Sparkles} from 'lucide-react';
|
||||
import type {ResExtractedFact} from '@/api';
|
||||
import {useExtractFactsFromText} from '@/api';
|
||||
import {Button} from '@/components/ui/button';
|
||||
import {notify, notifyApiError} from '@/lib/notify';
|
||||
import {cn} from '@/lib/utils';
|
||||
|
||||
/**
|
||||
* 붙여넣기로 정보 채우기 — **폴백 3단계의 2번**이다.
|
||||
*
|
||||
* ★ 왜 필요한가 (실측 2026-08-31)
|
||||
* 자동 수집만으로는 근거가 안 차는 업소가 흔하다.
|
||||
* · 조이모텔: TourAPI 미등록(모텔은 관광공사 대상이 아니다) + 네이버엔 요금표뿐 →
|
||||
* 수집 fact 6건이 전부 '대실 20,000 / 숙박 40,000' 같은 요금이었다.
|
||||
* 체크인·주차·와이파이가 하나도 없어 소개문도 FAQ 도 만들 수 없었다.
|
||||
* 이런 업소는 사장님이 이미 알고 있는 내용을 **붙여넣게 하는 것이 가장 빠르다.**
|
||||
* 홈페이지 URL 이 있으면 static_html 어댑터가 대신 읽지만, 그것도 없는 업소가 많다.
|
||||
*
|
||||
* ★ 사장님이 쓴 글을 그대로 싣지 않는다
|
||||
* 붙여넣은 원문은 저장되지 않는다. 서버가 업종 스키마 필드만 **뽑아서** 후보로 넣고,
|
||||
* 그 값의 근거 문장이 원문에 실제로 있는지까지 대조한다(services/grounding/extract.py).
|
||||
* 그래서 "조식 제공합니다" 를 안 썼는데 조식이 켜지는 일이 없다.
|
||||
*
|
||||
* ★ 결과를 통과분만 보여주지 않는다
|
||||
* 버려진 항목과 사유를 같이 띄운다 — 사장님이 "내가 적은 체크인 시간이 왜 안 들어갔지"
|
||||
* 를 화면에서 바로 알 수 있어야 한다. 조용히 버리면 신뢰를 잃는다.
|
||||
*/
|
||||
|
||||
const PLACEHOLDER = `가게 소개, 이용 안내, 객실·메뉴 정보를 그대로 붙여넣어 주세요.
|
||||
|
||||
예시)
|
||||
체크인 오후 3시 / 체크아웃 오전 11시
|
||||
전 객실 무료주차 가능, 와이파이 있습니다
|
||||
반려동물 동반은 어렵습니다
|
||||
바비큐장 이용료 1회 20,000원
|
||||
오션뷰룸 기준 2인 최대 4인 / 주중 180,000원 주말 220,000원`;
|
||||
|
||||
const MIN_CHARS = 80;
|
||||
|
||||
export function PasteFactsPanel({placeId, className}: {placeId: string | null; className?: string}) {
|
||||
const [text, setText] = useState('');
|
||||
const [result, setResult] = useState<{stored: number; rows: ResExtractedFact[]; rejections: string[][]} | null>(null);
|
||||
const queryClient = useQueryClient();
|
||||
const extract = useExtractFactsFromText();
|
||||
|
||||
// 데모(placeId 없음)에는 저장할 서버 상태가 없다. 눌러도 아무 일이 없는 버튼을 두지 않는다.
|
||||
if (!placeId) return null;
|
||||
|
||||
const tooShort = text.trim().length < MIN_CHARS;
|
||||
const busy = extract.isPending;
|
||||
|
||||
const run = async () => {
|
||||
try {
|
||||
const res = await extract.mutateAsync({placeId, data: {text}});
|
||||
setResult({
|
||||
stored: res.stored ?? 0,
|
||||
rows: res.facts ?? [],
|
||||
rejections: (res.rejections ?? []) as string[][],
|
||||
});
|
||||
if (res.stored) {
|
||||
// 새 후보가 생겼으니 fact 목록을 다시 읽는다 — 사장님이 바로 확인 버튼을 눌러야 한다.
|
||||
await queryClient.invalidateQueries({queryKey: ['/v1/place', placeId, 'fact']});
|
||||
notify.success(`${res.stored}건을 찾았습니다. 확인 후 사이트에 반영됩니다.`);
|
||||
setText('');
|
||||
} else {
|
||||
notify.info('가져올 수 있는 정보를 찾지 못했습니다. 아래 사유를 확인해 주세요.');
|
||||
}
|
||||
} catch (error) {
|
||||
notifyApiError(error);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<section className={cn('space-y-2.5 rounded-xl border border-border bg-card p-4', className)}>
|
||||
<header className="flex items-center gap-2">
|
||||
<ClipboardPaste className="size-4 shrink-0 text-muted-foreground" />
|
||||
<h2 className="text-sm font-semibold">붙여넣어서 정보 채우기</h2>
|
||||
</header>
|
||||
<p className="text-[11px] leading-relaxed text-muted-foreground">
|
||||
자동으로 못 가져온 정보는 직접 붙여넣어 주세요. 문장에서 필요한 항목만 뽑아 <strong>확인 대기</strong> 목록에
|
||||
넣습니다. 원문은 저장되지 않습니다.
|
||||
</p>
|
||||
|
||||
<textarea
|
||||
value={text}
|
||||
onChange={(e) => setText(e.target.value)}
|
||||
placeholder={PLACEHOLDER}
|
||||
rows={8}
|
||||
disabled={busy}
|
||||
className={cn(
|
||||
'w-full resize-y rounded-lg border border-input bg-background px-3 py-2',
|
||||
'text-xs leading-relaxed placeholder:text-muted-foreground/70',
|
||||
'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-60',
|
||||
)}
|
||||
/>
|
||||
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<span className="text-[10px] text-muted-foreground">
|
||||
{text.trim().length > 0 && tooShort
|
||||
? `${MIN_CHARS}자 이상 붙여넣어 주세요 (현재 ${text.trim().length}자)`
|
||||
: `${text.trim().length}자`}
|
||||
</span>
|
||||
<Button size="sm" disabled={busy || tooShort} onClick={() => void run()}>
|
||||
{busy ? <Loader2 className="animate-spin" /> : <Sparkles />}
|
||||
<span>{busy ? '읽는 중…' : '정보 뽑기'}</span>
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{result && (
|
||||
<div className="space-y-2 rounded-lg border border-border bg-muted/40 p-3">
|
||||
<p className="text-[11px] font-medium">
|
||||
{result.stored}건 추가됨
|
||||
{result.rejections.length > 0 && (
|
||||
<span className="text-muted-foreground"> · {result.rejections.length}건 제외</span>
|
||||
)}
|
||||
</p>
|
||||
|
||||
{result.rows.length > 0 && (
|
||||
<ul className="space-y-1">
|
||||
{result.rows.map((row, i) => (
|
||||
<li key={`${row.key}-${i}`} className="flex items-start gap-2 text-[11px]">
|
||||
<span className={cn('mt-1 size-1.5 shrink-0 rounded-full', row.stored ? 'bg-emerald-500' : 'bg-amber-500')} />
|
||||
<span className="min-w-0">
|
||||
<strong className="font-medium">{row.label}</strong>
|
||||
{row.unit_name && <span className="text-muted-foreground"> · {row.unit_name}</span>}
|
||||
<span className="text-muted-foreground"> — {row.value}</span>
|
||||
{row.reason && <span className="block text-amber-600 dark:text-amber-500">{row.reason}</span>}
|
||||
</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
|
||||
{/* ★ 버린 것도 보여준다. 사장님이 왜 안 들어갔는지 알아야 다시 쓸 수 있다. */}
|
||||
{result.rejections.length > 0 && (
|
||||
<details className="text-[10px] text-muted-foreground">
|
||||
<summary className="cursor-pointer select-none">제외된 항목 보기</summary>
|
||||
<ul className="mt-1 space-y-0.5 pl-3">
|
||||
{result.rejections.map(([label, why], i) => (
|
||||
<li key={i}>
|
||||
<span className="font-medium">{label}</span> — {why}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</details>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
import {ExternalLink, Link2, Loader2, MapPin} from 'lucide-react';
|
||||
import {Button} from '@/components/ui/button';
|
||||
import {Input} from '@/components/ui/input';
|
||||
import {cn} from '@/lib/utils';
|
||||
|
||||
/**
|
||||
* 자동 상호 검색이 실패했을 때 네이버 지도에서 직접 찾아 URL로 확정하는 fallback.
|
||||
*
|
||||
* ★ 왜 이 fallback 이 필요한가
|
||||
* 상호 검색은 동명 업소·지점명 표기 차이에서 실패한다(실측: '롯데호텔 서울').
|
||||
* 검색모델(Perplexity)은 네이버 플레이스를 아예 못 찾고 안내 페이지를 물어온 적도 있다.
|
||||
* 반면 사장님은 자기 가게 주소를 이미 안다 — 붙여넣는 순간 신원과 수집 채널이 동시에
|
||||
* 확정되고, 상호·주소·좌표는 서버가 그 URL 에서 직접 읽는다.
|
||||
* (선례: o2o-castad 도 네이버 지도 URL 직접 입력을 주 경로로 둔다.)
|
||||
*/
|
||||
export function PlaceUrlBox({
|
||||
value,
|
||||
onChange,
|
||||
onSubmit,
|
||||
isBusy,
|
||||
compact,
|
||||
searchQuery,
|
||||
}: {
|
||||
value: string;
|
||||
onChange: (next: string) => void;
|
||||
onSubmit: () => void;
|
||||
isBusy?: boolean;
|
||||
/** 후보 목록 아래에 놓일 때는 설명을 줄인다. */
|
||||
compact?: boolean;
|
||||
/** 자동 검색 실패 시 네이버 지도를 이 검색어로 바로 연다. */
|
||||
searchQuery?: string;
|
||||
}) {
|
||||
const isNaverUrl = /naver\.(com|me)/i.test(value);
|
||||
const mapSearchUrl = searchQuery?.trim()
|
||||
? `https://map.naver.com/p/search/${encodeURIComponent(searchQuery.trim())}`
|
||||
: 'https://map.naver.com/';
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
'rounded-2xl border bg-card p-5',
|
||||
compact ? 'border-border' : 'border-primary/40 ring-2 ring-primary/10',
|
||||
)}
|
||||
>
|
||||
<p className="flex items-center gap-1.5 text-sm font-bold">
|
||||
<MapPin className="size-4 text-primary" />
|
||||
네이버 플레이스에서 직접 찾기
|
||||
{!compact && (
|
||||
<span className="rounded bg-primary/10 px-1.5 py-0.5 text-[10px] font-semibold text-primary">
|
||||
가장 정확
|
||||
</span>
|
||||
)}
|
||||
</p>
|
||||
|
||||
{!compact && (
|
||||
<>
|
||||
<p className="mt-2 text-[11px] leading-relaxed text-muted-foreground">
|
||||
자동 검색에서 찾지 못했습니다. 네이버 지도에서 내 가게를 연 뒤 [공유] 주소를
|
||||
복사해 아래에 붙여넣어 주세요.
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
|
||||
<a
|
||||
href={mapSearchUrl}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="mt-3 flex w-full items-center justify-center gap-1.5 rounded-lg border border-border bg-background px-3 py-2 text-xs font-semibold transition-colors hover:bg-accent"
|
||||
>
|
||||
<ExternalLink className="size-3.5" />
|
||||
<span>
|
||||
네이버 지도에서{' '}
|
||||
{searchQuery?.trim()
|
||||
? `'${searchQuery.trim()}' 검색`
|
||||
: compact
|
||||
? '이 상호 다시 찾기'
|
||||
: '검색'}
|
||||
</span>
|
||||
</a>
|
||||
|
||||
<div className="mt-3 flex items-center gap-1.5">
|
||||
<Input
|
||||
value={value}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' && value.trim()) onSubmit();
|
||||
}}
|
||||
placeholder="https://map.naver.com/p/entry/place/1133638931"
|
||||
disabled={isBusy}
|
||||
/>
|
||||
<Button
|
||||
variant="primary"
|
||||
onClick={onSubmit}
|
||||
disabled={isBusy || !value.trim()}
|
||||
className="shrink-0"
|
||||
>
|
||||
{isBusy ? <Loader2 className="animate-spin" /> : <Link2 />}
|
||||
<span>확인</span>
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<p
|
||||
className={cn(
|
||||
'mt-1.5 text-[11px]',
|
||||
value.trim() && !isNaverUrl ? 'text-destructive' : 'text-muted-foreground',
|
||||
)}
|
||||
>
|
||||
{value.trim() && !isNaverUrl
|
||||
? '네이버 지도·플레이스 주소를 붙여넣어 주세요.'
|
||||
: 'map.naver.com · m.place.naver.com · naver.me 주소를 지원합니다.'}
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
import {Loader2, PenLine, RefreshCw, Sparkles, TriangleAlert} from 'lucide-react';
|
||||
import {useGetPlace} from '@/api';
|
||||
import {Button} from '@/components/ui/button';
|
||||
import {cn} from '@/lib/utils';
|
||||
import {useCollectFlow, type RecollectTask} from './useCollectFlow';
|
||||
|
||||
/**
|
||||
* 세 가지 재수집 동작.
|
||||
*
|
||||
* ★ 문구가 "다시 가져옵니다"로 읽히면 안 된다. 자동 수집(CRAWL)은 **노출 중인 값을 못 바꾼다** —
|
||||
* 달라진 값은 확인 대기 후보로 쌓이고, 사장님이 [맞아요]를 눌러야 교체된다. 사장님이 직접
|
||||
* 고친 값(CORRECTED)은 아예 잠겨 있다(fact_service 의 업데이트 프로세스).
|
||||
* 그래서 hint 는 전부 "후보로 올립니다 / 확인 뒤 나갑니다"로 끝난다.
|
||||
*/
|
||||
const ACTIONS: {
|
||||
task: RecollectTask;
|
||||
label: string;
|
||||
busyLabel: string;
|
||||
icon: typeof RefreshCw;
|
||||
hint: string;
|
||||
}[] = [
|
||||
{
|
||||
task: 'facts',
|
||||
label: '정보 다시 수집',
|
||||
busyLabel: '수집 중…',
|
||||
icon: RefreshCw,
|
||||
hint: '확정한 채널을 다시 읽습니다. 달라진 값은 확인 대기 목록에 쌓입니다.',
|
||||
},
|
||||
{
|
||||
task: 'photos',
|
||||
label: '사진 다시 분석',
|
||||
busyLabel: '분석 중…',
|
||||
icon: Sparkles,
|
||||
hint: '이미 분석한 사진까지 다시 분류하고 설명을 답니다.',
|
||||
},
|
||||
{
|
||||
task: 'copy',
|
||||
label: '소개문 다시 생성',
|
||||
busyLabel: '만드는 중…',
|
||||
icon: PenLine,
|
||||
hint: '확인된 정보만 근거로 소개문·FAQ 를 새로 씁니다.',
|
||||
},
|
||||
];
|
||||
|
||||
/**
|
||||
* 재수집 패널 — 사업장 상세와 빌더 에디터가 같이 쓴다.
|
||||
*
|
||||
* ★ 왜 필요한가: 재수집 버튼은 지금까지 위저드 3단계에만 있었다. 위저드를 끝내고 나면
|
||||
* **이미 만든 사업장을 다시 긁을 길이 없어서** 사장님 눈에는 "재크롤링 기능이 없다"였다.
|
||||
* 그래서 사업장을 다시 여는 두 자리(상세 · 에디터)에 같은 패널을 붙인다.
|
||||
*
|
||||
* ★ 배선은 위저드와 **같은 훅**(useCollectFlow)이다. 수집 경로를 두 벌 만들면 확정 게이트
|
||||
* 같은 규칙이 한쪽에서만 지켜진다 — 다른 건 force 플래그뿐이다.
|
||||
*/
|
||||
export function RecollectPanel({placeId, className}: {placeId: string | null; className?: string}) {
|
||||
const enabled = Boolean(placeId);
|
||||
// 이미 다른 화면이 읽어둔 캐시를 그대로 본다(같은 쿼리 키) — 이 패널 때문에 새로 요청하지 않는다.
|
||||
const placeQuery = useGetPlace(placeId ?? '', {query: {enabled}});
|
||||
const collect = useCollectFlow(placeId);
|
||||
|
||||
// 데모(placeId 없음)에는 재수집할 서버 상태 자체가 없다. 눌러도 아무 일이 없는 버튼을 두지 않는다.
|
||||
if (!placeId) return null;
|
||||
|
||||
const isVerified = Boolean(placeQuery.data?.place?.verified_at);
|
||||
const busy = collect.recollectingTask;
|
||||
|
||||
/** 지금 이 동작을 못 누르는 이유. 없으면 누를 수 있다. ★ 이유 없이 회색으로만 두지 않는다. */
|
||||
const blockedReason = (task: RecollectTask): string | null => {
|
||||
// 검증·확정 게이트는 크롤링에만 걸린다(place_service.start_collect).
|
||||
// 사진 분석·소개문 생성은 이미 쌓인 데이터를 다루므로 서버가 따로 막지 않는다.
|
||||
if (task !== 'facts') return null;
|
||||
if (!isVerified) return '동일 업소 검증을 끝내야 수집이 열립니다.';
|
||||
if (collect.confirmedCount === 0) return '확정한 채널 URL 이 없습니다. 먼저 채널을 확정해 주세요.';
|
||||
return null;
|
||||
};
|
||||
|
||||
return (
|
||||
<section className={cn('space-y-2.5 rounded-xl border border-border bg-card p-4', className)}>
|
||||
<header className="flex items-center justify-between gap-2">
|
||||
<h2 className="text-sm font-semibold">다시 수집하기</h2>
|
||||
{busy && (
|
||||
<span className="flex shrink-0 items-center gap-1 text-[10px] font-medium text-muted-foreground">
|
||||
<Loader2 className="size-3 animate-spin" />
|
||||
진행 중
|
||||
</span>
|
||||
)}
|
||||
</header>
|
||||
|
||||
<div className="space-y-2">
|
||||
{ACTIONS.map(({task, label, busyLabel, icon: Icon, hint}) => {
|
||||
const isRunning = busy === task;
|
||||
const reason = blockedReason(task);
|
||||
return (
|
||||
<div key={task} className="space-y-1">
|
||||
<Button
|
||||
variant={task === 'facts' ? 'primary' : 'outline'}
|
||||
size="sm"
|
||||
className="w-full justify-start"
|
||||
// 하나가 도는 동안 나머지도 잠근다 — 같은 사업장에 유료 잡을 겹쳐 태우지 않는다.
|
||||
disabled={Boolean(busy) || Boolean(reason)}
|
||||
onClick={() => void collect.recollect(task)}
|
||||
>
|
||||
{isRunning ? <Loader2 className="animate-spin" /> : <Icon />}
|
||||
<span>{isRunning ? busyLabel : label}</span>
|
||||
</Button>
|
||||
<p className="text-[10px] leading-relaxed text-muted-foreground">{reason ?? hint}</p>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
{busy && (
|
||||
// 잡은 몇 분짜리다. "누르긴 눌렀는데 아무 일도 안 난다"로 읽히지 않게 소요 시간을 적는다.
|
||||
<p className="rounded-lg border border-border bg-muted/40 p-2.5 text-[11px] leading-relaxed">
|
||||
몇 분 걸립니다. 끝나면 이 화면이 새 값으로 바뀝니다 — 그때까지 화면을 열어두세요.
|
||||
</p>
|
||||
)}
|
||||
|
||||
{/* ★ 유료 API 재호출 안내. 겁주지 않되 숨기지도 않는다 — 누르면 돈이 나가는 버튼이다. */}
|
||||
<p className="flex items-start gap-1.5 text-[10px] leading-relaxed text-muted-foreground">
|
||||
<TriangleAlert className="mt-px size-3 shrink-0" />
|
||||
<span>
|
||||
다시 수집하면 외부 검색·사진 분석 API 를 다시 호출합니다(호출당 비용 발생). 사장님이
|
||||
확인·수정한 값은 덮어쓰지 않습니다.
|
||||
</span>
|
||||
</p>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
import {Check} from 'lucide-react';
|
||||
import type {IndustryType} from '@o2o/shared';
|
||||
import {INDUSTRY_CONFIGS} from '@/data/industryData';
|
||||
import {cn} from '@/lib/utils';
|
||||
import {useBuilderStore} from '@/stores/builder';
|
||||
import {INDUSTRY_ICONS} from './industryIcons';
|
||||
import {WizardFooter} from './WizardFooter';
|
||||
import {WizardSteps} from './WizardSteps';
|
||||
|
||||
const INDUSTRY_ORDER: IndustryType[] = ['stay', 'cafe', 'restaurant', 'tour'];
|
||||
|
||||
export function Step1Industry() {
|
||||
const industry = useBuilderStore((s) => s.industry);
|
||||
const selectIndustry = useBuilderStore((s) => s.selectIndustry);
|
||||
const goToStep = useBuilderStore((s) => s.goToStep);
|
||||
|
||||
return (
|
||||
<div className="flex flex-1 flex-col justify-between bg-muted/30">
|
||||
<div className="flex flex-1 flex-col items-center justify-center px-4 py-10 sm:px-6 sm:py-16 lg:px-8">
|
||||
<div className="mx-auto flex w-full max-w-5xl flex-col">
|
||||
<WizardSteps current={1} />
|
||||
|
||||
<div className="mb-10 text-center sm:mb-12">
|
||||
<h1 className="text-2xl font-bold tracking-tight sm:text-3xl lg:text-4xl">
|
||||
어떤 업종의 홈페이지를 만들까요?
|
||||
</h1>
|
||||
<p className="mx-auto mt-2.5 max-w-lg text-sm text-muted-foreground sm:text-base">
|
||||
업종을 고르면 그 업종에 맞는 항목만 수집하고, 그 항목만 검증합니다.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2 sm:gap-5 lg:grid-cols-4">
|
||||
{INDUSTRY_ORDER.map((id) => {
|
||||
const config = INDUSTRY_CONFIGS[id];
|
||||
const Icon = INDUSTRY_ICONS[id];
|
||||
const isSelected = industry === id;
|
||||
|
||||
return (
|
||||
<button
|
||||
key={id}
|
||||
type="button"
|
||||
onClick={() => selectIndustry(id)}
|
||||
aria-pressed={isSelected}
|
||||
className={cn(
|
||||
'flex cursor-pointer flex-col justify-between rounded-2xl border bg-card p-6 text-left transition-all',
|
||||
isSelected
|
||||
? 'border-primary ring-1 ring-primary'
|
||||
: 'border-border hover:border-muted-foreground/30',
|
||||
)}
|
||||
>
|
||||
<div className="mb-5 flex items-center justify-between">
|
||||
<span
|
||||
className={cn(
|
||||
'flex size-10 items-center justify-center rounded-xl transition-colors',
|
||||
isSelected
|
||||
? 'bg-primary text-primary-foreground'
|
||||
: 'bg-muted text-foreground',
|
||||
)}
|
||||
>
|
||||
<Icon className="size-5" />
|
||||
</span>
|
||||
<span
|
||||
className={cn(
|
||||
'flex size-5 items-center justify-center rounded-full transition-all',
|
||||
isSelected
|
||||
? 'bg-primary text-primary-foreground'
|
||||
: 'border border-border bg-card',
|
||||
)}
|
||||
>
|
||||
{isSelected && <Check className="size-3" strokeWidth={3} />}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="mb-2">
|
||||
<h2 className="text-base font-bold sm:text-lg">{config.name}</h2>
|
||||
<span className="text-xs font-medium text-muted-foreground">
|
||||
{config.subName}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<p className="text-xs leading-relaxed text-muted-foreground sm:text-sm">
|
||||
{config.description}
|
||||
</p>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<WizardFooter
|
||||
hint={
|
||||
<>
|
||||
선택된 업종:{' '}
|
||||
<strong className="font-semibold text-foreground">
|
||||
{INDUSTRY_CONFIGS[industry].name}
|
||||
</strong>{' '}
|
||||
({INDUSTRY_CONFIGS[industry].subName})
|
||||
</>
|
||||
}
|
||||
onNext={() => goToStep(2)}
|
||||
nextLabel="다음: 내 가게 찾기"
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,382 @@
|
||||
import {useState} from 'react';
|
||||
import {useSearchParams} from 'react-router';
|
||||
import {ArrowRight, Check, MapPin, Phone, Search, TriangleAlert} from 'lucide-react';
|
||||
import type {PlaceCandidate} from '@/api';
|
||||
import {Badge} from '@/components/ui/badge';
|
||||
import {Button} from '@/components/ui/button';
|
||||
import {Input} from '@/components/ui/input';
|
||||
import {cn} from '@/lib/utils';
|
||||
import {useBuilderStore} from '@/stores/builder';
|
||||
import {PlaceUrlBox} from './PlaceUrlBox';
|
||||
import {usePlaceSearch} from './usePlaceSearch';
|
||||
import {WizardFooter} from './WizardFooter';
|
||||
import {WizardStage, WizardWaiting} from './WizardStage';
|
||||
|
||||
const STAGE_TITLE: Record<string, string> = {
|
||||
input: '상호명을 검색해 내 가게를 찾아주세요',
|
||||
searching: '내 가게를 찾는 중입니다',
|
||||
picking: '이 중에 사장님 가게가 있나요?',
|
||||
unavailable: '지도 검색을 사용할 수 없습니다',
|
||||
confirmed: '이 가게로 확인되었습니다',
|
||||
};
|
||||
|
||||
const STAGE_DESCRIPTION: Record<string, string> = {
|
||||
input: '지도·플레이스에 등록된 가게 중에서 사장님이 직접 고른 한 곳만 기준이 됩니다.',
|
||||
searching: '',
|
||||
picking: '고른 가게의 상호·주소·전화가 이 사이트의 기준 정보가 됩니다.',
|
||||
unavailable: '',
|
||||
confirmed: '이제 이 가게의 공개 채널에서 정보를 수집합니다.',
|
||||
};
|
||||
|
||||
/** outcome 코드 → 사장님이 읽을 한 줄. 서버 판정은 문구를 고르는 데만 쓴다. */
|
||||
const OUTCOME_TEXT: Record<string, string> = {
|
||||
matched: '이 가게로 보입니다. 맞는지 한 번만 확인해 주세요.',
|
||||
ambiguous: '비슷한 이름의 가게가 여럿입니다. 어느 쪽이 사장님 가게인가요?',
|
||||
no_candidate: '이 이름으로는 찾지 못했습니다.',
|
||||
};
|
||||
|
||||
/**
|
||||
* 2단계 — 내 가게 확인.
|
||||
*
|
||||
* 한 화면에 한 가지만 묻는다: 상호를 묻거나 · 기다리거나 · 후보를 고르게 하거나 · 확정을 보여준다.
|
||||
*/
|
||||
export function Step2PlaceSearch() {
|
||||
const industry = useBuilderStore((s) => s.industry);
|
||||
const storeName = useBuilderStore((s) => s.storeName);
|
||||
const location = useBuilderStore((s) => s.location);
|
||||
const confirmedIdentity = useBuilderStore((s) => s.confirmedIdentity);
|
||||
const setStoreName = useBuilderStore((s) => s.setStoreName);
|
||||
const setLocation = useBuilderStore((s) => s.setLocation);
|
||||
const confirmIdentity = useBuilderStore((s) => s.confirmIdentity);
|
||||
const clearIdentity = useBuilderStore((s) => s.clearIdentity);
|
||||
const goToStep = useBuilderStore((s) => s.goToStep);
|
||||
|
||||
// 새로고침을 넘어온 경우 이미 만들어진 사업장을 그대로 쓴다(같은 위저드에서 두 번 만들지 않는다).
|
||||
const search = usePlaceSearch(industry, confirmedIdentity?.placeId ?? null);
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
|
||||
/**
|
||||
* 확정된 사업장을 주소창에 남긴다 — `?placeId=...`.
|
||||
*
|
||||
* ★ 이게 새로고침을 넘기는 유일한 수단이다. 위저드 상태는 브라우저에 저장하지 않는다
|
||||
* (stores/builder 주석): 저장하면 새 가게를 만들러 들어와도 지난 가게가 확정된 것으로
|
||||
* 떠 버린다. 주소창에 두면 새로고침은 서버에서 복원되고(usePlaceSync), 주소를 새로
|
||||
* 열면 깨끗하다 — 두 요구를 동시에 만족하는 자리는 여기뿐이다.
|
||||
*/
|
||||
const rememberPlace = (placeId: string | null) => {
|
||||
const next = new URLSearchParams(searchParams);
|
||||
if (placeId) {
|
||||
next.set('placeId', placeId);
|
||||
// 개발 서버 재시작/HMR로 BuilderPage가 다시 마운트돼도 신규 등록 흐름임을 보존한다.
|
||||
next.set('flow', 'onboarding');
|
||||
} else {
|
||||
next.delete('placeId');
|
||||
next.delete('flow');
|
||||
}
|
||||
setSearchParams(next, {replace: true});
|
||||
};
|
||||
const [pickedIndex, setPickedIndex] = useState<number | null>(null);
|
||||
const [placeUrl, setPlaceUrl] = useState('');
|
||||
|
||||
const canSearch = storeName.trim().length > 0 && search.phase !== 'searching';
|
||||
|
||||
const runSearch = () => {
|
||||
clearIdentity(); // 상호를 고쳐 다시 찾는 것이므로 앞서 확정한 신원은 물린다
|
||||
setPickedIndex(null);
|
||||
void search.search(storeName, location);
|
||||
};
|
||||
|
||||
const backToInput = () => {
|
||||
clearIdentity();
|
||||
// 다른 가게를 찾으러 간다 — 주소창에 남은 사업장도 같이 놓아준다.
|
||||
rememberPlace(null);
|
||||
setPickedIndex(null);
|
||||
search.reset();
|
||||
};
|
||||
|
||||
const pick = async (candidate: PlaceCandidate, index: number) => {
|
||||
// 지역검색 후보만 있고 네이버 플레이스를 못 찾았으면 확정하지 않는다.
|
||||
// URL 확정 경로가 상호·주소·좌표와 수집 채널을 한 번에 보장한다.
|
||||
if (!candidate.naver_place_url) return;
|
||||
setPickedIndex(index);
|
||||
const identity = await search.confirmByUrl(candidate.naver_place_url);
|
||||
if (!identity) {
|
||||
setPickedIndex(null);
|
||||
return;
|
||||
}
|
||||
confirmIdentity(identity);
|
||||
rememberPlace(identity.placeId);
|
||||
goToStep(3);
|
||||
};
|
||||
|
||||
/** 네이버 플레이스 URL 로 확정 — 가장 확실한 경로다(usePlaceSearch.confirmByUrl 주석 참고). */
|
||||
const pickByUrl = async () => {
|
||||
const url = placeUrl.trim();
|
||||
if (!url) return;
|
||||
const identity = await search.confirmByUrl(url);
|
||||
if (!identity) return;
|
||||
confirmIdentity(identity);
|
||||
rememberPlace(identity.placeId);
|
||||
goToStep(3);
|
||||
};
|
||||
|
||||
// ── 화면 고르기. 위에서부터 먼저 맞는 것 하나만 그린다 ──────────────
|
||||
const stage = confirmedIdentity
|
||||
? 'confirmed'
|
||||
: search.phase === 'searching'
|
||||
? 'searching'
|
||||
: search.phase === 'unavailable'
|
||||
? 'unavailable'
|
||||
: search.phase === 'done'
|
||||
? 'picking'
|
||||
: 'input';
|
||||
|
||||
return (
|
||||
<div className="flex flex-1 flex-col justify-between bg-muted/30">
|
||||
<WizardStage
|
||||
current={2}
|
||||
wide={stage === 'picking'}
|
||||
title={STAGE_TITLE[stage]}
|
||||
description={STAGE_DESCRIPTION[stage]}
|
||||
>
|
||||
{stage === 'input' && (
|
||||
<div className="space-y-4">
|
||||
<div className="space-y-4 rounded-2xl border border-border bg-card p-6">
|
||||
<div>
|
||||
<label htmlFor="store-name" className="mb-1.5 block text-xs font-semibold">
|
||||
상호명 <span className="text-destructive">*</span>
|
||||
</label>
|
||||
<Input
|
||||
id="store-name"
|
||||
value={storeName}
|
||||
onChange={(e) => setStoreName(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' && canSearch) runSearch();
|
||||
}}
|
||||
placeholder="가게 이름을 입력하세요"
|
||||
autoFocus
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label htmlFor="store-location" className="mb-1.5 block text-xs font-semibold">
|
||||
위치 (시/군/구/동)
|
||||
</label>
|
||||
<Input
|
||||
id="store-location"
|
||||
value={location}
|
||||
onChange={(e) => setLocation(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' && canSearch) runSearch();
|
||||
}}
|
||||
placeholder="예: 제주시 애월읍"
|
||||
/>
|
||||
<p className="mt-1.5 text-[11px] text-muted-foreground">
|
||||
같은 이름의 가게가 많을 때 구분하는 데 쓰입니다. 비워도 검색됩니다.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
variant="outline"
|
||||
size="lg"
|
||||
className="w-full"
|
||||
onClick={runSearch}
|
||||
disabled={!canSearch}
|
||||
>
|
||||
<Search />
|
||||
<span>상호로 찾아보기</span>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{stage === 'searching' && (
|
||||
<WizardWaiting
|
||||
title="등록된 가게를 찾는 중입니다"
|
||||
description={`'${storeName}' 와(과) 같은 이름의 가게를 지도에서 확인하고 있어요`}
|
||||
/>
|
||||
)}
|
||||
|
||||
{stage === 'picking' && (
|
||||
<div className="space-y-3">
|
||||
<p
|
||||
className={cn(
|
||||
'rounded-xl p-3 text-xs leading-relaxed',
|
||||
search.candidates.length > 0
|
||||
? 'border border-border bg-card text-muted-foreground'
|
||||
: 'border border-warning/30 bg-warning/10 text-warning',
|
||||
)}
|
||||
>
|
||||
{OUTCOME_TEXT[search.outcome] ?? '아래 목록에서 사장님 가게를 골라 주세요.'}
|
||||
{search.sourceLabel && (
|
||||
<Badge variant="outline" className="ml-2 text-[10px]">
|
||||
{search.sourceLabel}
|
||||
</Badge>
|
||||
)}
|
||||
</p>
|
||||
|
||||
{search.candidates.length > 0 &&
|
||||
!search.candidates.some((candidate) => candidate.naver_place_url) && (
|
||||
<p className="rounded-xl border border-warning/30 bg-warning/10 p-3 text-xs font-medium leading-relaxed text-warning">
|
||||
<TriangleAlert className="mr-1 inline size-3.5 align-text-bottom" />
|
||||
상호 후보는 찾았지만 네이버 플레이스는 찾지 못했습니다. 아래 버튼으로 네이버
|
||||
지도에서 가게를 검색한 뒤 플레이스 URL을 붙여넣어 주세요.
|
||||
</p>
|
||||
)}
|
||||
|
||||
<ul className="space-y-2">
|
||||
{search.candidates.map((candidate, index) => (
|
||||
<li key={`${candidate.external_place_id ?? candidate.name}-${index}`}>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void pick(candidate, index)}
|
||||
disabled={search.isConfirming || !candidate.naver_place_url}
|
||||
className="w-full cursor-pointer rounded-xl border border-border bg-card p-4 text-left transition-all hover:border-primary hover:bg-accent disabled:opacity-60"
|
||||
>
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<span className="text-sm font-bold">{candidate.name}</span>
|
||||
{candidate.category_name && (
|
||||
<Badge variant="outline" className="text-[10px]">
|
||||
{candidate.category_name}
|
||||
</Badge>
|
||||
)}
|
||||
<Badge
|
||||
variant={candidate.naver_place_url ? 'success' : 'warning'}
|
||||
className="text-[10px]"
|
||||
>
|
||||
{candidate.naver_place_url
|
||||
? '네이버 플레이스 찾음'
|
||||
: '네이버 플레이스 못 찾음'}
|
||||
</Badge>
|
||||
</div>
|
||||
<p className="mt-1.5 flex items-start gap-1 text-xs text-muted-foreground">
|
||||
<MapPin className="mt-px size-3 shrink-0" />
|
||||
<span>{candidate.road_address ?? candidate.address ?? '주소 없음'}</span>
|
||||
</p>
|
||||
{candidate.phone && (
|
||||
<p className="mt-0.5 flex items-center gap-1 text-xs text-muted-foreground">
|
||||
<Phone className="size-3 shrink-0" />
|
||||
{candidate.phone}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
<span className="shrink-0 rounded-lg bg-primary px-3 py-1.5 text-[11px] font-bold text-primary-foreground">
|
||||
{!candidate.naver_place_url
|
||||
? 'URL 필요'
|
||||
: search.isConfirming && pickedIndex === index
|
||||
? '확정 중...'
|
||||
: '이 가게예요'}
|
||||
</span>
|
||||
</div>
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
|
||||
{!search.candidates.some((candidate) => candidate.naver_place_url) ? (
|
||||
<PlaceUrlBox
|
||||
value={placeUrl}
|
||||
onChange={setPlaceUrl}
|
||||
onSubmit={() => void pickByUrl()}
|
||||
isBusy={search.isConfirming}
|
||||
searchQuery={[storeName, location].filter(Boolean).join(' ')}
|
||||
/>
|
||||
) : (
|
||||
<PlaceUrlBox
|
||||
value={placeUrl}
|
||||
onChange={setPlaceUrl}
|
||||
onSubmit={() => void pickByUrl()}
|
||||
isBusy={search.isConfirming}
|
||||
compact
|
||||
searchQuery={[storeName, location].filter(Boolean).join(' ')}
|
||||
/>
|
||||
)}
|
||||
|
||||
</div>
|
||||
)}
|
||||
|
||||
{stage === 'unavailable' && (
|
||||
<div className="space-y-3">
|
||||
<p className="rounded-xl border border-warning/30 bg-warning/10 p-3 text-xs leading-relaxed text-warning">
|
||||
<TriangleAlert className="mr-1 inline size-3.5 align-text-bottom" />
|
||||
{search.unavailableReason}
|
||||
</p>
|
||||
<PlaceUrlBox
|
||||
value={placeUrl}
|
||||
onChange={setPlaceUrl}
|
||||
onSubmit={() => void pickByUrl()}
|
||||
isBusy={search.isConfirming}
|
||||
searchQuery={[storeName, location].filter(Boolean).join(' ')}
|
||||
/>
|
||||
|
||||
<Button variant="outline" className="w-full" onClick={runSearch}>
|
||||
<Search />
|
||||
<span>상호로 다시 검색하기</span>
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{stage === 'confirmed' && confirmedIdentity && (
|
||||
<div className="space-y-3">
|
||||
<div className="rounded-2xl border border-success/40 bg-success/5 p-6 text-center">
|
||||
<span className="mx-auto mb-3 flex size-12 items-center justify-center rounded-full bg-success text-white">
|
||||
<Check className="size-6" strokeWidth={3} />
|
||||
</span>
|
||||
<p className="text-base font-bold">{confirmedIdentity.name}</p>
|
||||
{confirmedIdentity.address && (
|
||||
<p className="mt-1 text-xs text-muted-foreground">{confirmedIdentity.address}</p>
|
||||
)}
|
||||
{confirmedIdentity.phone && (
|
||||
<p className="mt-0.5 text-xs text-muted-foreground">{confirmedIdentity.phone}</p>
|
||||
)}
|
||||
<div className="mt-3 flex items-center justify-center gap-1.5">
|
||||
{confirmedIdentity.origin === 'external' ? (
|
||||
<>
|
||||
<Badge variant="outline" className="text-[10px]">
|
||||
{confirmedIdentity.sourceLabel}
|
||||
</Badge>
|
||||
<Badge variant="success" className="text-[10px]">
|
||||
동일 업소 확인됨
|
||||
</Badge>
|
||||
</>
|
||||
) : (
|
||||
<Badge variant="warning" className="text-[10px]">
|
||||
직접 입력 · 동일 업소 미검증
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
variant="primary"
|
||||
size="lg"
|
||||
className="w-full"
|
||||
onClick={() => goToStep(3)}
|
||||
>
|
||||
<span>다음: 이 가게 정보 수집하기</span>
|
||||
<ArrowRight />
|
||||
</Button>
|
||||
<Button variant="ghost" size="sm" className="w-full" onClick={backToInput}>
|
||||
<Search />
|
||||
<span>다른 가게로 다시 찾기</span>
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</WizardStage>
|
||||
|
||||
<WizardFooter
|
||||
hint={
|
||||
confirmedIdentity
|
||||
? `${confirmedIdentity.name} 기준으로 진행합니다.`
|
||||
: '내 가게를 확인해야 다음 단계로 갈 수 있습니다.'
|
||||
}
|
||||
onPrev={() => goToStep(1)}
|
||||
onNext={() => goToStep(3)}
|
||||
nextLabel="다음: 데이터 수집"
|
||||
nextDisabled={!confirmedIdentity}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,513 @@
|
||||
import {useEffect, useRef, useState} from 'react';
|
||||
import {ArrowRight, Check, Loader2, MapPin, Pencil, Search, TriangleAlert} from 'lucide-react';
|
||||
import {Badge} from '@/components/ui/badge';
|
||||
import {Button} from '@/components/ui/button';
|
||||
import {Input} from '@/components/ui/input';
|
||||
import {Switch} from '@/components/ui/switch';
|
||||
import {INDUSTRY_CONFIGS} from '@/data/industryData';
|
||||
import {cn} from '@/lib/utils';
|
||||
import {useBuilderStore, useUnverifiedFields} from '@/stores/builder';
|
||||
import {ChannelConfirmPanel} from './ChannelConfirmPanel';
|
||||
import {ChannelUrlInput} from './ChannelUrlInput';
|
||||
import {useCollectFlow} from './useCollectFlow';
|
||||
import {WizardFooter} from './WizardFooter';
|
||||
import {WizardStage, WizardWaiting} from './WizardStage';
|
||||
|
||||
const STAGE_TITLE: Record<string, string> = {
|
||||
ready: '내 가게 주소를 알려주세요',
|
||||
discovering: '공개 채널을 찾는 중입니다',
|
||||
channels: '이 채널들이 사장님 가게가 맞나요?',
|
||||
crawling: '정보를 수집하는 중입니다',
|
||||
review: '수집된 정보가 맞는지 확인해주세요',
|
||||
};
|
||||
|
||||
const STAGE_DESCRIPTION: Record<string, string> = {
|
||||
ready: '네이버 지도에서 복사한 주소 하나면 영업시간·전화·사진까지 그대로 가져옵니다.',
|
||||
discovering: '',
|
||||
channels: '링크를 열어 내 가게가 맞는지 확인한 뒤 확정해 주세요. 확정한 URL 만 크롤링합니다.',
|
||||
crawling: '',
|
||||
review: '찾은 값은 전부 출처와 함께 보여드립니다. 사장님이 [맞아요]를 누른 값만 사이트와 AI 검색 답변에 나갑니다.',
|
||||
};
|
||||
|
||||
/** 채널 URL 확인과 수집 결과 검토 단계. */
|
||||
export function Step3DataReview() {
|
||||
const industry = useBuilderStore((s) => s.industry);
|
||||
const storeName = useBuilderStore((s) => s.storeName);
|
||||
const confirmedIdentity = useBuilderStore((s) => s.confirmedIdentity);
|
||||
const gatherCompleted = useBuilderStore((s) => s.gatherCompleted);
|
||||
const infoFields = useBuilderStore((s) => s.infoFields);
|
||||
const photos = useBuilderStore((s) => s.photos);
|
||||
const goToStep = useBuilderStore((s) => s.goToStep);
|
||||
|
||||
const unverified = useUnverifiedFields();
|
||||
const placeId = confirmedIdentity?.placeId ?? null;
|
||||
const collect = useCollectFlow(placeId);
|
||||
const collectPhase = collect.phase;
|
||||
const startAutomaticCollect = collect.crawl;
|
||||
const autoCollectStarted = useRef(false);
|
||||
|
||||
// 2단계에서 네이버 플레이스를 URL로 확정하는 순간 채널도 함께 등록·확정된다.
|
||||
// 이 화면에 들어오면 추가 버튼 없이 곧바로 그 채널에서 수집을 시작한다.
|
||||
useEffect(() => {
|
||||
if (
|
||||
autoCollectStarted.current ||
|
||||
!placeId ||
|
||||
confirmedIdentity?.origin !== 'external' ||
|
||||
gatherCompleted ||
|
||||
collect.isCheckingActive ||
|
||||
collectPhase !== 'idle'
|
||||
) {
|
||||
return;
|
||||
}
|
||||
autoCollectStarted.current = true;
|
||||
void startAutomaticCollect();
|
||||
}, [
|
||||
placeId,
|
||||
confirmedIdentity?.origin,
|
||||
gatherCompleted,
|
||||
collect.isCheckingActive,
|
||||
collectPhase,
|
||||
startAutomaticCollect,
|
||||
]);
|
||||
// 사업장 동기화는 BuilderPage 가 한 곳에서 맡는다(같은 placeId 를 두 번 구독하지 않는다).
|
||||
const [activeTab, setActiveTab] = useState<'info' | 'photos'>('info');
|
||||
|
||||
const config = INDUSTRY_CONFIGS[industry];
|
||||
const canCollect = confirmedIdentity?.origin === 'external';
|
||||
/** 아직 실제 수집이 붙지 않은 줄들 — 업종 예시다. 그렇게 부른다. */
|
||||
const isSample = !confirmedIdentity || confirmedIdentity.origin === 'owner';
|
||||
|
||||
const stage =
|
||||
collect.phase === 'discovering'
|
||||
? 'discovering'
|
||||
: collect.phase === 'crawling'
|
||||
? 'crawling'
|
||||
: collect.phase === 'awaiting-confirm'
|
||||
? 'channels'
|
||||
: gatherCompleted || collect.phase === 'done'
|
||||
? 'review'
|
||||
: 'ready';
|
||||
|
||||
return (
|
||||
<div className="flex flex-1 flex-col justify-between bg-muted/30">
|
||||
<WizardStage
|
||||
current={3}
|
||||
wide={stage === 'review' || stage === 'channels'}
|
||||
title={STAGE_TITLE[stage]}
|
||||
description={STAGE_DESCRIPTION[stage]}
|
||||
>
|
||||
{stage === 'ready' && (
|
||||
<div className="space-y-3">
|
||||
<IdentityCard />
|
||||
|
||||
{/* ★ 자동 해석이 실패했다는 사실을 서버가 알려준 경우 —
|
||||
"수집했는데 아무것도 안 나왔다"로 끝나지 않게 다음 동작을 지목한다. */}
|
||||
{collect.naverPlaceMissing && (
|
||||
<p className="flex items-start gap-1.5 rounded-xl border border-warning/30 bg-warning/10 p-3 text-[11px] leading-relaxed text-warning">
|
||||
<TriangleAlert className="mt-px size-3.5 shrink-0" />
|
||||
<span>
|
||||
<strong>네이버 플레이스를 자동으로 찾지 못했습니다.</strong> 아래에 내 가게의
|
||||
네이버 지도 주소를 직접 붙여넣어 주세요 — 그러면 확실하게 가져옵니다.
|
||||
</span>
|
||||
</p>
|
||||
)}
|
||||
|
||||
{/* ★ 1순위 경로. URL 만 있으면 100% 되므로 화면에서도 맨 위에 둔다. */}
|
||||
{canCollect && <ChannelUrlInput onAdd={collect.addLink} isBusy={collect.isAdding} />}
|
||||
|
||||
{canCollect && (
|
||||
<Button
|
||||
variant="primary"
|
||||
size="lg"
|
||||
className="w-full"
|
||||
onClick={collect.crawl}
|
||||
disabled={collect.confirmedCount === 0}
|
||||
>
|
||||
<Search />
|
||||
<span>
|
||||
{collect.confirmedCount === 0
|
||||
? '주소를 먼저 붙여넣어 주세요'
|
||||
: `등록한 ${collect.confirmedCount}개 주소에서 정보 가져오기`}
|
||||
</span>
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{/* 부차 경로 — 남겨두되 기대치를 정직하게 적는다. 실측 성공률이 낮다. */}
|
||||
{canCollect && (
|
||||
<div className="rounded-2xl border border-border bg-card p-4">
|
||||
<p className="text-xs font-bold">주소를 못 찾겠으면</p>
|
||||
<p className="mt-1 text-[11px] leading-relaxed text-muted-foreground">
|
||||
상호로 {config.channels.map((c) => c.name).join(' · ')} 등 공개 채널을 대신
|
||||
찾아봅니다. <strong>못 찾을 수 있습니다</strong> — 상호 표기가 조금만 달라도
|
||||
실패합니다. 그때는 위에 주소를 붙여넣어 주세요.
|
||||
</p>
|
||||
<label
|
||||
htmlFor="discover-public-channels"
|
||||
className="mt-3 flex cursor-pointer items-start justify-between gap-3 rounded-xl border border-border bg-muted/40 p-3"
|
||||
>
|
||||
<span>
|
||||
<span className="block text-xs font-semibold">추가 채널까지 AI로 찾기</span>
|
||||
<span className="mt-0.5 block text-[10px] leading-relaxed text-muted-foreground">
|
||||
Perplexity 유료 검색을 1회 사용합니다. URL만 후보로 저장하며, 확인한 링크만
|
||||
에디터와 사이트 푸터에 표시됩니다.
|
||||
</span>
|
||||
</span>
|
||||
<Switch
|
||||
id="discover-public-channels"
|
||||
checked={collect.discoverChannels}
|
||||
onCheckedChange={collect.setDiscoverChannels}
|
||||
aria-label="Perplexity로 추가 공개 채널 찾기"
|
||||
/>
|
||||
</label>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="mt-2.5 w-full"
|
||||
onClick={collect.discover}
|
||||
>
|
||||
<Search />
|
||||
<span>자동으로 찾아보기</span>
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{confirmedIdentity?.origin === 'owner' && (
|
||||
<>
|
||||
<p className="rounded-xl border border-warning/30 bg-warning/10 p-3 text-[11px] leading-relaxed text-warning">
|
||||
직접 입력으로 진행 중이라 수집이 열리지 않습니다. 동일 업소 검증을 통과한
|
||||
가게만 채널을 긁을 수 있습니다 — 2단계에서 지도 검색으로 가게를 확인하시면
|
||||
주소 붙여넣기와 자동 찾기가 모두 열립니다.
|
||||
</p>
|
||||
<Button variant="outline" className="w-full" onClick={() => goToStep(4)}>
|
||||
<span>수집 없이 다음 단계로</span>
|
||||
<ArrowRight />
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
|
||||
<Button variant="ghost" size="sm" className="w-full" onClick={() => goToStep(2)}>
|
||||
가게를 다시 찾을게요
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{stage === 'discovering' && (
|
||||
<WizardWaiting
|
||||
title="공개된 채널 URL 을 찾는 중입니다"
|
||||
description={`${storeName}의 예약·지도·SNS 채널을 찾고 있어요`}
|
||||
/>
|
||||
)}
|
||||
|
||||
{stage === 'crawling' && (
|
||||
<WizardWaiting
|
||||
title="확정하신 채널에서 정보를 수집 중입니다"
|
||||
description="운영 정보와 사진을 정돈하고 있어요"
|
||||
/>
|
||||
)}
|
||||
|
||||
{stage === 'channels' && (
|
||||
<div className="space-y-3">
|
||||
<div className="rounded-2xl border border-border bg-card p-5">
|
||||
<ChannelConfirmPanel
|
||||
links={collect.links}
|
||||
confirmedCount={collect.confirmedCount}
|
||||
confirmingId={collect.confirmingId}
|
||||
onConfirm={collect.confirm}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<ChannelUrlInput onAdd={collect.addLink} isBusy={collect.isAdding} />
|
||||
|
||||
<Button
|
||||
variant="primary"
|
||||
size="lg"
|
||||
className="w-full"
|
||||
onClick={collect.crawl}
|
||||
disabled={collect.confirmedCount === 0}
|
||||
>
|
||||
<Search />
|
||||
<span>
|
||||
{collect.confirmedCount === 0
|
||||
? '확정한 채널이 없습니다'
|
||||
: `확정한 ${collect.confirmedCount}개 채널에서 수집하기`}
|
||||
</span>
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{stage === 'review' && (
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
{isSample ? (
|
||||
<Badge variant="warning">예시 데이터 ({infoFields.length}개 항목)</Badge>
|
||||
) : (
|
||||
<Badge variant="success">수집 완료 ({infoFields.length}개 항목)</Badge>
|
||||
)}
|
||||
{unverified.length > 0 && (
|
||||
<Badge variant="warning">확인 필요 {unverified.length}</Badge>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-1 rounded-lg bg-muted p-0.5 text-xs">
|
||||
{(['info', 'photos'] as const).map((tab) => (
|
||||
<button
|
||||
key={tab}
|
||||
type="button"
|
||||
onClick={() => setActiveTab(tab)}
|
||||
className={cn(
|
||||
'cursor-pointer rounded-md px-3 py-1 font-medium transition-all',
|
||||
activeTab === tab
|
||||
? 'bg-card font-semibold text-foreground shadow-xs'
|
||||
: 'text-muted-foreground hover:text-foreground',
|
||||
)}
|
||||
>
|
||||
{tab === 'info' ? `기본정보 (${infoFields.length})` : `사진 (${photos.length})`}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{isSample && (
|
||||
<p className="rounded-xl border border-warning/30 bg-warning/10 p-3 text-[11px] leading-relaxed text-warning">
|
||||
<strong>상호·주소는 2단계에서 확인하신 값</strong>이고, 나머지 줄과 사진은 아직
|
||||
실제 수집 결과가 아니라 <strong>{config.name} 업종 예시</strong>입니다.
|
||||
</p>
|
||||
)}
|
||||
|
||||
{activeTab === 'info' ? (
|
||||
<ul className="space-y-2">
|
||||
{infoFields.map((field) => (
|
||||
<FieldRow key={field.id} fieldId={field.id} />
|
||||
))}
|
||||
</ul>
|
||||
) : (
|
||||
<div className="grid grid-cols-2 gap-2 sm:grid-cols-3">
|
||||
{photos.map((photo) => (
|
||||
<figure
|
||||
key={photo.id}
|
||||
className="group relative aspect-4/3 overflow-hidden rounded-xl border border-border bg-muted"
|
||||
>
|
||||
<img
|
||||
src={photo.url}
|
||||
alt={photo.title}
|
||||
loading="lazy"
|
||||
className="size-full object-cover transition-transform duration-300 group-hover:scale-105"
|
||||
/>
|
||||
<figcaption className="absolute inset-x-0 bottom-0 truncate bg-gradient-to-t from-black/70 to-transparent p-2 text-[11px] text-white">
|
||||
{photo.title}
|
||||
</figcaption>
|
||||
</figure>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<Button variant="primary" size="lg" className="w-full" onClick={() => goToStep(4)}>
|
||||
<span>다음: 템플릿 고르기</span>
|
||||
<ArrowRight />
|
||||
</Button>
|
||||
<label
|
||||
htmlFor="rediscover-public-channels"
|
||||
className="flex cursor-pointer items-center justify-between gap-3 rounded-xl border border-border bg-card p-3"
|
||||
>
|
||||
<span>
|
||||
<span className="block text-xs font-semibold">추가 채널 URL도 다시 찾기</span>
|
||||
<span className="block text-[10px] text-muted-foreground">
|
||||
켜면 다음 수집에서 Perplexity 유료 검색을 1회 사용합니다.
|
||||
</span>
|
||||
</span>
|
||||
<Switch
|
||||
id="rediscover-public-channels"
|
||||
checked={collect.discoverChannels}
|
||||
onCheckedChange={collect.setDiscoverChannels}
|
||||
aria-label="Perplexity로 추가 공개 채널 다시 찾기"
|
||||
/>
|
||||
</label>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="w-full"
|
||||
onClick={collect.discover}
|
||||
disabled={!canCollect}
|
||||
>
|
||||
<Search />
|
||||
<span>채널 URL 다시 찾기</span>
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</WizardStage>
|
||||
|
||||
<WizardFooter
|
||||
hint={
|
||||
stage === 'ready' ? (
|
||||
'수집을 먼저 돌려야 다음으로 넘어갈 수 있습니다.'
|
||||
) : stage === 'channels' ? (
|
||||
'내 채널을 확정한 뒤 수집하면 다음으로 넘어갑니다.'
|
||||
) : stage === 'review' && unverified.length > 0 ? (
|
||||
<span className="flex items-center gap-1 text-warning">
|
||||
<TriangleAlert className="size-3.5" />
|
||||
확인 안 된 항목 {unverified.length}개는 사이트에 나가지 않습니다.
|
||||
</span>
|
||||
) : stage === 'review' ? (
|
||||
'확인된 값만 사이트와 AI 검색 답변에 실립니다.'
|
||||
) : (
|
||||
'수집을 돌리면 찾은 값이 출처와 함께 여기에 나옵니다.'
|
||||
)
|
||||
}
|
||||
onPrev={() => goToStep(2)}
|
||||
onNext={() => goToStep(4)}
|
||||
nextLabel="다음: 템플릿 선택"
|
||||
/**
|
||||
* ★ 수집 전에는 잠근다.
|
||||
* 여기서 그냥 넘어가면 fact 도 사진도 없는 채로 템플릿을 고르고 발행까지 가서,
|
||||
* 서버 게이트가 NO_UNIQUE_CONTENT 로 막는다 — 사장님은 세 화면을 지나온 뒤에야
|
||||
* "처음부터 아무것도 없었다"는 사실을 알게 된다. 그 전에 막는 것이 맞다.
|
||||
*/
|
||||
nextDisabled={stage !== 'review'}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** 2단계에서 확인된 가게 — 3단계 내내 "무엇을 수집하는지"의 근거로 남는다. */
|
||||
function IdentityCard() {
|
||||
const confirmedIdentity = useBuilderStore((s) => s.confirmedIdentity);
|
||||
|
||||
if (!confirmedIdentity) {
|
||||
return (
|
||||
<div className="rounded-xl border border-warning/30 bg-warning/10 p-4 text-xs text-warning">
|
||||
아직 가게를 확인하지 않았습니다. 2단계에서 내 가게를 먼저 골라주세요.
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="rounded-2xl border border-border bg-card p-5">
|
||||
<p className="text-sm font-bold">{confirmedIdentity.name}</p>
|
||||
{confirmedIdentity.address && (
|
||||
<p className="mt-1 flex items-start gap-1 text-xs text-muted-foreground">
|
||||
<MapPin className="mt-px size-3 shrink-0" />
|
||||
<span>{confirmedIdentity.address}</span>
|
||||
</p>
|
||||
)}
|
||||
<div className="mt-2.5 flex items-center gap-1.5">
|
||||
{confirmedIdentity.origin === 'external' ? (
|
||||
<>
|
||||
<Badge variant="outline" className="text-[10px]">
|
||||
{confirmedIdentity.sourceLabel}
|
||||
</Badge>
|
||||
<Badge variant="success" className="text-[10px]">
|
||||
동일 업소 확인됨
|
||||
</Badge>
|
||||
</>
|
||||
) : (
|
||||
<Badge variant="warning" className="text-[10px]">
|
||||
직접 입력 · 동일 업소 미검증
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 수집된 값 한 줄 — 확인이 이 화면의 목적이므로 [맞아요]/[아니에요]가 줄 안에 있다.
|
||||
*
|
||||
* ★ 승인은 스토어의 verifyField 가 그대로 fact 전이 API 로 올린다 —
|
||||
* 화면만 바뀌고 서버가 모르는 승인은 없다.
|
||||
*/
|
||||
function FieldRow({fieldId}: {fieldId: string}) {
|
||||
const field = useBuilderStore((s) => s.infoFields.find((f) => f.id === fieldId));
|
||||
const savingFieldIds = useBuilderStore((s) => s.savingFieldIds);
|
||||
const verifyField = useBuilderStore((s) => s.verifyField);
|
||||
|
||||
const [isEditing, setIsEditing] = useState(false);
|
||||
const [draft, setDraft] = useState('');
|
||||
|
||||
if (!field) return null;
|
||||
|
||||
const isSaving = savingFieldIds.includes(field.id);
|
||||
const needsCheck = field.requiresVerification && !field.isVerified;
|
||||
|
||||
const openEditor = () => {
|
||||
setDraft(field.value);
|
||||
setIsEditing(true);
|
||||
};
|
||||
|
||||
const submit = () => {
|
||||
const trimmed = draft.trim();
|
||||
if (trimmed) verifyField(field.id, trimmed);
|
||||
setIsEditing(false);
|
||||
};
|
||||
|
||||
return (
|
||||
<li
|
||||
className={cn(
|
||||
'rounded-xl border p-3 text-xs transition-colors',
|
||||
needsCheck ? 'border-warning/40 bg-warning/5' : 'border-border bg-card',
|
||||
)}
|
||||
>
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="mb-0.5 flex flex-wrap items-center gap-1.5">
|
||||
<span className="font-semibold">{field.label}</span>
|
||||
{field.source && (
|
||||
<Badge variant="outline" className="text-[10px]">
|
||||
{field.source}
|
||||
</Badge>
|
||||
)}
|
||||
{field.critical && (
|
||||
<Badge variant="warning" className="text-[10px]">
|
||||
예약 관련
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
<p className="font-medium">{field.value}</p>
|
||||
</div>
|
||||
|
||||
{needsCheck ? (
|
||||
<div className="flex shrink-0 items-center gap-1">
|
||||
<Button
|
||||
size="sm"
|
||||
variant="primary"
|
||||
onClick={() => verifyField(field.id)}
|
||||
disabled={isSaving}
|
||||
>
|
||||
{isSaving ? <Loader2 className="animate-spin" /> : <Check />}
|
||||
<span>맞아요</span>
|
||||
</Button>
|
||||
<Button size="sm" variant="outline" onClick={openEditor} disabled={isSaving}>
|
||||
<Pencil />
|
||||
<span>아니에요</span>
|
||||
</Button>
|
||||
</div>
|
||||
) : (
|
||||
<Badge variant="success" className="shrink-0">
|
||||
확인됨
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{isEditing && (
|
||||
<div className="mt-2 flex items-center gap-1.5 border-t border-border pt-2">
|
||||
<Input
|
||||
value={draft}
|
||||
onChange={(e) => setDraft(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter') submit();
|
||||
if (e.key === 'Escape') setIsEditing(false);
|
||||
}}
|
||||
placeholder={`${field.label}의 정확한 값`}
|
||||
autoFocus
|
||||
/>
|
||||
<Button size="sm" variant="primary" onClick={submit} disabled={!draft.trim()}>
|
||||
저장
|
||||
</Button>
|
||||
<Button size="sm" variant="ghost" onClick={() => setIsEditing(false)}>
|
||||
취소
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</li>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
import {Check} from 'lucide-react';
|
||||
import {INDUSTRY_CONFIGS} from '@/data/industryData';
|
||||
import {queueSiteTemplateSave} from '@/features/publish/siteTemplate';
|
||||
import {cn} from '@/lib/utils';
|
||||
import {useBuilderStore} from '@/stores/builder';
|
||||
import {WizardFooter} from './WizardFooter';
|
||||
import {WizardSteps} from './WizardSteps';
|
||||
|
||||
export function Step4Template() {
|
||||
const industry = useBuilderStore((s) => s.industry);
|
||||
const templateId = useBuilderStore((s) => s.templateId);
|
||||
const placeId = useBuilderStore((s) => s.placeId);
|
||||
const selectTemplate = useBuilderStore((s) => s.selectTemplate);
|
||||
const goToStep = useBuilderStore((s) => s.goToStep);
|
||||
const startGenerating = useBuilderStore((s) => s.startGenerating);
|
||||
|
||||
const config = INDUSTRY_CONFIGS[industry];
|
||||
|
||||
/**
|
||||
* 고른 순간 서버에도 남긴다.
|
||||
*
|
||||
* ★ 화면 상태로만 두면 발행 잡이 읽을 곳이 없어 업종 기본 템플릿으로 굽는다 —
|
||||
* 사장님이 고른 디자인과 실제 발행본이 갈린다. 저장은 화면을 기다리게 하지 않는다.
|
||||
*/
|
||||
const chooseTemplate = (id: string) => {
|
||||
selectTemplate(id);
|
||||
queueSiteTemplateSave(placeId, id);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex flex-1 flex-col justify-between bg-muted/30">
|
||||
<div className="flex flex-1 flex-col items-center justify-center px-4 py-10 sm:px-6 sm:py-14 lg:px-8">
|
||||
<div className="mx-auto flex w-full max-w-5xl flex-col">
|
||||
<WizardSteps current={4} />
|
||||
|
||||
<div className="mb-8 text-center">
|
||||
<h1 className="text-2xl font-bold tracking-tight sm:text-3xl">
|
||||
원하시는 디자인 스타일을 선택해주세요
|
||||
</h1>
|
||||
<p className="mx-auto mt-2 max-w-lg text-xs text-muted-foreground sm:text-sm">
|
||||
{config.name}에 맞춘 템플릿입니다. 색상과 서체는 에디터에서 언제든 바꿀 수 있고,
|
||||
어떤 템플릿을 골라도 구조화 데이터와 필수 섹션은 동일하게 들어갑니다.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2 sm:gap-5 lg:grid-cols-3">
|
||||
{config.templates.map((template) => {
|
||||
const isSelected = templateId === template.id;
|
||||
|
||||
return (
|
||||
<button
|
||||
key={template.id}
|
||||
type="button"
|
||||
onClick={() => chooseTemplate(template.id)}
|
||||
aria-pressed={isSelected}
|
||||
className={cn(
|
||||
'flex cursor-pointer flex-col justify-between rounded-2xl border bg-card p-5 text-left transition-all',
|
||||
isSelected
|
||||
? 'border-primary ring-1 ring-primary'
|
||||
: 'border-border hover:border-muted-foreground/30',
|
||||
)}
|
||||
>
|
||||
<div className="mb-3 flex items-start justify-between">
|
||||
<div>
|
||||
<h2 className="text-base font-bold">{template.name}</h2>
|
||||
<span className="text-xs font-medium text-muted-foreground">
|
||||
{template.toneLabel} · {template.fontStyle}
|
||||
</span>
|
||||
</div>
|
||||
<span
|
||||
className={cn(
|
||||
'flex size-5 shrink-0 items-center justify-center rounded-full transition-all',
|
||||
isSelected
|
||||
? 'bg-primary text-primary-foreground'
|
||||
: 'border border-border bg-card',
|
||||
)}
|
||||
>
|
||||
{isSelected && <Check className="size-3" strokeWidth={3} />}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* 색·레이아웃 미리보기 와이어프레임 */}
|
||||
<div className="my-3 space-y-2.5 rounded-xl border border-border bg-muted/50 p-3.5">
|
||||
<div className="flex items-center gap-1.5">
|
||||
{(['primary', 'secondary', 'card'] as const).map((key) => (
|
||||
<span
|
||||
key={key}
|
||||
className="size-3.5 rounded-full border border-black/10"
|
||||
style={{backgroundColor: template.colors[key]}}
|
||||
title={key}
|
||||
/>
|
||||
))}
|
||||
<span className="ml-1 font-mono text-[10px] text-muted-foreground">
|
||||
{template.colors.primary}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1.5 pt-1">
|
||||
<div
|
||||
className="h-2.5 w-2/3 rounded"
|
||||
style={{backgroundColor: template.colors.primary, opacity: 0.85}}
|
||||
/>
|
||||
<div className="h-1.5 w-full rounded bg-border" />
|
||||
<div className="h-1.5 w-4/5 rounded bg-border" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p className="text-xs leading-relaxed text-muted-foreground">
|
||||
{template.description}
|
||||
</p>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<WizardFooter
|
||||
onPrev={() => goToStep(3)}
|
||||
onNext={() => {
|
||||
// ★ 아무것도 안 누르고 넘어가는 경우(첫 템플릿이 이미 선택돼 있다)도 서버에 남긴다 —
|
||||
// 화면이 보여준 그 템플릿이 발행본이 되어야 한다. 같은 값이면 서버가 재빌드 표시도 찍지 않는다.
|
||||
queueSiteTemplateSave(placeId, templateId);
|
||||
startGenerating();
|
||||
}}
|
||||
nextLabel="이 템플릿으로 사이트 생성하기"
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
import {useCallback, useEffect} from 'react';
|
||||
import {useSearchParams} from 'react-router';
|
||||
import {Check, Loader2} from 'lucide-react';
|
||||
import {JobStatus} from '@o2o/shared';
|
||||
import {delay, getAccessToken, pollJob, startCopy} from '@/api';
|
||||
import {Progress} from '@/components/ui/progress';
|
||||
import {notify, notifyApiError} from '@/lib/notify';
|
||||
import {cn} from '@/lib/utils';
|
||||
import {EDITOR_STEP, useBuilderStore} from '@/stores/builder';
|
||||
|
||||
const BUILD_STEPS = [
|
||||
'수집된 사진 분류 및 대체 텍스트 생성',
|
||||
'브랜드 컬러 시스템 및 타이포그래피 조합',
|
||||
'확인된 사실만으로 소개 콘텐츠 구성',
|
||||
'위치 기반 길찾기 및 주변 정보 연동',
|
||||
'구조화 데이터(JSON-LD) 준비',
|
||||
];
|
||||
|
||||
const STAGE_MS = 600;
|
||||
|
||||
/**
|
||||
* ★ 잡은 PENDING/RUNNING/DONE 세 상태만 준다 — 단계별 progress 필드가 없다.
|
||||
* 그래서 문구는 "지금 서버가 이 근처를 하고 있다"는 안내이고, 진짜 신호는 잡 상태다.
|
||||
* RUNNING 동안 마지막 단계 직전까지만 올리고, 완료는 오직 DONE 이 만든다
|
||||
* — 100%를 먼저 그려 놓고 기다리게 하지 않는다.
|
||||
*/
|
||||
const RUNNING_STAGE_CEILING = BUILD_STEPS.length - 1;
|
||||
|
||||
export function Step5Generating() {
|
||||
const storeName = useBuilderStore((s) => s.storeName);
|
||||
const stage = useBuilderStore((s) => s.generateStage);
|
||||
const setGenerateStage = useBuilderStore((s) => s.setGenerateStage);
|
||||
const goToStep = useBuilderStore((s) => s.goToStep);
|
||||
const placeId = useBuilderStore((s) => s.placeId);
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
|
||||
/**
|
||||
* 생성이 끝나면 곧바로 에디터다.
|
||||
*
|
||||
* ★ 중간에 다른 화면을 끼우지 않는다. 위저드를 끝까지 걸어온 사람의 다음 용건은
|
||||
* 자기 사이트를 보는 것이고, 목록을 한 번 거치게 하면 그게 한 번 더 클릭이 된다.
|
||||
* 사업장은 이미 2단계에서 등록돼 목록에 들어가 있다 — '목록에 생기는 것'과
|
||||
* '목록으로 보내는 것'은 다른 얘기다.
|
||||
*/
|
||||
const finishOnboarding = useCallback(() => {
|
||||
const next = new URLSearchParams(searchParams);
|
||||
next.delete('flow');
|
||||
setSearchParams(next, {replace: true});
|
||||
goToStep(EDITOR_STEP);
|
||||
}, [goToStep, searchParams, setSearchParams]);
|
||||
|
||||
/**
|
||||
* 소개문·FAQ 생성(JobType.COPY). `POST /v1/place/{id}/copy` 로 잡을 넣고 폴링한다.
|
||||
*
|
||||
* ★ 정적 빌드(JobType.BUILD)는 여기가 아니라 발행 모달이 부른다 — 빌드는 발행 검수
|
||||
* 게이트와 한 몸이고(services/build_service), 여기서 미리 구워 봐야 편집 전 스냅샷이라
|
||||
* 버릴 버전만 쌓인다.
|
||||
* ★ 폴백: placeId(데모 경로) 나 토큰이 없으면 백엔드를 아예 부르지 않고 타이머로 돈다.
|
||||
*/
|
||||
useEffect(() => {
|
||||
const controller = new AbortController();
|
||||
|
||||
/** 타이머 시뮬레이션. 폴백 경로 전용 — 백엔드가 없어도 위저드는 끝까지 간다. */
|
||||
const runSimulation = async () => {
|
||||
for (let next = 1; next <= BUILD_STEPS.length; next += 1) {
|
||||
await delay(STAGE_MS, controller.signal);
|
||||
if (controller.signal.aborted) return;
|
||||
setGenerateStage(next);
|
||||
}
|
||||
await delay(STAGE_MS, controller.signal);
|
||||
if (!controller.signal.aborted) finishOnboarding();
|
||||
};
|
||||
|
||||
/** RUNNING 인 동안 문구만 천천히 밀어 준다. 완료 판정은 하지 않는다. */
|
||||
const creep = () =>
|
||||
setGenerateStage(
|
||||
Math.min(RUNNING_STAGE_CEILING, useBuilderStore.getState().generateStage + 1),
|
||||
);
|
||||
|
||||
const runCopy = async (id: string) => {
|
||||
let jobId: string;
|
||||
try {
|
||||
const started = await startCopy(id, {}, undefined, controller.signal);
|
||||
// ★ 근거로 쓸 확인된 fact 가 0 이면 서버는 아무것도 쓰지 않는다 — LLM 은 사실을 만들지 않는다.
|
||||
if (started.grounded_facts === 0) {
|
||||
notify.warn(
|
||||
'확인된 정보가 없어 소개문을 쓰지 않았습니다.',
|
||||
'[확인] 탭에서 수집된 정보를 확정하면 그 사실만으로 소개문을 씁니다.',
|
||||
);
|
||||
}
|
||||
if (!started.job_id) {
|
||||
await runSimulation();
|
||||
return;
|
||||
}
|
||||
jobId = started.job_id;
|
||||
} catch (error) {
|
||||
if (controller.signal.aborted) return;
|
||||
notifyApiError(error, '소개문 생성을 시작하지 못했습니다.');
|
||||
await runSimulation();
|
||||
return;
|
||||
}
|
||||
|
||||
setGenerateStage(1);
|
||||
const outcome = await pollJob(jobId, {
|
||||
signal: controller.signal,
|
||||
onTick: (job) => {
|
||||
if (job.status === JobStatus.RUNNING) creep();
|
||||
},
|
||||
});
|
||||
|
||||
if (outcome.kind === 'aborted') return;
|
||||
if (outcome.kind === 'dead') {
|
||||
notify.error('소개문을 만들지 못했습니다.', outcome.job.last_error ?? undefined);
|
||||
} else if (outcome.kind === 'unreachable') {
|
||||
notifyApiError(outcome.error, '생성 상태를 확인하지 못했습니다.');
|
||||
} else if (outcome.kind === 'timeout') {
|
||||
notify.warn('생성이 예상보다 오래 걸립니다.', '생성은 계속 진행됩니다.');
|
||||
}
|
||||
|
||||
// ★ 실패해도 편집기로는 보낸다. 소개문은 없어도 확인된 fact 로 편집·발행이 되고,
|
||||
// 여기서 멈추면 사장님은 되돌아갈 길이 없는 화면에 갇힌다.
|
||||
setGenerateStage(BUILD_STEPS.length);
|
||||
await delay(STAGE_MS, controller.signal);
|
||||
if (!controller.signal.aborted) finishOnboarding();
|
||||
};
|
||||
|
||||
if (!placeId || !getAccessToken()) void runSimulation();
|
||||
else void runCopy(placeId);
|
||||
|
||||
return () => controller.abort();
|
||||
}, [setGenerateStage, finishOnboarding, placeId]);
|
||||
|
||||
const progress = Math.min(100, Math.round((stage / BUILD_STEPS.length) * 100));
|
||||
|
||||
return (
|
||||
<div className="flex flex-1 flex-col items-center justify-center bg-muted/30 px-4 py-16 sm:px-6 sm:py-24 lg:px-8">
|
||||
<div className="mx-auto flex w-full max-w-md flex-col items-center text-center">
|
||||
<div className="mb-6 flex size-16 items-center justify-center rounded-2xl border border-border bg-card">
|
||||
<Loader2 className="size-8 animate-spin text-primary" />
|
||||
</div>
|
||||
|
||||
<h1 className="mb-2 text-2xl font-bold tracking-tight sm:text-3xl">
|
||||
웹사이트를 생성하고 있습니다
|
||||
</h1>
|
||||
<p className="mb-8 max-w-md text-xs text-muted-foreground sm:text-sm">
|
||||
<strong className="font-semibold text-foreground">{storeName}</strong>의 확인된 정보만
|
||||
담아 정적 페이지로 굽고 있어요.
|
||||
</p>
|
||||
|
||||
<div className="w-full space-y-4 rounded-2xl border border-border bg-card p-6 text-left">
|
||||
<div className="flex items-center justify-between text-xs">
|
||||
<span className="font-bold">{BUILD_STEPS[Math.min(stage - 1, BUILD_STEPS.length - 1)]}</span>
|
||||
<span className="font-mono font-bold">{progress}%</span>
|
||||
</div>
|
||||
|
||||
<Progress value={progress} aria-label="사이트 생성 진행률" />
|
||||
|
||||
<ol className="space-y-2.5 pt-2">
|
||||
{BUILD_STEPS.map((text, index) => {
|
||||
const num = index + 1;
|
||||
const isDone = stage > num;
|
||||
const isCurrent = stage === num;
|
||||
|
||||
return (
|
||||
<li
|
||||
key={text}
|
||||
className={cn(
|
||||
'flex items-center gap-3 text-xs transition-colors',
|
||||
isDone || isCurrent ? 'font-medium text-foreground' : 'text-muted-foreground',
|
||||
)}
|
||||
>
|
||||
<span
|
||||
className={cn(
|
||||
'flex size-4 shrink-0 items-center justify-center rounded-full text-[10px] font-bold',
|
||||
isDone || isCurrent
|
||||
? 'bg-primary text-primary-foreground'
|
||||
: 'border border-border bg-muted',
|
||||
isCurrent && 'ring-2 ring-primary/20',
|
||||
)}
|
||||
>
|
||||
{isDone ? <Check className="size-2.5" strokeWidth={3} /> : num}
|
||||
</span>
|
||||
<span className="truncate">{text}</span>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ol>
|
||||
</div>
|
||||
|
||||
<p className="mt-6 text-xs text-muted-foreground">
|
||||
생성이 끝나면 실시간 에디터로 자동 전환됩니다.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import type {ReactNode} from 'react';
|
||||
import {ArrowRight} from 'lucide-react';
|
||||
import {Button} from '@/components/ui/button';
|
||||
|
||||
interface WizardFooterProps {
|
||||
hint?: ReactNode;
|
||||
onPrev?: () => void;
|
||||
onNext: () => void;
|
||||
nextLabel: string;
|
||||
nextDisabled?: boolean;
|
||||
}
|
||||
|
||||
/** 위저드 3단계가 공유하는 하단 고정 CTA 바. */
|
||||
export function WizardFooter({
|
||||
hint,
|
||||
onPrev,
|
||||
onNext,
|
||||
nextLabel,
|
||||
nextDisabled,
|
||||
}: WizardFooterProps) {
|
||||
return (
|
||||
<div className="safe-b sticky bottom-0 z-30 w-full border-t border-border bg-card/95 px-4 py-3 backdrop-blur-md sm:px-6 lg:px-8">
|
||||
<div className="mx-auto flex max-w-5xl flex-col items-center justify-between gap-3 sm:flex-row">
|
||||
<div className="text-center text-xs text-muted-foreground sm:text-left">{hint}</div>
|
||||
<div className="flex w-full items-center justify-end gap-2 sm:w-auto">
|
||||
{onPrev && (
|
||||
<Button variant="outline" onClick={onPrev}>
|
||||
이전
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
variant="primary"
|
||||
onClick={onNext}
|
||||
disabled={nextDisabled}
|
||||
className="flex-1 sm:flex-none"
|
||||
>
|
||||
<span>{nextLabel}</span>
|
||||
<ArrowRight />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
import type {ReactNode} from 'react';
|
||||
import {WizardSteps} from './WizardSteps';
|
||||
|
||||
/**
|
||||
* 위저드 한 화면.
|
||||
*
|
||||
* ★ 한 번에 한 가지만 묻는다. 입력 폼과 결과 목록을 좌우로 같이 띄우면, 사장님은
|
||||
* "지금 내가 뭘 해야 하는지"를 화면에서 찾아야 한다. 그래서 단계마다 패널 하나만 세운다 —
|
||||
* 묻는 것이 바뀌면 화면이 통째로 바뀐다.
|
||||
*/
|
||||
export function WizardStage({
|
||||
current,
|
||||
title,
|
||||
description,
|
||||
children,
|
||||
wide,
|
||||
}: {
|
||||
current: number;
|
||||
title: ReactNode;
|
||||
description?: ReactNode;
|
||||
children: ReactNode;
|
||||
/** 목록처럼 폭이 필요한 패널에서만 넓힌다(기본은 좁은 한 칸). */
|
||||
wide?: boolean;
|
||||
}) {
|
||||
return (
|
||||
<div className="flex flex-1 flex-col items-center overflow-y-auto px-4 py-10 sm:px-6 sm:py-14">
|
||||
<div className="mx-auto flex w-full max-w-5xl flex-col">
|
||||
<WizardSteps current={current} />
|
||||
|
||||
<div className="mb-8 text-center">
|
||||
<h1 className="text-2xl font-bold tracking-tight sm:text-3xl">{title}</h1>
|
||||
{description && (
|
||||
<p className="mx-auto mt-2.5 max-w-xl text-xs leading-relaxed text-muted-foreground sm:text-sm">
|
||||
{description}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className={wide ? 'mx-auto w-full max-w-2xl' : 'mx-auto w-full max-w-lg'}>
|
||||
{children}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** 단계 안에서 기다리는 화면(검색·수집). 스피너 하나와 지금 하는 일만 보여준다. */
|
||||
export function WizardWaiting({title, description}: {title: string; description?: ReactNode}) {
|
||||
return (
|
||||
<div className="flex flex-col items-center gap-4 rounded-2xl border border-border bg-card p-10 text-center">
|
||||
<span className="size-9 animate-spin rounded-full border-2 border-primary border-t-transparent" />
|
||||
<div className="space-y-1">
|
||||
<h2 className="text-sm font-bold">{title}</h2>
|
||||
{description && <p className="text-xs text-muted-foreground">{description}</p>}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import {Check} from 'lucide-react';
|
||||
import {cn} from '@/lib/utils';
|
||||
|
||||
/**
|
||||
* 위저드 진행 표시.
|
||||
*
|
||||
* 2(신원 확인)와 3(사실 확인)이 왜 따로인지 사장님이 한눈에 알게 하는 것이 이 줄의 목적이다 —
|
||||
* "가게가 맞나" 를 먼저 끝내고 "값이 맞나" 로 넘어간다.
|
||||
*/
|
||||
const STEPS = [
|
||||
{step: 1, label: '업종'},
|
||||
{step: 2, label: '내 가게 확인'},
|
||||
{step: 3, label: '수집 정보 확인'},
|
||||
{step: 4, label: '템플릿'},
|
||||
] as const;
|
||||
|
||||
export function WizardSteps({current}: {current: number}) {
|
||||
return (
|
||||
<ol className="mx-auto mb-8 flex w-full max-w-xl items-center justify-between gap-1">
|
||||
{STEPS.map(({step, label}, index) => {
|
||||
const isDone = current > step;
|
||||
const isCurrent = current === step;
|
||||
|
||||
return (
|
||||
<li key={step} className="flex flex-1 items-center gap-1 last:flex-none">
|
||||
<div className="flex items-center gap-1.5">
|
||||
<span
|
||||
className={cn(
|
||||
'flex size-5 shrink-0 items-center justify-center rounded-full text-[10px] font-bold transition-colors',
|
||||
isDone
|
||||
? 'bg-success text-white'
|
||||
: isCurrent
|
||||
? 'bg-primary text-primary-foreground ring-4 ring-primary/15'
|
||||
: 'border border-border bg-muted text-muted-foreground',
|
||||
)}
|
||||
>
|
||||
{isDone ? <Check className="size-3" strokeWidth={3} /> : step}
|
||||
</span>
|
||||
<span
|
||||
className={cn(
|
||||
'whitespace-nowrap text-[11px] transition-colors',
|
||||
isCurrent ? 'font-bold text-foreground' : 'text-muted-foreground',
|
||||
)}
|
||||
>
|
||||
{label}
|
||||
</span>
|
||||
</div>
|
||||
{index < STEPS.length - 1 && (
|
||||
<span
|
||||
className={cn(
|
||||
'mx-1 hidden h-px flex-1 sm:block',
|
||||
isDone ? 'bg-success/40' : 'bg-border',
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ol>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
/**
|
||||
* 수집 잡 결과(`job.result`) 판독 — 순수 함수만.
|
||||
*
|
||||
* ★ `job.result` 는 백엔드가 관측·디버깅용으로 넣어 둔 JSONB 라 타입이 없다.
|
||||
* 화면이 그걸 여기저기서 직접 파헤치면, 백엔드가 키 하나를 바꿔도 조용히 0 건으로 보인다.
|
||||
* 읽는 규칙을 한 곳에 모은다 — 기준은 backend/services/collect_service.py 의 반환값이다.
|
||||
*/
|
||||
import type {JobData} from '@/api';
|
||||
|
||||
/**
|
||||
* 잡 결과에서 숫자 한 칸만 좁혀 읽는다.
|
||||
*
|
||||
* `job.result` 는 잡 종류마다 모양이 달라 스키마상 unknown 이다(readNaverPlaceMissing 과 같은 이유).
|
||||
* 없으면 0 — 서버가 필드를 빼도 토스트가 `undefined 건` 이 되지 않는다.
|
||||
*/
|
||||
export function readNumber(source: unknown, key: string): number {
|
||||
if (!source || typeof source !== 'object') return 0;
|
||||
const value = (source as Record<string, unknown>)[key];
|
||||
return typeof value === 'number' ? value : 0;
|
||||
}
|
||||
|
||||
/** 결과 안의 하위 묶음(facts · media)을 꺼낸다. */
|
||||
export function readGroup(job: JobData, key: string): unknown {
|
||||
const result: unknown = job.result;
|
||||
if (!result || typeof result !== 'object') return null;
|
||||
return (result as Record<string, unknown>)[key];
|
||||
}
|
||||
|
||||
/**
|
||||
* 서버가 남긴 사유 한 줄(`result.note`).
|
||||
*
|
||||
* ★ "왜 아무것도 안 들어왔는지"는 서버만 안다("크롤링 대상이 없다" 등).
|
||||
* 화면이 추측해서 지어내지 않고, 있으면 그대로 보여준다.
|
||||
*/
|
||||
export function readNote(job: JobData): string | undefined {
|
||||
const result: unknown = job.result;
|
||||
if (!result || typeof result !== 'object') return undefined;
|
||||
const note = (result as {note?: unknown}).note;
|
||||
return typeof note === 'string' && note.trim() ? note : undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* 잡 결과에서 "네이버 플레이스를 자동으로 못 찾았다" 플래그만 꺼낸다.
|
||||
*
|
||||
* `job.result` 는 잡 종류마다 모양이 달라 스키마상 unknown 이다. 통째로 캐스팅하지 않고
|
||||
* 이 한 칸만 좁혀서 읽는다 — 서버가 필드를 안 실어도 화면은 그냥 조용해질 뿐이다.
|
||||
*/
|
||||
export function readNaverPlaceMissing(job: JobData): boolean {
|
||||
const result: unknown = job.result;
|
||||
if (!result || typeof result !== 'object') return false;
|
||||
return (result as {naver_place_missing?: unknown}).naver_place_missing === true;
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
/**
|
||||
* 수집에 딸린 잡 실행과 캐시 정리 — React 를 모르는 부분.
|
||||
*
|
||||
* ★ 훅 상태를 건드리지 않는 일만 모았다. 하는 일은 "잡을 넣고 → 폴링하고 → 캐시를
|
||||
* 무효화하고 → 결과를 알린다" 뿐이라 컴포넌트 마운트와 아무 상관이 없다. 훅 안에 두면
|
||||
* 수집 흐름(단계 전이)과 잡 실행이 한 덩어리로 보여 어느 쪽을 고치는지 흐려진다.
|
||||
*/
|
||||
import type {JobData} from '@/api';
|
||||
import {
|
||||
getGetPlaceQueryKey,
|
||||
getListFactsQueryKey,
|
||||
getListFaqsQueryKey,
|
||||
getListLinksQueryKey,
|
||||
getListMediaQueryKey,
|
||||
pollJob,
|
||||
startCopy,
|
||||
startVision,
|
||||
} from '@/api';
|
||||
import {notify, notifyApiError} from '@/lib/notify';
|
||||
import {queryClient} from '@/lib/query-client';
|
||||
import {notifyCopy, notifyVision} from './collectNotify';
|
||||
import type {RecollectTask} from './useCollectFlow';
|
||||
|
||||
/** 재수집 작업의 화면 표시명. */
|
||||
export const RECOLLECT_LABEL: Record<RecollectTask, string> = {
|
||||
facts: '정보',
|
||||
photos: '사진',
|
||||
copy: '소개문',
|
||||
};
|
||||
|
||||
/**
|
||||
* 사진 분석 · 소개문 생성 잡 1회분.
|
||||
*
|
||||
* 수집(runCollect)과 달리 훅 상태를 건드리지 않아 모듈 함수로 둔다 —
|
||||
* 하는 일은 "잡을 넣고 → 폴링하고 → 캐시를 무효화하고 → 결과를 알린다" 뿐이다.
|
||||
*/
|
||||
export async function runSideJob(task: 'photos' | 'copy', placeId: string, signal: AbortSignal) {
|
||||
const label = RECOLLECT_LABEL[task];
|
||||
let jobId: string;
|
||||
try {
|
||||
const started =
|
||||
task === 'photos'
|
||||
? // ★ force:true — 이미 alt 가 붙은 사진도 다시 분석한다. 사장님이 일부러 누른 버튼이라
|
||||
// "분석할 사진이 없습니다"로 끝나면 재분석이라는 이름값을 못 한다.
|
||||
await startVision(placeId, {force: true}, undefined, signal)
|
||||
: await startCopy(placeId, {}, undefined, signal);
|
||||
// 거절도 HTTP 200 이다 — 사진 0장(MEDIA_NOT_FOUND)·근거 부족(FAQ_UNGROUNDED)·
|
||||
// 키 미설정(GENERATOR_NOT_CONFIGURED)이 전부 이 자리로 온다.
|
||||
if (started.result?.success === false || !started.job_id) {
|
||||
notifyApiError({data: started}, `${label}을 시작하지 못했습니다.`);
|
||||
return;
|
||||
}
|
||||
jobId = started.job_id;
|
||||
} catch (error) {
|
||||
if (signal.aborted) return;
|
||||
notifyApiError(error, `${label}을 시작하지 못했습니다.`);
|
||||
return;
|
||||
}
|
||||
|
||||
const outcome = await pollJob(jobId, {signal});
|
||||
switch (outcome.kind) {
|
||||
case 'aborted':
|
||||
return;
|
||||
case 'dead':
|
||||
notify.error(`${label}을 끝내지 못했습니다.`, outcome.job.last_error ?? undefined);
|
||||
return;
|
||||
case 'unreachable':
|
||||
notifyApiError(outcome.error, `${label} 상태를 확인하지 못했습니다.`);
|
||||
return;
|
||||
case 'timeout':
|
||||
notify.warn(
|
||||
`${label}이 예상보다 오래 걸립니다.`,
|
||||
'서버에서는 계속 진행됩니다. 잠시 후 다시 확인해 주세요.',
|
||||
);
|
||||
return;
|
||||
case 'done':
|
||||
if (task === 'photos') {
|
||||
// 사진은 media 가 진실이다 — 라벨·alt 가 바뀌었으니 다시 읽게 한다.
|
||||
await invalidate(getListMediaQueryKey(placeId));
|
||||
notifyVision(outcome.job);
|
||||
} else {
|
||||
// 소개문은 fact(intro·meta_description)로, FAQ 는 faq 로 들어간다 — 둘 다 무효화한다.
|
||||
await invalidate(getListFactsQueryKey(placeId), getListFaqsQueryKey(placeId));
|
||||
notifyCopy(outcome.job);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 수집이 큐에 넣은 사진 분석 잡을 기다린다.
|
||||
*
|
||||
* 잡 id 는 수집 결과(`result.vision_job_id`)에 실려 온다 — 사진이 한 장도 없으면 없다.
|
||||
* 실패·타임아웃은 조용히 넘어간다: 사진이 늦게 붙을 뿐 수집 자체는 성공이고,
|
||||
* 여기서 화면을 막으면 사장님이 다음으로 못 간다.
|
||||
*/
|
||||
export async function waitForVision(placeId: string, job: JobData, signal: AbortSignal) {
|
||||
const visionJobId = (job.result as {vision_job_id?: string} | undefined)?.vision_job_id;
|
||||
if (!visionJobId) return;
|
||||
const outcome = await pollJob(visionJobId, {signal});
|
||||
if (outcome.kind === 'done') await refreshPlaceCaches(placeId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 수집이 끝난 뒤 서버가 진실인 것들 — place(주소·갱신시각) · 링크 · fact · **사진**.
|
||||
*
|
||||
* ★ media 를 빠뜨리면 사진이 서버에 10장 들어와도 화면은 빈 목록을 계속 본다.
|
||||
* 실제로 그랬다 — "이미지 왜 못 가져오냐"의 원인이 수집이 아니라 여기였다.
|
||||
* 목록에 뭘 더할 때는 화면이 그 값을 어디서 읽는지 같이 확인해야 한다.
|
||||
*/
|
||||
export async function refreshPlaceCaches(placeId: string) {
|
||||
await Promise.all([
|
||||
queryClient.invalidateQueries({queryKey: getGetPlaceQueryKey(placeId)}),
|
||||
queryClient.invalidateQueries({queryKey: getListLinksQueryKey(placeId)}),
|
||||
queryClient.invalidateQueries({queryKey: getListFactsQueryKey(placeId)}),
|
||||
queryClient.invalidateQueries({queryKey: getListMediaQueryKey(placeId)}),
|
||||
]).catch(() => undefined);
|
||||
}
|
||||
|
||||
/**
|
||||
* 캐시 무효화 묶음. 실패해도 삼킨다 — 화면이 한 박자 늦게 갱신될 뿐이고, 잡은 이미 끝났다.
|
||||
*
|
||||
* 생성물 쿼리 키는 `as const` 라 안쪽도 readonly 다 — 그 모양 그대로 받는다.
|
||||
*/
|
||||
export async function invalidate(...queryKeys: readonly (readonly unknown[])[]) {
|
||||
await Promise.all(
|
||||
queryKeys.map((queryKey) => queryClient.invalidateQueries({queryKey})),
|
||||
).catch(() => undefined);
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
/**
|
||||
* 수집·분석·소개문 잡이 끝났을 때의 알림 문구.
|
||||
*
|
||||
* ★ "몇 건이 새로 들어왔는가"를 말해 주지 않으면 사장님은 버튼을 눌렀는데 아무 일도
|
||||
* 일어나지 않은 것으로 읽는다. 숫자는 job.result 에만 있으므로 판독은 collectJobResult 가
|
||||
* 맡고, 여기서는 문구만 만든다.
|
||||
*/
|
||||
import type {JobData} from '@/api';
|
||||
import {notify} from '@/lib/notify';
|
||||
import {readGroup, readNote, readNumber} from './collectJobResult';
|
||||
|
||||
/**
|
||||
* 재수집(정보) 결과 알림.
|
||||
*
|
||||
* ★ `facts.stored` 하나만 보여주면 "N건이 반영됐다"로 읽힌다 — 사실이 아니다.
|
||||
* stored 는 **후보로 새로 쌓인 것(candidate)** 과 **값이 같아 다시 확인만 된 것(refreshed)** 의
|
||||
* 합이고, 노출 중인 값은 어느 쪽이든 그대로다(fact_service 의 업데이트 프로세스).
|
||||
* 그래서 둘을 갈라 보여주고, 승인이 남았다는 사실을 같이 적는다.
|
||||
*/
|
||||
export function notifyCollected(job: JobData) {
|
||||
const facts = readGroup(job, 'facts');
|
||||
const media = readGroup(job, 'media');
|
||||
const stored = readNumber(facts, 'stored');
|
||||
const candidate = readNumber(facts, 'candidate');
|
||||
const refreshed = readNumber(facts, 'refreshed');
|
||||
const photos = readNumber(media, 'stored');
|
||||
|
||||
if (stored === 0 && photos === 0) {
|
||||
notify.warn(
|
||||
'새로 들어온 정보가 없습니다.',
|
||||
readNote(job) ?? '확정된 채널에서 달라진 값을 찾지 못했습니다.',
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const parts = [`확인할 새 값 ${candidate}건`, `그대로인 값 ${refreshed}건`];
|
||||
if (photos > 0) parts.push(`새 사진 ${photos}장`);
|
||||
notify.success(
|
||||
'다시 수집했습니다',
|
||||
`${parts.join(' · ')} — 새 값은 [맞아요]를 눌러야 사이트에 나갑니다.`,
|
||||
);
|
||||
}
|
||||
|
||||
/** 재분석(사진) 결과 알림. 신뢰도가 낮은 건은 자동 반영되지 않고 확인 큐에 남는다. */
|
||||
export function notifyVision(job: JobData) {
|
||||
const analyzed = readNumber(job.result, 'analyzed');
|
||||
if (analyzed === 0) {
|
||||
notify.warn('분석한 사진이 없습니다.', readNote(job) ?? '수집된 사진이 없습니다.');
|
||||
return;
|
||||
}
|
||||
notify.success(
|
||||
'사진을 다시 분석했습니다',
|
||||
`${analyzed}장 · 자동 반영 ${readNumber(job.result, 'approved')}장 · ` +
|
||||
`확인 대기 ${readNumber(job.result, 'needs_review')}장`,
|
||||
);
|
||||
}
|
||||
|
||||
/** 재생성(소개문·FAQ) 결과 알림. 생성물도 미검증으로 들어가 사람이 승인해야 나간다. */
|
||||
export function notifyCopy(job: JobData) {
|
||||
const faqCount = readNumber(job.result, 'faqs');
|
||||
const hasIntro = (job.result as {intro?: unknown} | undefined)?.intro === true;
|
||||
if (!hasIntro && faqCount === 0) {
|
||||
notify.warn(
|
||||
'새로 만든 문장이 없습니다.',
|
||||
readNote(job) ?? '근거로 쓸 확인된 정보가 부족합니다. 정보를 먼저 확인해 주세요.',
|
||||
);
|
||||
return;
|
||||
}
|
||||
notify.success(
|
||||
'소개문을 다시 만들었습니다',
|
||||
`소개문 ${hasIntro ? '1건' : '없음'} · FAQ ${faqCount}건 — 확인하신 뒤 사이트에 나갑니다.`,
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
export {Step1Industry} from './Step1Industry';
|
||||
export {Step2PlaceSearch} from './Step2PlaceSearch';
|
||||
export {Step3DataReview} from './Step3DataReview';
|
||||
export {Step4Template} from './Step4Template';
|
||||
export {Step5Generating} from './Step5Generating';
|
||||
// 재수집 패널은 위저드 밖(사업장 상세 · 빌더 에디터)에서 쓰지만 배선(useCollectFlow)이
|
||||
// 여기 있어서 같이 둔다 — 수집 경로를 두 곳으로 쪼개지 않는다.
|
||||
export {RecollectPanel} from './RecollectPanel';
|
||||
// 붙여넣기 패널도 위저드 밖에서 쓴다 — 자동 수집이 못 채운 업소의 폴백 입구다.
|
||||
export {PasteFactsPanel} from './PasteFactsPanel';
|
||||
@@ -0,0 +1,10 @@
|
||||
import {Building2, Coffee, Compass, UtensilsCrossed} from 'lucide-react';
|
||||
import type {IndustryType} from '@o2o/shared';
|
||||
|
||||
/** 업종 아이콘. lucide 하나로 통일한다 — 손으로 그린 SVG 세트를 따로 두지 않는다. */
|
||||
export const INDUSTRY_ICONS: Record<IndustryType, typeof Building2> = {
|
||||
stay: Building2,
|
||||
cafe: Coffee,
|
||||
restaurant: UtensilsCrossed,
|
||||
tour: Compass,
|
||||
};
|
||||
@@ -0,0 +1,90 @@
|
||||
/**
|
||||
* 채널 링크 — 목록 · 직접 등록 · 확정.
|
||||
*
|
||||
* ★ 수집 흐름(useCollectFlow)에서 떼어낸 이유: 이건 **단계 전이가 없는** 일이다.
|
||||
* 등록하고 확정하는 것뿐이고, 수집이 돌고 있든 아니든 똑같이 동작한다.
|
||||
* 한 훅에 섞여 있으면 "지금 어느 단계라 이 버튼이 되는가"를 매번 따져야 한다.
|
||||
*
|
||||
* ★ 확정된 링크만 크롤링 대상이 된다 — 이 훅이 수집 게이트의 앞단이다.
|
||||
*/
|
||||
import {useCallback, useState} from 'react';
|
||||
import {LinkChannel, SourceType} from '@o2o/shared';
|
||||
import type {LinkChannel as LinkChannelCode, LinkData} from '@/api';
|
||||
import {confirmLink, createLink, getListLinksQueryKey, useListLinks} from '@/api';
|
||||
import {notify, notifyApiError} from '@/lib/notify';
|
||||
import {queryClient} from '@/lib/query-client';
|
||||
|
||||
export function useChannelLinks(placeId: string | null) {
|
||||
const [confirmingId, setConfirmingId] = useState<string | null>(null);
|
||||
const [isAdding, setIsAdding] = useState(false);
|
||||
/** 서버가 네이버 플레이스를 찾지 못했는지 여부. 수집 결과가 알려주고, 직접 등록하면 내린다. */
|
||||
const [naverPlaceMissing, setNaverPlaceMissing] = useState(false);
|
||||
|
||||
const enabled = Boolean(placeId);
|
||||
const linksQuery = useListLinks(placeId ?? '', undefined, {query: {enabled}});
|
||||
const links: LinkData[] = linksQuery.data?.links ?? [];
|
||||
const confirmedCount = linksQuery.data?.confirmed ?? 0;
|
||||
|
||||
/**
|
||||
* 사장님이 직접 붙여넣은 채널 URL 을 등록하고 **동시에 확정**한다.
|
||||
*
|
||||
* ★ 발견된 URL 과 달리 확인 절차를 한 번 더 두지 않는다. 사장님이 자기 가게 주소를
|
||||
* 직접 가져온 것이므로, 그 붙여넣기 자체가 확인이다. 여기서 또 [내 채널 맞아요]를
|
||||
* 요구하면 같은 판단을 두 번 시키는 셈이다.
|
||||
*/
|
||||
const addLink = useCallback(
|
||||
async (url: string, channel: LinkChannelCode, title: string) => {
|
||||
if (!placeId) return;
|
||||
setIsAdding(true);
|
||||
try {
|
||||
const created = await createLink(placeId, {
|
||||
channel, url, title, discovered_by: SourceType.OWNER,
|
||||
});
|
||||
const linkId = created.link?.link_id;
|
||||
if (linkId) await confirmLink(placeId, linkId);
|
||||
// 사장님이 직접 주소를 넣었으면 "자동으로 못 찾았습니다" 안내는 할 일을 다 했다 — 내린다.
|
||||
if (channel === LinkChannel.NAVER_PLACE) setNaverPlaceMissing(false);
|
||||
await queryClient
|
||||
.invalidateQueries({queryKey: getListLinksQueryKey(placeId)})
|
||||
.catch(() => undefined);
|
||||
notify.success('채널을 등록했습니다', `${title} · 바로 수집 대상이 됩니다.`);
|
||||
} catch (error) {
|
||||
notifyApiError(error, '채널을 등록하지 못했습니다.');
|
||||
} finally {
|
||||
setIsAdding(false);
|
||||
}
|
||||
},
|
||||
[placeId],
|
||||
);
|
||||
|
||||
/** 사람이 "내 채널 맞다"고 고른 URL 을 확정한다. ★ 확정된 것만 크롤링 대상이 된다. */
|
||||
const confirm = useCallback(
|
||||
async (linkId: string) => {
|
||||
if (!placeId) return;
|
||||
setConfirmingId(linkId);
|
||||
try {
|
||||
await confirmLink(placeId, linkId);
|
||||
await queryClient
|
||||
.invalidateQueries({queryKey: getListLinksQueryKey(placeId)})
|
||||
.catch(() => undefined);
|
||||
} catch (error) {
|
||||
notifyApiError(error, '채널을 확정하지 못했습니다.');
|
||||
} finally {
|
||||
setConfirmingId(null);
|
||||
}
|
||||
},
|
||||
[placeId],
|
||||
);
|
||||
|
||||
return {
|
||||
links,
|
||||
confirmedCount,
|
||||
confirmingId,
|
||||
isAdding,
|
||||
naverPlaceMissing,
|
||||
setNaverPlaceMissing,
|
||||
isLinksLoading: enabled && linksQuery.isPending,
|
||||
addLink,
|
||||
confirm,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,291 @@
|
||||
import {useCallback, useEffect, useRef, useState} from 'react';
|
||||
import {JobStatus, LinkChannel, SourceType} from '@o2o/shared';
|
||||
import type {
|
||||
JobData,
|
||||
LinkChannel as LinkChannelCode,
|
||||
LinkData,
|
||||
ReqStartCollect,
|
||||
} from '@/api';
|
||||
import {
|
||||
getListLinksQueryKey,
|
||||
listLinks,
|
||||
pollJob,
|
||||
startCollect,
|
||||
useGetActiveCollect,
|
||||
} from '@/api';
|
||||
import {notify, notifyApiError} from '@/lib/notify';
|
||||
import {queryClient} from '@/lib/query-client';
|
||||
import {useBuilderStore} from '@/stores/builder';
|
||||
import {readNaverPlaceMissing} from './collectJobResult';
|
||||
import {refreshPlaceCaches, runSideJob, waitForVision} from './collectJobs';
|
||||
import {notifyCollected} from './collectNotify';
|
||||
import {useChannelLinks} from './useChannelLinks';
|
||||
|
||||
/** 채널 코드의 화면 표시명. */
|
||||
export const CHANNEL_LABEL: Record<number, string> = {
|
||||
[LinkChannel.YANOLJA]: '야놀자',
|
||||
[LinkChannel.GOODCHOICE]: '여기어때',
|
||||
[LinkChannel.NAVER_PLACE]: '네이버 플레이스',
|
||||
[LinkChannel.INSTAGRAM]: '인스타그램',
|
||||
[LinkChannel.OFFICIAL_SITE]: '공식 홈페이지',
|
||||
[LinkChannel.BLOG]: '블로그',
|
||||
[LinkChannel.ETC]: '기타',
|
||||
};
|
||||
|
||||
export type CollectPhase =
|
||||
| 'idle'
|
||||
| 'discovering'
|
||||
| 'awaiting-confirm'
|
||||
| 'crawling'
|
||||
| 'done';
|
||||
|
||||
/** 에디터에서 다시 실행할 수집 작업. */
|
||||
export type RecollectTask = 'facts' | 'photos' | 'copy';
|
||||
|
||||
/** 실패 문구에 쓰는 이름. 잡 종류를 코드값으로 말하지 않는다. */
|
||||
const RECOLLECT_LABEL: Record<RecollectTask, string> = {
|
||||
facts: '정보 수집',
|
||||
photos: '사진 분석',
|
||||
copy: '소개문 생성',
|
||||
};
|
||||
|
||||
/** 채널 발견 → 사용자 확인 → 확정 URL 수집 흐름을 관리한다. */
|
||||
export function useCollectFlow(placeId: string | null) {
|
||||
const [phase, setPhase] = useState<CollectPhase>('idle');
|
||||
/** Perplexity는 명시적으로 선택한 발견 요청에만 사용한다. */
|
||||
const [discoverChannels, setDiscoverChannels] = useState(false);
|
||||
/** 실행 중인 재수집 작업. */
|
||||
const [recollectingTask, setRecollectingTask] = useState<RecollectTask | null>(null);
|
||||
/** 렌더 전에 발생하는 연속 클릭도 차단한다. */
|
||||
const recollecting = useRef<RecollectTask | null>(null);
|
||||
const startGather = useBuilderStore((s) => s.startGather);
|
||||
const setGatherStage = useBuilderStore((s) => s.setGatherStage);
|
||||
const finishGather = useBuilderStore((s) => s.finishGather);
|
||||
const running = useRef<AbortController | null>(null);
|
||||
const recoveryHandled = useRef(false);
|
||||
|
||||
const enabled = Boolean(placeId);
|
||||
const activeCollectQuery = useGetActiveCollect(placeId ?? '', {query: {enabled, retry: false}});
|
||||
// 채널 링크(목록·등록·확정)는 단계 전이가 없는 일이라 별도 훅이 맡는다.
|
||||
const channels = useChannelLinks(placeId);
|
||||
const {setNaverPlaceMissing} = channels;
|
||||
|
||||
useEffect(() => () => running.current?.abort(), []);
|
||||
|
||||
// URL 재접속/새로고침 시 서버에 남아 있는 수집 잡을 찾아 같은 폴링에 다시 붙는다.
|
||||
useEffect(() => {
|
||||
if (!placeId || !activeCollectQuery.isSuccess || recoveryHandled.current) return;
|
||||
recoveryHandled.current = true;
|
||||
const active = activeCollectQuery.data?.job;
|
||||
if (!active) return;
|
||||
|
||||
const controller = new AbortController();
|
||||
running.current?.abort();
|
||||
running.current = controller;
|
||||
startGather();
|
||||
setPhase('crawling');
|
||||
|
||||
void (async () => {
|
||||
const outcome = await pollJob(active.job_id, {
|
||||
signal: controller.signal,
|
||||
onTick: (job) => setGatherStage(job.status === JobStatus.RUNNING ? 2 : 1),
|
||||
});
|
||||
if (controller.signal.aborted) return;
|
||||
if (outcome.kind === 'done') {
|
||||
await refreshPlaceCaches(placeId);
|
||||
setNaverPlaceMissing(readNaverPlaceMissing(outcome.job));
|
||||
await waitForVision(placeId, outcome.job, controller.signal);
|
||||
finishGather();
|
||||
setPhase('done');
|
||||
} else if (outcome.kind === 'dead') {
|
||||
finishGather();
|
||||
setPhase('idle');
|
||||
notify.error('수집을 끝내지 못했습니다.', outcome.job.last_error ?? undefined);
|
||||
} else if (outcome.kind !== 'aborted') {
|
||||
finishGather();
|
||||
setPhase('idle');
|
||||
}
|
||||
})();
|
||||
}, [
|
||||
placeId,
|
||||
activeCollectQuery.isSuccess,
|
||||
activeCollectQuery.data?.job,
|
||||
startGather,
|
||||
setGatherStage,
|
||||
finishGather,
|
||||
setNaverPlaceMissing,
|
||||
]);
|
||||
|
||||
/**
|
||||
* 수집 잡 1회분. 끝나면 링크·fact·사진 캐시를 무효화해 화면이 서버 상태를 다시 읽게 한다.
|
||||
*
|
||||
* ★ 끝난 잡을 그대로 돌려준다(boolean 아님). 재수집 화면은 "몇 건이 새로 들어왔는지"를
|
||||
* 알려야 하는데 그 숫자는 `job.result` 에만 있다 — 성패만 받으면 다시 물어볼 길이 없다.
|
||||
*/
|
||||
const runCollect = useCallback(
|
||||
async (id: string, signal: AbortSignal, body: ReqStartCollect = {}): Promise<JobData | null> => {
|
||||
let jobId: string;
|
||||
try {
|
||||
const started = await startCollect(id, body, undefined, signal);
|
||||
// ★ 거절도 HTTP 200 이다 — 검증 전(PLACE_NOT_VERIFIED)·이미 도는 잡
|
||||
// (COLLECT_ALREADY_RUNNING)이 여기로 온다. result 를 안 보면 전부
|
||||
// '잡이 만들어지지 않았습니다'로 뭉개져 사장님이 할 일을 못 찾는다.
|
||||
if (started.result?.success === false || !started.job_id) {
|
||||
notifyApiError({data: started}, '수집을 시작하지 못했습니다.');
|
||||
return null;
|
||||
}
|
||||
jobId = started.job_id;
|
||||
} catch (error) {
|
||||
if (signal.aborted) return null;
|
||||
notifyApiError(error, '수집을 시작하지 못했습니다.');
|
||||
return null;
|
||||
}
|
||||
|
||||
const outcome = await pollJob(jobId, {
|
||||
signal,
|
||||
onTick: (job) => setGatherStage(job.status === JobStatus.RUNNING ? 2 : 1),
|
||||
});
|
||||
|
||||
switch (outcome.kind) {
|
||||
case 'aborted':
|
||||
return null;
|
||||
case 'dead':
|
||||
notify.error('수집을 끝내지 못했습니다.', outcome.job.last_error ?? undefined);
|
||||
return null;
|
||||
case 'unreachable':
|
||||
notifyApiError(outcome.error, '수집 상태를 확인하지 못했습니다.');
|
||||
return null;
|
||||
case 'timeout':
|
||||
notify.warn(
|
||||
'수집이 예상보다 오래 걸립니다.',
|
||||
'수집은 서버에서 계속 진행됩니다. 잠시 후 다시 확인해 주세요.',
|
||||
);
|
||||
return null;
|
||||
case 'done':
|
||||
await refreshPlaceCaches(id);
|
||||
setNaverPlaceMissing(readNaverPlaceMissing(outcome.job));
|
||||
// ★ 수집이 끝나도 사진은 아직 못 쓴다. 사진은 Vision 이 alt 를 붙여야 발행 대상이
|
||||
// 되고(snapshot 이 alt 없는 사진을 거른다), Vision 은 수집이 큐에 넣는 **별개 잡**이다.
|
||||
// 여기서 안 기다리면 서버에 10장이 들어와 있어도 화면은 "사진 0" 으로 보인다.
|
||||
await waitForVision(id, outcome.job, signal);
|
||||
return outcome.job;
|
||||
}
|
||||
},
|
||||
[setGatherStage, setNaverPlaceMissing],
|
||||
);
|
||||
|
||||
/** 1회차 — 채널 URL 찾기. 확정할 URL 이 이미 있으면 곧장 크롤링으로 간다. */
|
||||
const discover = useCallback(async () => {
|
||||
if (!placeId) return;
|
||||
running.current?.abort();
|
||||
const controller = new AbortController();
|
||||
running.current = controller;
|
||||
|
||||
startGather();
|
||||
setPhase('discovering');
|
||||
|
||||
const job = await runCollect(placeId, controller.signal, {
|
||||
discover_channels: discoverChannels,
|
||||
});
|
||||
if (controller.signal.aborted) return;
|
||||
|
||||
finishGather();
|
||||
if (!job) {
|
||||
setPhase('idle');
|
||||
return;
|
||||
}
|
||||
|
||||
// 잡이 끝난 뒤의 링크 상태를 직접 읽는다(캐시 무효화만으로는 이 자리에서 값을 못 본다).
|
||||
const fresh = await queryClient
|
||||
.fetchQuery({
|
||||
queryKey: getListLinksQueryKey(placeId),
|
||||
queryFn: () => listLinks(placeId),
|
||||
})
|
||||
.catch(() => null);
|
||||
|
||||
const found = fresh?.links ?? [];
|
||||
if ((fresh?.confirmed ?? 0) > 0) {
|
||||
// 이미 확정된 채널이 있다 = 크롤링까지 끝난 회차였다.
|
||||
setPhase('done');
|
||||
return;
|
||||
}
|
||||
if (found.length === 0) {
|
||||
notify.warn(
|
||||
'자동으로는 찾지 못했습니다.',
|
||||
'네이버 지도에서 내 가게 주소를 복사해 붙여넣어 주세요 — 그러면 확실하게 가져옵니다.',
|
||||
);
|
||||
setPhase('idle');
|
||||
return;
|
||||
}
|
||||
setPhase('awaiting-confirm');
|
||||
}, [placeId, runCollect, startGather, finishGather, discoverChannels]);
|
||||
|
||||
/** 2회차 — 확정된 URL 만 긁는다. 여기서 나온 값이 [수집된 데이터]에 들어간다. */
|
||||
const crawl = useCallback(async () => {
|
||||
if (!placeId) return;
|
||||
running.current?.abort();
|
||||
const controller = new AbortController();
|
||||
running.current = controller;
|
||||
|
||||
startGather();
|
||||
setPhase('crawling');
|
||||
|
||||
const job = await runCollect(placeId, controller.signal);
|
||||
if (controller.signal.aborted) return;
|
||||
|
||||
finishGather();
|
||||
setPhase(job ? 'done' : 'awaiting-confirm');
|
||||
}, [placeId, runCollect, startGather, finishGather]);
|
||||
|
||||
/**
|
||||
* 재수집 — 이미 만든 사업장을 다시 긁는다.
|
||||
*
|
||||
* ★ 크롤링은 `crawl` 과 같은 배선(runCollect)을 그대로 쓴다. 다른 건 `force:true` 뿐이다:
|
||||
* force 없이는 "이미 필수 항목이 다 차 있다"며 크롤링을 건너뛰어(collect_service.run_collect)
|
||||
* 사장님 눈에는 버튼을 눌러도 아무 일이 안 일어난 것처럼 보인다.
|
||||
*
|
||||
* ★ 그래도 **노출 중인 값은 밀려나지 않는다**. 자동 출처(CRAWL)는 노출값을 직접 못 바꾸고
|
||||
* 후보로만 쌓이며(fact_service._write_candidate), 사장님이 고친 값(CORRECTED)은 잠겨 있다.
|
||||
* 그래서 화면 문구도 "다 새로 가져옵니다"가 아니라 "확인할 후보로 쌓입니다"여야 한다.
|
||||
*/
|
||||
const recollect = useCallback(
|
||||
async (task: RecollectTask) => {
|
||||
if (!placeId || recollecting.current) return;
|
||||
recollecting.current = task;
|
||||
setRecollectingTask(task);
|
||||
|
||||
running.current?.abort();
|
||||
const controller = new AbortController();
|
||||
running.current = controller;
|
||||
|
||||
try {
|
||||
if (task === 'facts') {
|
||||
const job = await runCollect(placeId, controller.signal, {force: true});
|
||||
if (job && !controller.signal.aborted) notifyCollected(job);
|
||||
return;
|
||||
}
|
||||
await runSideJob(task, placeId, controller.signal);
|
||||
} finally {
|
||||
// 언마운트로 끊겼어도 ref 는 반드시 푼다 — 안 그러면 다음 마운트가 아니라
|
||||
// 이 훅 인스턴스가 영영 잠긴다(같은 화면에서 다시 못 누른다).
|
||||
recollecting.current = null;
|
||||
setRecollectingTask(null);
|
||||
}
|
||||
},
|
||||
[placeId, runCollect],
|
||||
);
|
||||
|
||||
// ★ 반환 모양은 그대로 둔다. 훅을 쪼갠 건 내부 사정이고, 화면이 보는 계약이 아니다 —
|
||||
// 여기서 모양이 바뀌면 위저드와 재수집 패널을 같이 고쳐야 한다.
|
||||
return {
|
||||
phase,
|
||||
...channels,
|
||||
discoverChannels,
|
||||
setDiscoverChannels,
|
||||
discover,
|
||||
crawl,
|
||||
recollect,
|
||||
recollectingTask,
|
||||
isCheckingActive: enabled && activeCollectQuery.isPending,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,282 @@
|
||||
import {useCallback, useRef, useState} from 'react';
|
||||
import type {IndustryType} from '@o2o/shared';
|
||||
import type {ExternalPlaceSource as ExternalPlaceSourceType, PlaceCandidate, PlaceCategory} from '@/api';
|
||||
import {
|
||||
createPlace,
|
||||
ExternalPlaceSource,
|
||||
getAccessToken,
|
||||
PlaceCategory as PlaceCategoryEnum,
|
||||
updatePlace,
|
||||
verifyCandidates,
|
||||
verifyPlace,
|
||||
verifyPlaceByUrl,
|
||||
} from '@/api';
|
||||
import type {ConfirmedIdentity} from '@/stores/builder';
|
||||
import {ensureDevSession} from '@/lib/devSession';
|
||||
import {notify, notifyApiError} from '@/lib/notify';
|
||||
|
||||
/** 빌더 업종 → places.category. 반대 방향은 stores/builder 의 CATEGORY_TO_INDUSTRY 다. */
|
||||
const INDUSTRY_TO_CATEGORY: Record<IndustryType, PlaceCategory> = {
|
||||
stay: PlaceCategoryEnum.LODGING,
|
||||
cafe: PlaceCategoryEnum.CAFE,
|
||||
restaurant: PlaceCategoryEnum.RESTAURANT,
|
||||
tour: PlaceCategoryEnum.TOUR_ACTIVITY,
|
||||
};
|
||||
|
||||
/** 후보를 어느 장소 DB 에서 찾았는지 — 사장님이 판단할 근거로 카드에 그대로 붙인다. */
|
||||
const SOURCE_LABEL: Record<number, string> = {
|
||||
[ExternalPlaceSource.KAKAO]: '카카오맵',
|
||||
[ExternalPlaceSource.NAVER]: '네이버 지도',
|
||||
};
|
||||
|
||||
export type SearchPhase =
|
||||
/** 아직 검색 전. */
|
||||
| 'idle'
|
||||
/** 사업장 생성 + 후보 조회 중. */
|
||||
| 'searching'
|
||||
/** 후보를 받았다(0건일 수도 있다 — outcome 이 no_candidate). */
|
||||
| 'done'
|
||||
/**
|
||||
* 장소 DB 를 부를 수 없다 — 로그인이 없거나 백엔드가 응답하지 않는다.
|
||||
* ★ 이때 가짜 후보를 지어내지 않는다. 검색 결과인 척하는 예시 카드는
|
||||
* 사장님이 남의 가게를 자기 가게로 확정하게 만드는 가장 빠른 길이다.
|
||||
*/
|
||||
| 'unavailable';
|
||||
|
||||
export interface PlaceSearchState {
|
||||
phase: SearchPhase;
|
||||
/** 외부 장소 DB 후보. 서버가 자동 확정하지 않으므로 항상 사람이 고른다. */
|
||||
candidates: PlaceCandidate[];
|
||||
/** matched | ambiguous | no_candidate — 서버 판정. 문구를 고르는 데만 쓴다. */
|
||||
outcome: string;
|
||||
/** true 면 판정이 명확해 '이거 맞나요?' 한 번만 물어도 된다. */
|
||||
autoSelectable: boolean;
|
||||
/** 후보를 준 장소 DB 이름. 없으면 빈 문자열. */
|
||||
sourceLabel: string;
|
||||
source: ExternalPlaceSourceType | null;
|
||||
/** 검색을 못 한 이유(로그인 필요 등). phase === 'unavailable' 일 때만 채워진다. */
|
||||
unavailableReason: string;
|
||||
}
|
||||
|
||||
const INITIAL: PlaceSearchState = {
|
||||
phase: 'idle',
|
||||
candidates: [],
|
||||
outcome: '',
|
||||
autoSelectable: false,
|
||||
sourceLabel: '',
|
||||
source: null,
|
||||
unavailableReason: '',
|
||||
};
|
||||
|
||||
/**
|
||||
* 상호 검색 → 동일 업소 후보 조회 → 사람이 고른 후보로 확정.
|
||||
*
|
||||
* 백엔드 순서가 그대로 화면 순서다:
|
||||
* 1) POST /v1/place 사업장(껍데기)을 만든다 — 후보 조회가 place_id 를 요구한다
|
||||
* 2) GET /v1/place/{id}/verify/candidates?query= 외부 장소 DB 후보
|
||||
* 3) POST /v1/place/{id}/verify 사람이 고른 후보로 동일 업소 확정
|
||||
*
|
||||
* ★ 3 을 통과해야 수집이 열린다(place.py: "동일 업소 검증과 채널 URL 확정이 끝나야 시작할 수 있다").
|
||||
* 그래서 직접 입력 경로는 수집 없이 사장님 입력만으로 사이트를 만든다 — 검증을 우회하지 않는다.
|
||||
*/
|
||||
export function usePlaceSearch(industry: IndustryType, existingPlaceId: string | null = null) {
|
||||
const [state, setState] = useState<PlaceSearchState>(INITIAL);
|
||||
const [isConfirming, setIsConfirming] = useState(false);
|
||||
/**
|
||||
* 이 위저드가 만든 사업장. 상호를 고쳐 다시 검색해도 사업장을 새로 만들지 않는다.
|
||||
* ★ 새로고침을 넘어온 경우 스토어에 남아 있는 사업장을 그대로 이어받는다 — 안 그러면
|
||||
* 되살아난 화면이 같은 가게를 한 번 더 만든다.
|
||||
*/
|
||||
const placeIdRef = useRef<string | null>(existingPlaceId);
|
||||
const inflight = useRef<AbortController | null>(null);
|
||||
/** 마지막으로 검색한 상호. URL 확정 때 사업장 껍데기 이름으로 쓴다. */
|
||||
const nameRef = useRef<string>('');
|
||||
|
||||
const reset = useCallback(() => {
|
||||
inflight.current?.abort();
|
||||
inflight.current = null;
|
||||
setState(INITIAL);
|
||||
}, []);
|
||||
|
||||
/** 사업장 껍데기 확보. 이미 만들었으면 상호만 맞춰 둔다(같은 위저드에서 두 번 만들지 않는다). */
|
||||
const ensurePlace = useCallback(
|
||||
async (name: string, signal: AbortSignal): Promise<string | null> => {
|
||||
if (placeIdRef.current) {
|
||||
// PATCH 는 취소 신호를 받지 않는다(생성물 시그니처) — 뒤에서 signal 로 결과를 버린다.
|
||||
await updatePlace(placeIdRef.current, {name});
|
||||
if (signal.aborted) return null;
|
||||
return placeIdRef.current;
|
||||
}
|
||||
const created = await createPlace(
|
||||
{name, category: INDUSTRY_TO_CATEGORY[industry]},
|
||||
undefined,
|
||||
signal,
|
||||
);
|
||||
placeIdRef.current = created.place?.place_id ?? null;
|
||||
return placeIdRef.current;
|
||||
},
|
||||
[industry],
|
||||
);
|
||||
|
||||
const search = useCallback(
|
||||
async (name: string, location: string) => {
|
||||
nameRef.current = name.trim();
|
||||
const query = [name.trim(), location.trim()].filter(Boolean).join(' ');
|
||||
if (!name.trim()) return;
|
||||
|
||||
inflight.current?.abort();
|
||||
const controller = new AbortController();
|
||||
inflight.current = controller;
|
||||
|
||||
// ★ 개발 서버라면 자동 로그인이 끝날 때까지 기다린다. 이걸 안 기다리면 페이지를 열자마자
|
||||
// 누른 검색이 토큰 없이 나가 '로그인 만료'로 떨어진다 — 만료가 아니라 경합이다.
|
||||
await ensureDevSession();
|
||||
|
||||
if (!getAccessToken()) {
|
||||
setState({
|
||||
...INITIAL,
|
||||
phase: 'unavailable',
|
||||
unavailableReason: '로그인이 만료되었습니다. 다시 로그인한 뒤 검색해 주세요.',
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
setState({...INITIAL, phase: 'searching'});
|
||||
|
||||
try {
|
||||
const placeId = await ensurePlace(name.trim(), controller.signal);
|
||||
if (!placeId) throw new Error('사업장을 만들지 못했습니다.');
|
||||
|
||||
const res = await verifyCandidates(placeId, {query}, undefined, controller.signal);
|
||||
if (controller.signal.aborted) return;
|
||||
|
||||
const source = res.source ?? null;
|
||||
setState({
|
||||
phase: 'done',
|
||||
candidates: res.candidates ?? [],
|
||||
outcome: res.outcome ?? '',
|
||||
autoSelectable: res.auto_selectable ?? false,
|
||||
source,
|
||||
sourceLabel: source ? (SOURCE_LABEL[source] ?? '외부 장소 DB') : '외부 장소 DB',
|
||||
unavailableReason: '',
|
||||
});
|
||||
} catch (error) {
|
||||
if (controller.signal.aborted) return;
|
||||
notifyApiError(error, '상호를 검색하지 못했습니다.');
|
||||
setState({
|
||||
...INITIAL,
|
||||
phase: 'unavailable',
|
||||
unavailableReason:
|
||||
'장소 DB 를 부르지 못했습니다. 백엔드가 떠 있는지 확인하시거나, 직접 입력으로 진행해 주세요.',
|
||||
});
|
||||
}
|
||||
},
|
||||
[ensurePlace],
|
||||
);
|
||||
|
||||
/**
|
||||
* 사람이 고른 후보를 이 사업장의 신원으로 확정한다(POST /verify).
|
||||
* 성공하면 화면에 얹을 신원을 돌려준다 — 실패하면 null.
|
||||
*/
|
||||
const confirm = useCallback(
|
||||
async (candidate: PlaceCandidate): Promise<ConfirmedIdentity | null> => {
|
||||
const placeId = placeIdRef.current;
|
||||
const address = candidate.road_address ?? candidate.address ?? '';
|
||||
if (!placeId) return null;
|
||||
|
||||
setIsConfirming(true);
|
||||
try {
|
||||
await verifyPlace(placeId, {
|
||||
source: state.source ?? ExternalPlaceSource.KAKAO,
|
||||
// 네이버는 고유 id 를 주지 않는다 — 그 경우 상호명 + 도로명주소가 중복 판정 키다.
|
||||
external_place_id: candidate.external_place_id ?? '',
|
||||
road_address: candidate.road_address ?? null,
|
||||
address: candidate.address ?? null,
|
||||
phone: candidate.phone ?? null,
|
||||
latitude: candidate.latitude ?? null,
|
||||
longitude: candidate.longitude ?? null,
|
||||
place_url: candidate.place_url ?? null,
|
||||
});
|
||||
|
||||
// ★ 상호도 후보 쪽으로 맞춘다. 사장님이 그 이름이 적힌 카드를 보고 "이 가게예요"를
|
||||
// 눌렀는데 DB 에는 검색어로 친 이름이 남으면, 화면과 서버가 다른 상호를 들고 있게 된다.
|
||||
const officialName = candidate.name?.trim();
|
||||
if (officialName) await updatePlace(placeId, {name: officialName});
|
||||
|
||||
return {
|
||||
placeId,
|
||||
name: candidate.name ?? '',
|
||||
address,
|
||||
phone: candidate.phone ?? undefined,
|
||||
origin: 'external',
|
||||
sourceLabel: state.sourceLabel || '외부 장소 DB',
|
||||
externalPlaceId: candidate.external_place_id ?? undefined,
|
||||
placeUrl: candidate.place_url ?? undefined,
|
||||
};
|
||||
} catch (error) {
|
||||
notifyApiError(error, '이 가게로 확정하지 못했습니다.');
|
||||
return null;
|
||||
} finally {
|
||||
setIsConfirming(false);
|
||||
}
|
||||
},
|
||||
[state.source, state.sourceLabel],
|
||||
);
|
||||
|
||||
/**
|
||||
* 네이버 플레이스 URL 로 확정한다.
|
||||
*
|
||||
* ★ 이 경로가 가장 확실하다. 상호 검색은 동명 업소·지점명 표기 차이에서 실패하고
|
||||
* (실측: '롯데호텔 서울'), 검색모델은 네이버 플레이스를 아예 못 찾는다.
|
||||
* 반면 사장님은 자기 가게 주소를 이미 안다 — 붙여넣는 순간 신원·채널이 동시에 확정된다.
|
||||
* 상호·주소는 서버가 그 URL 에서 읽어 온다(손으로 옮겨 적게 하면 오타가 남의 가게가 된다).
|
||||
*/
|
||||
const confirmByUrl = useCallback(
|
||||
async (url: string): Promise<ConfirmedIdentity | null> => {
|
||||
setIsConfirming(true);
|
||||
try {
|
||||
const placeId = await ensurePlace(nameRef.current || '내 가게', new AbortController().signal);
|
||||
if (!placeId) return null;
|
||||
const res = await verifyPlaceByUrl(placeId, {url});
|
||||
const place = res.place;
|
||||
if (!place) {
|
||||
notify.error('가게 정보를 읽지 못했습니다.', res.msg ?? '주소를 다시 확인해 주세요.');
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
placeId,
|
||||
name: place.name ?? '',
|
||||
address: place.road_address ?? place.address ?? '',
|
||||
phone: place.phone ?? undefined,
|
||||
origin: 'external',
|
||||
sourceLabel: '네이버 플레이스',
|
||||
externalPlaceId: place.external_place_id ?? undefined,
|
||||
};
|
||||
} catch (error) {
|
||||
notifyApiError(error, '이 주소로 확정하지 못했습니다.');
|
||||
return null;
|
||||
} finally {
|
||||
setIsConfirming(false);
|
||||
}
|
||||
},
|
||||
[ensurePlace],
|
||||
);
|
||||
|
||||
/**
|
||||
* 목록에 없거나 장소 DB 를 못 부를 때 — 사장님이 직접 댄 값으로 신원을 세운다.
|
||||
*
|
||||
* ★ 동일 업소 검증(POST /verify)을 하지 않는다. 검증 없이 수집을 열면 남의 가게 URL 을
|
||||
* 긁을 수 있다. 그래서 이 경로는 수집 없이 직접 입력한 정보로만 사이트를 만든다.
|
||||
*/
|
||||
const confirmManual = useCallback((name: string, address: string): ConfirmedIdentity => {
|
||||
return {
|
||||
placeId: placeIdRef.current,
|
||||
name: name.trim(),
|
||||
address: address.trim(),
|
||||
origin: 'owner',
|
||||
sourceLabel: '직접 입력',
|
||||
};
|
||||
}, []);
|
||||
|
||||
return {...state, isConfirming, search, confirm, confirmByUrl, confirmManual, reset};
|
||||
}
|
||||
Reference in new issue
Block a user