이름: 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,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,
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user