Files
o2o-castad-frontend/src/pages/P2v/PlayreelGateContent.tsx
T

468 lines
17 KiB
TypeScript

import React, { useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import {
AnalysisReview, ClipReview, FetchReview, FinalReview, GATE_CAN_BACK, GATE_ORDER,
GateEdits, GateKey, NarrationReview, PlayreelJob,
approvePlayreelGate, backPlayreelGate, retryPlayreelClip,
} from '../../utils/playreelApi';
import { isAutoApprovable, useAutoApprove } from '../../utils/playreelPrefs';
interface PlayreelGateContentProps {
/** `gate` 와 `review` 가 채워진 검수 대기 잡 */
job: PlayreelJob;
/** 승인·되돌리기·재생성 요청이 끝나면 호출 — GenerationFlow 가 폴링을 다시 켠다 */
onChanged: () => void;
/** 자동 승인이 성공했을 때 호출 — 진행 화면이 "자동 승인했습니다" 안내를 이어서 보여준다 */
onAutoApproved: (gate: GateKey) => void;
}
const Icon: React.FC<{ d: string; size?: number }> = ({ d, size = 12 }) => (
<svg
width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor"
strokeWidth="3" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"
>
<path d={d} />
</svg>
);
const CHECK = 'M20 6 9 17l-5-5';
const CROSS = 'M18 6 6 18M6 6l12 12';
const PLUS = 'M12 5v14M5 12h14';
const Lock: React.FC<{ size?: number }> = ({ size = 12 }) => (
<svg
width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor"
strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"
>
<rect x="4" y="11" width="16" height="10" rx="2" /><path d="M8 11V7a4 4 0 0 1 8 0v4" />
</svg>
);
/** 켜고 끄는 칩. `locked` 는 항상 켜져 있어 누를 수 없다 */
const Chip: React.FC<{
on: boolean; locked?: boolean; onClick?: () => void; children: React.ReactNode;
}> = ({ on, locked, onClick, children }) => (
<button
type="button"
className={`p2v-chip pr-chip${on ? ' active' : ''}${locked ? ' locked' : ''}`}
onClick={locked ? undefined : onClick}
>
{locked ? <Lock /> : <Icon d={on ? CHECK : PLUS} />}
{children}
</button>
);
// ── ① 수집 확인 ─────────────────────────────────────────────────────────
type FetchEdits = Extract<GateEdits, { sections: string[] }>;
/**
* 상세페이지 조각은 라벨이 겹친다 — "유의사항"만 일곱 개인 페이지가 흔하다.
* 칩으로 그리면 같은 글자가 줄줄이 서서 무엇을 고르는지 알 수 없어 썸네일을 그린다.
*/
const FetchGate: React.FC<{ data: FetchReview; onChange: (edits: FetchEdits) => void }> = ({
data, onChange,
}) => {
const { t } = useTranslation();
const [sections, setSections] = useState(data.sections);
const [meta, setMeta] = useState(data.meta);
const emit = (nextSections = sections, nextMeta = meta) =>
onChange({ sections: nextSections.filter((s) => s.selected).map((s) => s.id), meta: nextMeta });
const chosen = sections.filter((s) => s.selected).length;
return (
<div className="pr-two">
<div>
<p className="p2v-label">{t('playreel.fetch.info')}</p>
{(['title', 'date_text', 'place'] as const).map((key) => (
<div key={key} className="pr-row">
<span className="pr-row__label">{t(`playreel.fetch.field.${key}`)}</span>
<input
className="p2v-input"
value={meta[key]}
onChange={(e) => {
const next = { ...meta, [key]: e.target.value };
setMeta(next);
emit(sections, next);
}}
/>
</div>
))}
<p className="p2v-note">{t('playreel.fetch.cast', { cast: meta.cast.join(', ') })}</p>
<p className="p2v-label pr-gap">{t('playreel.fetch.sections')}</p>
<p className="p2v-help">{t('playreel.fetch.sectionsHelp')}</p>
<div className="pr-sections">
{sections.map((s, i) => (
<button
key={s.id}
type="button"
title={`${s.label} · ${s.height.toLocaleString()}px`}
className={`pr-section${s.selected ? ' selected' : ''}${s.required ? ' locked' : ''}`}
onClick={s.required ? undefined : () => {
const next = sections.map((x) => (x.id === s.id ? { ...x, selected: !x.selected } : x));
setSections(next);
emit(next);
}}
>
<img src={s.thumb_url} alt={s.label} />
<span className="pr-section__no">{i + 1}</span>
<span className="pr-section__cap">
{s.required ? <Lock size={10} /> : <Icon d={s.selected ? CHECK : PLUS} size={10} />}
<span>{s.label}</span>
</span>
</button>
))}
</div>
<p className="p2v-note">
{t('playreel.fetch.sectionsCount', { total: sections.length, chosen })}
</p>
{data.poster_width <= 800 && (
<p className="pr-callout">{t('playreel.fetch.lowRes', { width: data.poster_width })}</p>
)}
</div>
<div>
<p className="p2v-label">{t('playreel.fetch.poster')}</p>
<img className="p2v-review__image pr-image" src={data.poster_url} alt={t('playreel.fetch.poster')} />
</div>
</div>
);
};
// ── ② 연출 확인 ─────────────────────────────────────────────────────────
type AnalysisEdits = Extract<GateEdits, { movable: string[] }>;
const AnalysisGate: React.FC<{ data: AnalysisReview; onChange: (edits: AnalysisEdits) => void }> = ({
data, onChange,
}) => {
const { t } = useTranslation();
const [movable, setMovable] = useState(data.movable);
const [fixed, setFixed] = useState(data.fixed);
const emit = (nextMovable = movable, nextFixed = fixed) =>
onChange({
movable: nextMovable.filter((x) => x.on).map((x) => x.key),
fixed: nextFixed.filter((x) => x.on).map((x) => x.key),
model: data.model,
});
return (
<div className="pr-two">
<div>
<p className="p2v-label">{t('playreel.analysis.movable')}</p>
<p className="p2v-help">{t('playreel.analysis.movableHelp')}</p>
<div className="p2v-chips">
{movable.map((m) => (
<Chip
key={m.key}
on={m.on}
onClick={() => {
const next = movable.map((x) => (x.key === m.key ? { ...x, on: !x.on } : x));
setMovable(next);
emit(next);
}}
>
{m.label}
</Chip>
))}
</div>
<p className="p2v-label pr-gap">{t('playreel.analysis.fixed')}</p>
<p className="p2v-help">{t('playreel.analysis.fixedHelp')}</p>
<div className="p2v-chips">
{fixed.map((f) => (
<Chip
key={f.key}
on={f.on}
locked={f.key === 'title'}
onClick={() => {
const next = fixed.map((x) => (x.key === f.key ? { ...x, on: !x.on } : x));
setFixed(next);
emit(movable, next);
}}
>
{f.label}
</Chip>
))}
</div>
<p className="p2v-label pr-gap">{t('playreel.analysis.model')}</p>
<p className="p2v-help">{t('playreel.analysis.modelValue')}</p>
{data.ip_risk && <p className="pr-callout">{t('playreel.analysis.ipRisk')}</p>}
{!data.has_qr && <p className="p2v-note">{t('playreel.analysis.noQr')}</p>}
</div>
<div>
<p className="p2v-label">{t('playreel.analysis.grid')}</p>
<img className="p2v-review__image pr-image" src={data.grid_url} alt={t('playreel.analysis.grid')} />
</div>
</div>
);
};
// ── ③ 나레이션·보이스 확인 ──────────────────────────────────────────────
type NarrationEdits = Extract<GateEdits, { lines: string[] }>;
const NARRATION_MIN_SECONDS = 28;
const NARRATION_MAX_SECONDS = 31;
const NarrationGate: React.FC<{ data: NarrationReview; onChange: (edits: NarrationEdits) => void }> = ({
data, onChange,
}) => {
const { t } = useTranslation();
const [lines, setLines] = useState(data.lines);
const lengthOk = data.est_seconds >= NARRATION_MIN_SECONDS && data.est_seconds <= NARRATION_MAX_SECONDS;
return (
<div className="pr-two">
<div>
<p className="p2v-label">{t('playreel.narration.lines', { count: lines.length })}</p>
{lines.map((line, i) => (
<div key={i} className="pr-row">
<span className="pr-row__label pr-row__label--slot">{line.slot}</span>
<input
className="p2v-input"
value={line.text}
onChange={(e) => {
const next = lines.map((x, j) => (j === i ? { ...x, text: e.target.value } : x));
setLines(next);
onChange({ lines: next.map((x) => x.text), voice_id: data.voice.id });
}}
/>
</div>
))}
</div>
<div>
<p className="p2v-label">{t('playreel.narration.voice')}</p>
<div className="p2v-panel">
<p className="pr-strong">{data.voice.name}</p>
{data.voice.sample_url ? (
<audio controls src={data.voice.sample_url} className="pr-audio" />
) : (
<p className="p2v-note">{t('playreel.narration.sampleMissing')}</p>
)}
</div>
<p className="p2v-label pr-gap">{t('playreel.narration.estimate')}</p>
<p className={`pr-stat${lengthOk ? '' : ' warn'}`}>
{t('playreel.narration.seconds', { value: data.est_seconds.toFixed(1) })}
</p>
<p className="p2v-note">
{t('playreel.narration.target', { min: NARRATION_MIN_SECONDS, max: NARRATION_MAX_SECONDS })}
{!lengthOk && ` — ${t('playreel.narration.adjust')}`}
</p>
</div>
</div>
);
};
// ── ④ 클립 검수 ─────────────────────────────────────────────────────────
const ClipGate: React.FC<{ data: ClipReview }> = ({ data }) => {
const { t } = useTranslation();
return (
<div className="pr-two">
<div className="p2v-panel pr-player">
{data.clip_url ? (
<video src={data.clip_url} controls playsInline />
) : (
<p className="p2v-note">{t('playreel.clip.missing')}</p>
)}
</div>
<div>
<p className="p2v-label">{t('playreel.clip.titleCheck')}</p>
<div className={`p2v-panel pr-verdict${data.gate_passed ? ' ok' : ' fail'}`}>
<p className="pr-strong">
{t(data.gate_passed ? 'playreel.clip.passed' : 'playreel.clip.failed', {
mae: data.title_mae.toFixed(2),
})}
</p>
<p className="p2v-note">{t('playreel.clip.criteria')}</p>
{data.gate_reason && <p className="p2v-note warn">{data.gate_reason}</p>}
</div>
<p className="p2v-label pr-gap">{t('playreel.clip.frames')}</p>
<img className="p2v-review__image pr-image" src={data.frames_url} alt={t('playreel.clip.frames')} />
<p className="pr-callout">{t('playreel.clip.redoNote')}</p>
</div>
</div>
);
};
// ── ⑤ 최종 검수 ─────────────────────────────────────────────────────────
const FinalGate: React.FC<{ data: FinalReview }> = ({ data }) => {
const { t } = useTranslation();
return (
<div className="pr-two">
<div className="p2v-panel pr-player">
{data.video_url ? (
<video src={data.video_url} controls playsInline />
) : (
<p className="p2v-note">{t('playreel.final.missing', { seconds: data.duration.toFixed(1) })}</p>
)}
</div>
<div>
<p className="p2v-label">{t('playreel.final.checks')}</p>
{data.checks.map((c) => (
<p key={c.key} className={`pr-check${c.ok ? '' : ' fail'}`}>
<Icon d={c.ok ? CHECK : CROSS} size={14} />
{c.label}
</p>
))}
<p className="p2v-label pr-gap">{t('playreel.final.proof')}</p>
<img className="p2v-review__image pr-image" src={data.proof_url} alt={t('playreel.final.proof')} />
<p className="p2v-note">{t('playreel.final.version', { version: data.version })}</p>
</div>
</div>
);
};
// ── 게이트 셸 ───────────────────────────────────────────────────────────
/**
* 롱컷 검수 게이트. 파이프라인이 사람의 확인을 기다리며 멈추는 5개 지점 중 하나를 그린다.
*
* 승인하면 다음 단계가 이어지고, 크레딧을 이미 쓴 지점(연출 확인 이후)부터는 되돌릴 수 없다.
* 고친 값은 `edits` ref 에 모았다가 승인할 때 함께 보낸다 — 입력마다 요청하지 않는다.
*/
const PlayreelGateContent: React.FC<PlayreelGateContentProps> = ({ job, onChanged, onAutoApproved }) => {
const { t } = useTranslation();
const edits = useRef<GateEdits | null>(null);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const prefs = useAutoApprove();
const autoFired = useRef(false); // 같은 게이트에 두 번 보내지 않는다
const { gate, review } = job;
// 자동 승인이 켜진 게이트(①·③)는 폴링이 검수 대기를 보는 순간 한 번만 승인한다.
// 실패하면 카드가 그대로 남아 사람이 직접 누를 수 있다.
const autoGate = isAutoApprovable(gate) && prefs[gate] ? gate : null;
const autoActive = autoGate !== null && !error;
useEffect(() => {
if (!autoGate || autoFired.current) return;
autoFired.current = true;
approvePlayreelGate(job.id, autoGate, null)
.then(() => {
onAutoApproved(autoGate);
onChanged();
})
.catch((e) => setError(t('playreel.auto.failed', { message: (e as Error).message })));
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [autoGate]);
if (!gate || !review) return null;
if (autoActive) {
return (
<div className="p2v-scope p2v-making">
<div className="p2v-spinner" aria-hidden="true" />
<p className="p2v-making__desc">
{t('playreel.auto.working', { step: GATE_ORDER.indexOf(gate) + 1, name: t(`playreel.gates.${gate}.name`) })}
</p>
<p className="p2v-note">{t('playreel.auto.hint')}</p>
</div>
);
}
const step = GATE_ORDER.indexOf(gate) + 1;
const run = async (request: () => Promise<unknown>) => {
setBusy(true);
setError(null);
try {
await request();
edits.current = null;
onChanged();
} catch (e) {
setError((e as Error).message);
} finally {
setBusy(false);
}
};
const approveLabel =
gate === 'final_confirm' ? t('playreel.gate.approveFinal')
: gate === 'clip_confirm' ? t('playreel.gate.approveClip')
: t('playreel.gate.approve');
const renderBody = () => {
switch (review.gate) {
case 'fetch_confirm':
return <FetchGate data={review.data} onChange={(e) => { edits.current = e; }} />;
case 'analysis_confirm':
return <AnalysisGate data={review.data} onChange={(e) => { edits.current = e; }} />;
case 'narration_confirm':
return <NarrationGate data={review.data} onChange={(e) => { edits.current = e; }} />;
case 'clip_confirm':
return <ClipGate data={review.data} />;
case 'final_confirm':
return <FinalGate data={review.data} />;
}
};
return (
<div className="p2v-scope p2v-review pr-gate">
<p className="pr-gate__eyebrow">
{t('playreel.gate.progress', { step, total: GATE_ORDER.length, name: t(`playreel.gates.${gate}.name`) })}
</p>
<h2 className="pr-gate__title">{t(`playreel.gates.${gate}.title`)}</h2>
<p className="p2v-help">{t(`playreel.gates.${gate}.why`)}</p>
{renderBody()}
{error && <div className="p2v-note warn">{error}</div>}
<button
type="button"
className="p2v-btn-cta"
disabled={busy}
onClick={() => run(() => approvePlayreelGate(job.id, gate, edits.current))}
>
{busy ? t('playreel.gate.working') : approveLabel}
</button>
<div className="pr-gate__actions">
{gate === 'clip_confirm' && (
<button
type="button"
className="p2v-btn-outline"
disabled={busy}
onClick={() => run(() => retryPlayreelClip(job.id))}
>
{t('playreel.gate.redo')}
</button>
)}
{GATE_CAN_BACK[gate] && (
<button
type="button"
className="p2v-btn-outline"
disabled={busy}
onClick={() => run(() => backPlayreelGate(job.id))}
>
{t('playreel.gate.back')}
</button>
)}
</div>
<p className="p2v-note">
{t('playreel.gate.next', {
next: t(`playreel.gates.${gate}.next`),
eta: t(`playreel.gates.${gate}.eta`),
})}
</p>
</div>
);
};
export default PlayreelGateContent;