Merge branch 'feature/social-post'

This commit is contained in:
skkim committed 2026-09-18 09:00:07 +09:00
commit 46171b4f24
55 files changed
+2872 -7

No files matched your search

@@ -5,6 +5,7 @@
* 여기 한 줄을 더한다는 뜻이고, 그 순간 캔버스와 고르는 UI가 동시에 늘어난다.
*/
import type {IndustryType, SectionItem} from '@o2o/shared';
import {SocialCanvasSection} from '@/features/social/SocialCanvasSection';
import type {SectionVariant} from './types';
import {HeroCover} from './variants/hero/HeroCover';
@@ -367,6 +368,7 @@ export const SECTION_VARIANTS: Record<string, SectionVariant[]> = {
},
],
social: [{id: 'social.cards', name: '함께 발행한 소식', description: '승인해 SNS에 게재한 최신 소식. 홈페이지 맨 아래에 표시합니다.', thumb: 'cards', Component: SocialCanvasSection, isDefault: true}],
songs: [
{
id: 'songs.turntable',
@@ -1,3 +1,4 @@
import {SocialPanel} from '@/features/social/SocialPanel';
import {useCallback, useEffect, useMemo, useState} from 'react';
import {useNavigate} from 'react-router';
import {
@@ -380,6 +381,7 @@ export function PublishModal() {
{/* ★ 서버 판정. 화면 점검(gate)이 통과여도 여기서 막힐 수 있다 — 저장된 fact 기준이라 기준값이 다르다. */}
<ServerVerdict state={state} />
{placeId && (isDone || isRepublish) && <SocialPanel placeId={placeId} />}
{isDone && (
<div className="flex items-center justify-between gap-2 rounded-lg border border-border bg-muted/40 p-3 text-left">
@@ -0,0 +1,10 @@
import {SectionBody, SectionFrame, SectionHeading} from '@/features/builder/canvas/primitives';
import type {SectionRenderProps} from '@/features/builder/canvas/types';
export function SocialCanvasSection({section, isSelected, onSelect, template}: SectionRenderProps) {
return <SectionFrame section={section} isSelected={isSelected} onSelect={onSelect} tone="paper">
<SectionBody width="narrow">
<SectionHeading variant="minimal" title="함께 발행한 소식" subtitle="승인해 Threads에 게재한 최신 소식이 홈페이지 맨 아래에 표시됩니다." colors={template.colors} />
</SectionBody>
</SectionFrame>;
}
@@ -0,0 +1,132 @@
import {useCallback, useEffect, useState} from 'react';
import {Loader2, Link2, Unlink} from 'lucide-react';
import {Button} from '@/components/ui/button';
import {socialApi, type SocialState} from './api';
/**
* Threads 계정 연동 — **'내 사이트' 화면에 한 자리**.
*
* ★ 왜 발행 모달이 아니라 여기인가
* 계정은 `user × provider` 단위다(표도 그렇게 생겼다 — `owner_social_accounts`).
* 연결 버튼이 사업장 안에 있으면 사장님은 **업장 수만큼 연결해야 하는 줄 안다.**
* 연결은 한 번, 게재는 사이트마다다 — 화면이 그 모양을 그대로 말해야 한다.
* 그래서 여기서 미리 연결해 두고, 발행한 뒤 사이트에서 [소개글 쓰기] 를 누른다.
*
* ★ 준비 전에도 **자리는 보여준다.** 단, 버튼은 죽여 둔다.
* 처음에는 `connection_enabled=false` 면 통째로 숨겼는데, 그러면 **기능이 없는 것처럼 보인다** —
* 이 기능을 만든 사람조차 "연동 버튼이 안 보인다" 고 했다(2026-09-14). 사장님은 더더욱 못 찾는다.
* 숨기는 것과 "아직 준비 중" 은 다른 말이고, 화면은 그 둘을 구별해 말해야 한다.
* 앱 자격증명이 없으면 눌러도 409 이므로(`SOCIAL_CONNECTION_DISABLED`) **버튼은 비활성**이다 —
* 보이되 눌리지 않고, 왜 아직인지 한 줄로 말한다(docs/SOCIAL.md '연동 준비').
*/
export function SocialConnectionCard() {
const [state, setState] = useState<SocialState | null>(null);
const [busy, setBusy] = useState(false);
const [error, setError] = useState('');
const load = useCallback(async () => {
try {
setState(await socialApi<SocialState>('/account'));
} catch {
// 연결 상태를 못 읽는 것은 사이트 목록을 못 보여줄 이유가 아니다 — 조용히 접는다.
setState(null);
}
}, []);
useEffect(() => {
void load();
}, [load]);
// 상태를 아직 못 읽었을 때만 접는다(로그인 직후 한순간). '준비 안 됨' 과는 다르다.
if (!state) return null;
const ready = state.connection_enabled;
const account = state.account;
const needsReauth = account?.status === 'needs_reauth';
async function run(fn: () => Promise<unknown>) {
setBusy(true);
setError('');
try {
await fn();
await load();
} catch (e) {
setError(e instanceof Error ? e.message : '요청을 처리하지 못했습니다.');
} finally {
setBusy(false);
}
}
const connect = () =>
run(async () => {
const {url} = await socialApi<{url: string}>('/oauth/connect', {});
// 인가 화면은 Meta 쪽이다. 돌아오면 `/sites?social=…` 로 되돌아온다.
window.location.assign(url);
});
return (
<section className="mb-4 rounded-xl border border-border p-4">
<div className="flex flex-wrap items-center justify-between gap-3">
<div className="min-w-0">
<h2 className="text-sm font-bold">SNS 연동 · Threads</h2>
<p className="mt-1 text-xs text-muted-foreground">
{!ready
? '연동 준비 중입니다. 열리면 여기서 계정을 연결합니다.'
: account
? needsReauth
? '연결이 만료됐습니다. 다시 연결해야 게재할 수 있습니다.'
: '연결되어 있습니다. 사이트를 발행한 뒤 소개글을 써서 올릴 수 있습니다.'
: '미리 연결해 두면, 사이트를 발행한 뒤 소개글을 써서 이 계정으로 올립니다.'}
</p>
{account && (
<p className="mt-1 text-xs">
<a
href={account.profile_url}
target="_blank"
rel="noopener noreferrer"
className="font-bold underline underline-offset-4"
>
@{account.handle}
</a>
</p>
)}
</div>
<div className="flex shrink-0 flex-wrap gap-2">
<Button
size="sm"
variant={account && !needsReauth ? 'outline' : 'primary'}
disabled={busy || !ready}
onClick={connect}
>
{busy ? <Loader2 className="size-4 animate-spin" /> : <Link2 className="size-4" />}
<span>{account ? '다시 연결' : 'Threads 계정 연결'}</span>
</Button>
{account && (
<Button
size="sm"
variant="ghost"
disabled={busy}
onClick={() => run(() => socialApi('/oauth/disconnect', {}))}
>
<Unlink className="size-4" />
<span>연결 해제</span>
</Button>
)}
</div>
</div>
{/* 게재가 아직 안 열린 상태를 숨기지 않는다 — 연결만 해 두고 기다리는 것도 사장님의 선택이다. */}
{ready && !state.posting_enabled && (
<p className="mt-3 text-xs text-muted-foreground">
자동 게재는 준비 중입니다. 지금은 소개글을 만들어 복사하거나 내용을 확인할 수 있습니다.
</p>
)}
{error && (
<p role="alert" className="mt-3 text-xs text-destructive">
{error}
</p>
)}
</section>
);
}
@@ -0,0 +1,10 @@
import {useSearchParams} from 'react-router';
export function SocialConnectionNotice() {
const [query] = useSearchParams();
const status = query.get('social');
if (!status) return null;
return <p role="status" className="mb-4 rounded-lg border p-4 text-sm">{status === 'connected'
? 'Threads 계정을 연결했습니다. 홈페이지 발행 화면에서 원고를 확인하고 게재를 승인해 주세요.'
: 'Threads 연결을 완료하지 못했습니다. 권한을 확인한 뒤 다시 연결해 주세요.'}</p>;
}
@@ -0,0 +1,69 @@
import {useCallback, useEffect, useState} from 'react';
import {Button} from '@/components/ui/button';
import {socialApi, postStatus, statusLabels, type SocialState} from './api';
export function SocialPanel({placeId}: {placeId: string}) {
const [state, setState] = useState<SocialState | null>(null);
const [busy, setBusy] = useState(false);
const [message, setMessage] = useState('');
const refresh = useCallback(async () => {
setState(await socialApi<SocialState>(`/place/${placeId}`));
}, [placeId]);
useEffect(() => {
let alive = true;
const load = () => socialApi<SocialState>(`/place/${placeId}`).then((data) => {
if (alive) setState(data);
}).catch(() => {if (alive) setMessage('SNS 상태를 불러오지 못했습니다.');});
void load();
const interval = window.setInterval(() => {void load();}, 5000);
return () => {alive = false; window.clearInterval(interval);};
}, [placeId]);
async function action(fn: () => Promise<unknown>) {
setBusy(true); setMessage('');
try {await fn(); await refresh();}
catch (e) {setMessage(e instanceof Error ? e.message : '요청에 실패했습니다.'); await refresh().catch(() => {});}
finally {setBusy(false);}
}
return <section className="space-y-3 rounded-xl border border-border p-4 text-sm">
<h3 className="font-bold">Threads에 알리기</h3>
<p className="text-xs text-muted-foreground">확인된 가게 정보로 소개글을 씁니다. 글을 복사해 직접 올릴 수도 있습니다.</p>
{state?.account && <p>게재 계정: <strong>@{state.account.handle}</strong>
{state.account.status === 'needs_reauth' && ' · 다시 연결해 주세요'}</p>}
<div className="flex flex-wrap gap-2">
<Button size="sm" disabled={busy || !state} onClick={() => void action(() => socialApi(`/place/${placeId}/draft`, {}))}>소개글 쓰기</Button>
</div>
{/*
★ 연결 버튼을 여기 두지 않는다 (2026-09-14). 계정은 `user × provider` 하나인데 버튼이
사업장 화면에 있으면 사장님은 **업장마다 연결해야 하는 줄 안다.** 연결은 [내 사이트]에
한 자리, 게재는 사이트마다다 — 화면이 그 모양을 그대로 말한다.
★ 그래서 여기서는 "연결이 없다" 를 **막다른 문구가 아니라 갈 곳**으로 알린다.
*/}
{state && state.connection_enabled && !state.account && (
<p className="text-xs text-muted-foreground">
아직 Threads 계정이 연결되지 않았습니다 — <a href="/sites" className="underline underline-offset-4">내 사이트</a> 화면에서 한 번만 연결하면 됩니다. 연결 전에도 소개글을 만들어 복사할 수 있습니다.
</p>
)}
{state && !state.posting_enabled && <p className="text-xs text-muted-foreground">자동 게재 연동을 준비 중입니다. 글 복사와 내용 확인을 이용할 수 있습니다. 지금 확인해도 계정 연결 후 다시 승인받습니다.</p>}
<p role="status" aria-live="polite">{message}</p>
{state?.posts.map((post) => {
const status = postStatus(post);
return <article key={post.post_id} className="space-y-2 rounded-lg bg-muted/40 p-3">
<p className="font-semibold">{statusLabels[status] ?? status}</p>
<p className="whitespace-pre-wrap break-words">{post.body}</p>
{post.approval_expires_at && <p className="text-xs text-muted-foreground">승인 기한: {new Date(post.approval_expires_at).toLocaleString('ko-KR', {timeZone: 'Asia/Seoul'})} (한국시간)</p>}
{post.last_error && <p className="text-xs text-destructive">{post.last_error === 'ALIMTALK_SEND_FAILED' ? '알림톡 발송 실패 · 여기서 승인할 수 있습니다.' : status === 'UNKNOWN' ? 'Threads 계정에서 실제 게재 여부를 확인해 주세요. 중복을 막기 위해 자동으로 다시 올리지 않습니다.' : '처리에 실패했습니다. 글은 보관되어 있습니다.'}</p>}
<div className="flex flex-wrap gap-2">
{post.body && <Button size="sm" variant="outline" onClick={() => {
void navigator.clipboard.writeText(post.body).then(() => setMessage('글과 홈페이지 링크를 복사했습니다.')).catch(() => setMessage('복사하지 못했습니다. 위 글을 선택해 복사해 주세요.'));
}}>글 복사</Button>}
{(!state.posting_enabled || state.account?.status === 'linked') && (['DRAFT', 'DECLINED', 'EXPIRED', 'FAILED'].includes(status) || (status === 'APPROVED' && !post.account_bound) || (status === 'PENDING_APPROVAL' && !!post.last_error)) && post.body && <Button size="sm" disabled={busy} onClick={() => void action(() => socialApi(`/posts/${post.post_id}/request-approval`, {}))}>{status === 'EXPIRED' ? '승인 다시 요청' : state.posting_enabled ? '게재 승인 요청' : '내용 확인 요청'}</Button>}
{status === 'PENDING_APPROVAL' && <>
<Button size="sm" disabled={busy} onClick={() => void action(() => socialApi(`/posts/${post.post_id}/decision`, {approve: true}))}>{post.account_bound ? '이 글을 게재할게요' : '내용을 확인했어요'}</Button>
<Button size="sm" variant="outline" disabled={busy} onClick={() => void action(() => socialApi(`/posts/${post.post_id}/decision`, {approve: false}))}>게재하지 않기</Button>
</>}
{post.permalink && <a href={post.permalink} target="_blank" rel="noopener noreferrer" className="underline">SNS에 올린 글 보기</a>}
</div>
</article>;
})}
</section>;
}
@@ -0,0 +1,43 @@
import {getAccessToken} from '@/api';
export type SocialPost = {
post_id: string; provider: number; body: string; link_url: string; status: string;
approval_expires_at?: string; approval_channel?: string; permalink?: string;
posted_at?: string; last_error?: string; account_handle?: string; account_bound: boolean;
};
export type SocialState = {
posts: SocialPost[]; connection_enabled: boolean; posting_enabled: boolean;
account: {handle: string; profile_url: string; status: string} | null;
};
const base = import.meta.env.VITE_API_BASE_URL ?? 'http://localhost:9800';
const messages: Record<string, string> = {
SOCIAL_PUBLISHED_FIXED_URL_REQUIRED: '홈페이지 주소를 확정하고 발행한 뒤 이용할 수 있습니다.',
NO_GROUNDED_FACTS: '확인된 정보가 아직 없습니다. 가게 정보를 먼저 확인해 주세요.',
SOCIAL_POSTING_DISABLED_COPY_AVAILABLE: '자동 게재를 준비 중입니다. 글을 복사해 직접 올릴 수 있습니다.',
ACCOUNT_CONNECTION_REQUIRED: 'Threads 계정을 먼저 연결해 주세요.',
APPROVAL_NOTIFICATION_FAILED_SCREEN_AVAILABLE: '알림톡을 보내지 못했습니다. 아래 카드에서 승인할 수 있습니다.',
PUBLISH_URL_CHANGED: '홈페이지 주소가 변경되었습니다. 기존 승인으로 게재할 수 없습니다.',
APPROVAL_NOT_FOUND: '유효하지 않거나 교체된 승인 링크입니다.',
PLACE_NOT_FOUND: '가게를 찾을 수 없습니다.',
};
export async function socialApi<T>(path: string, data?: unknown, publicAccess = false): Promise<T> {
const token = publicAccess ? null : getAccessToken();
const response = await fetch(`${base}/v1/social${path}`, {
method: data === undefined ? 'GET' : 'POST', credentials: 'include',
referrerPolicy: 'no-referrer', cache: 'no-store',
headers: {'Content-Type': 'application/json', ...(token ? {Authorization: `Bearer ${token}`} : {})},
body: data === undefined ? undefined : JSON.stringify(data),
});
const result = await response.json();
if (!response.ok) throw new Error(messages[result.detail] ?? '요청을 처리하지 못했습니다. 잠시 후 다시 확인해 주세요.');
return result as T;
}
export const statusLabels: Record<string, string> = {
DRAFTING: '글 작성 중', DRAFT: '초안', PENDING_APPROVAL: '승인 대기', APPROVED: '승인 완료',
POSTING: '게재 중', POSTED: '게재 완료', DECLINED: '게재하지 않음', EXPIRED: '승인 만료',
FAILED: '실패', UNKNOWN: '게재 결과 확인 필요',
};
export function postStatus(post: SocialPost) {
return post.status === 'PENDING_APPROVAL' && post.approval_expires_at && Date.parse(post.approval_expires_at) <= Date.now()
? 'EXPIRED' : post.status;
}