사업장 API 가 전부 "요청자 = 소유자" 로 걸러져서 관리자가 남의 빌더·미니블로그를 열면 PLACE_NOT_FOUND 였다. 운영 중 사업장 정리도 사장님 계정으로 들어가야 했다. - validator/dependencies: DEVELOPER 가 place_id 경로를 부르면 그 사업장 소유자 신원으로 처리 — [admin-access] 로그 - ops/sites: search(상호·소유자 이메일·이름·아이디) · category 필터, 건수도 같은 조건 - OpsSitesPage: 검색창 · 업종 칩 · 행마다 빌더·미니블로그·삭제(공개 중이면 발행 내린 뒤 삭제) - SitesPage: 더보기에서 미니블로그 관리 · 예약요청 관리 제거 테스트 4건 추가(test_admin_access). 전체 900 passed · 145 failed(변경 전과 같은 파일: agent_runtime·gemini 등) frontend tsc·eslint 통과 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
423 lines
17 KiB
TypeScript
423 lines
17 KiB
TypeScript
import {SocialConnectionCard} from '@/features/social/SocialConnectionCard';
|
|
import {KakaoChannelCard} from '@/features/agent/KakaoChannelCard';
|
|
import {AgentChatDock} from '@/features/agent/AgentChatDock';
|
|
import {SocialConnectionNotice} from '@/features/social/SocialConnectionNotice';
|
|
import {useMemo, useState} from 'react';
|
|
import {Link, useNavigate} from 'react-router';
|
|
import {
|
|
Building2,
|
|
Coffee,
|
|
ExternalLink,
|
|
Loader2,
|
|
MoreHorizontal,
|
|
Pencil,
|
|
Plus,
|
|
Search,
|
|
SearchX,
|
|
Stethoscope,
|
|
UtensilsCrossed,
|
|
Wand2,
|
|
X,
|
|
} from 'lucide-react';
|
|
import {PlaceCategory, publishUrlString, SiteStatus} from '@o2o/shared';
|
|
import {changeStatus, PublishAction, useListMySites, type MySiteData} from '@/api';
|
|
import {AppShell, EmptyState, PageContainer} from '@/components/layout/AppShell';
|
|
import {Badge} from '@/components/ui/badge';
|
|
import {Button} from '@/components/ui/button';
|
|
import {Input} from '@/components/ui/input';
|
|
import {notify, notifyApiError} from '@/lib/notify';
|
|
import {PUBLISH_HOST} from '@/lib/site';
|
|
import {cn} from '@/lib/utils';
|
|
|
|
// 발행본 주소는 PublishModal·CanvasView 와 같은 규칙이다 — 세 곳이 다른 주소를 말하면 안 된다.
|
|
|
|
const CATEGORY_ICON: Record<number, typeof Building2> = {
|
|
[PlaceCategory.LODGING]: Building2,
|
|
[PlaceCategory.CAFE]: Coffee,
|
|
[PlaceCategory.RESTAURANT]: UtensilsCrossed,
|
|
[PlaceCategory.CLINIC]: Stethoscope,
|
|
};
|
|
|
|
/** 줄이 속하는 칸. */
|
|
type SiteBucket = 'live' | 'draft';
|
|
type SiteFilter = SiteBucket | 'all';
|
|
|
|
/** 칸은 **둘**이다. */
|
|
const FILTER_LABEL: Record<SiteFilter, string> = {
|
|
all: '전체',
|
|
live: '발행됨',
|
|
draft: '발행 전',
|
|
};
|
|
|
|
const FILTER_TABS: readonly SiteFilter[] = ['all', 'live', 'draft'];
|
|
|
|
const BUCKET_ORDER: Record<SiteBucket, number> = {live: 0, draft: 1};
|
|
|
|
function bucketOf(row: MySiteData): SiteBucket {
|
|
return row.site_id && row.status === SiteStatus.PUBLISHED ? 'live' : 'draft';
|
|
}
|
|
|
|
/** 줄의 상태 배지. */
|
|
function statusBadge(row: MySiteData) {
|
|
if (bucketOf(row) === 'live') {
|
|
return row.needs_rebuild
|
|
? {label: '수정됨 · 재발행 필요', variant: 'warning' as const}
|
|
: {label: '발행됨', variant: 'success' as const};
|
|
}
|
|
if (row.status === SiteStatus.SUSPENDED) return {label: '중지', variant: 'outline' as const};
|
|
if (row.status === SiteStatus.UNPUBLISHED) return {label: '내림', variant: 'outline' as const};
|
|
return {label: '발행 전', variant: 'default' as const};
|
|
}
|
|
|
|
/** 발행본이 실제로 열리는 주소. */
|
|
function publishedUrl(row: MySiteData): string | null {
|
|
if (row.status !== SiteStatus.PUBLISHED || !row.domain) return null;
|
|
return publishUrlString(row.domain.split('.')[0], PUBLISH_HOST);
|
|
}
|
|
|
|
/** 줄 뒤에 붙는 시각. */
|
|
function whenLabel(row: MySiteData): string {
|
|
const raw = row.published_at ?? row.created_at;
|
|
if (!raw) return '';
|
|
const at = new Date(raw);
|
|
if (Number.isNaN(at.getTime())) return '';
|
|
const now = new Date();
|
|
const date = at.toLocaleDateString('ko-KR', {
|
|
...(at.getFullYear() === now.getFullYear() ? {} : {year: 'numeric'}),
|
|
month: 'long',
|
|
day: 'numeric',
|
|
});
|
|
return row.published_at ? `${date} 발행` : `${date} 만듦`;
|
|
}
|
|
|
|
/** 정렬용 시각. */
|
|
function rowTime(row: MySiteData): number {
|
|
const raw = row.published_at ?? row.created_at;
|
|
if (!raw) return 0;
|
|
const at = new Date(raw).getTime();
|
|
return Number.isNaN(at) ? 0 : at;
|
|
}
|
|
|
|
/** 검색 비교용 정규화. */
|
|
function normalizeText(value: string): string {
|
|
return value.toLowerCase().replace(/\s+/g, '');
|
|
}
|
|
|
|
/** 상호와 도로명 주소만 본다 — 상호가 겹치는 줄을 실제로 가르는 건 주소다. */
|
|
function matchesQuery(row: MySiteData, needle: string): boolean {
|
|
if (!needle) return true;
|
|
return normalizeText(row.name).includes(needle) || normalizeText(row.road_address ?? '').includes(needle);
|
|
}
|
|
|
|
/** 줄 앞의 그림. */
|
|
function SiteThumb({row, Icon}: {row: MySiteData; Icon: typeof Building2}) {
|
|
const [failed, setFailed] = useState(false);
|
|
const src = row.thumbnail_url;
|
|
|
|
// 비율은 **16:10 — 브라우저 창 비율**이다.
|
|
if (!src || failed) {
|
|
return (
|
|
<div className="flex aspect-[16/10] w-full items-center justify-center border-b border-border bg-muted/60">
|
|
<Icon className="size-7 text-muted-foreground/60" />
|
|
</div>
|
|
);
|
|
}
|
|
return (
|
|
<img
|
|
src={src}
|
|
alt=""
|
|
loading="lazy"
|
|
onError={() => setFailed(true)}
|
|
className="aspect-[16/10] w-full border-b border-border object-cover"
|
|
/>
|
|
);
|
|
}
|
|
|
|
/** 내 사이트 — 로그인한 사장님의 홈이다. */
|
|
export function SitesPage() {
|
|
const navigate = useNavigate();
|
|
const {data, isLoading, isError, error, refetch} = useListMySites({size: 50});
|
|
const [busyId, setBusyId] = useState<string | null>(null);
|
|
const [menuId, setMenuId] = useState<string | null>(null);
|
|
const [query, setQuery] = useState('');
|
|
const [filter, setFilter] = useState<SiteFilter>('all');
|
|
|
|
const rows = useMemo(() => data?.sites ?? [], [data]);
|
|
|
|
// 서버로 안 보낸다.
|
|
const found = useMemo(() => {
|
|
const needle = normalizeText(query);
|
|
return rows.filter((row) => matchesQuery(row, needle));
|
|
}, [rows, query]);
|
|
|
|
// 건수는 **검색 결과 위에서** 센다.
|
|
const counts = useMemo(() => {
|
|
const tally: Record<SiteFilter, number> = {all: found.length, live: 0, draft: 0};
|
|
for (const row of found) tally[bucketOf(row)] += 1;
|
|
return tally;
|
|
}, [found]);
|
|
|
|
// 서버는 사업장 생성 역순으로만 준다(site_crud.list_owner_sites) — 발행 여부를 모른다.
|
|
const visible = useMemo(() => {
|
|
const picked = filter === 'all' ? found : found.filter((row) => bucketOf(row) === filter);
|
|
return [...picked].sort(
|
|
(a, b) => BUCKET_ORDER[bucketOf(a)] - BUCKET_ORDER[bucketOf(b)] || rowTime(b) - rowTime(a),
|
|
);
|
|
}, [found, filter]);
|
|
|
|
const isNarrowed = query.trim().length > 0 || filter !== 'all';
|
|
|
|
const resetView = () => {
|
|
setQuery('');
|
|
setFilter('all');
|
|
};
|
|
|
|
// 발행 내리기만 둔다.
|
|
const handleUnpublish = async (row: MySiteData) => {
|
|
if (!window.confirm(`'${row.name}' 사이트를 검색에서 내릴까요?\n주소는 그대로 두고 페이지만 내려갑니다.`)) return;
|
|
setMenuId(null);
|
|
setBusyId(row.place_id);
|
|
try {
|
|
const res = await changeStatus(row.place_id, {action: PublishAction.UNPUBLISH});
|
|
if (!res.result?.success) {
|
|
notifyApiError({data: res}, '사이트를 내리지 못했습니다.');
|
|
return;
|
|
}
|
|
notify.success('사이트를 내렸습니다.');
|
|
await refetch();
|
|
} catch (unpublishError) {
|
|
notifyApiError(unpublishError, '사이트를 내리지 못했습니다.');
|
|
} finally {
|
|
setBusyId(null);
|
|
}
|
|
};
|
|
|
|
return (
|
|
<AppShell>
|
|
<PageContainer
|
|
title="내 사이트"
|
|
description="만든 사이트를 열어 고치고, 다시 발행합니다."
|
|
actions={
|
|
<Button variant="primary" size="sm" onClick={() => navigate('/builder?new=1')}>
|
|
<Plus />새 사이트
|
|
</Button>
|
|
}
|
|
>
|
|
<SocialConnectionNotice />
|
|
{/* 연결은 사업장이 아니라 사람 단위다 — 목록 위에 한 자리만 둔다(SocialConnectionCard 주석). */}
|
|
<SocialConnectionCard />
|
|
{/* 카카오톡 연결도 사람 단위다 — 같은 자리에 나란히 둔다(KakaoChannelCard 주석). */}
|
|
<KakaoChannelCard />
|
|
{isLoading && (
|
|
<div className="flex items-center justify-center py-20 text-muted-foreground">
|
|
<Loader2 className="size-5 animate-spin" />
|
|
</div>
|
|
)}
|
|
|
|
{isError && (
|
|
<EmptyState
|
|
title="목록을 불러오지 못했습니다"
|
|
description={(error as Error)?.message ?? '잠시 후 다시 시도해 주세요.'}
|
|
action={
|
|
<Button size="sm" onClick={() => refetch()}>
|
|
다시 시도
|
|
</Button>
|
|
}
|
|
/>
|
|
)}
|
|
|
|
{!isLoading && !isError && rows.length === 0 && (
|
|
<EmptyState
|
|
icon={Wand2}
|
|
title="아직 만든 사이트가 없습니다"
|
|
description="상호명 하나로 시작하면 AI 가 정보를 모아 사이트를 만듭니다."
|
|
action={
|
|
<Button variant="primary" size="sm" onClick={() => navigate('/builder?new=1')}>
|
|
<Plus />첫 사이트 만들기
|
|
</Button>
|
|
}
|
|
/>
|
|
)}
|
|
|
|
{!isLoading && !isError && rows.length > 0 && (
|
|
<div className="mb-3 flex flex-wrap items-center gap-2">
|
|
<div className="relative min-w-56 flex-1">
|
|
<Search className="pointer-events-none absolute top-1/2 left-2.5 size-3.5 -translate-y-1/2 text-muted-foreground" />
|
|
<Input
|
|
type="search"
|
|
value={query}
|
|
onChange={(event) => setQuery(event.target.value)}
|
|
placeholder="상호나 주소로 찾기"
|
|
aria-label="상호나 주소로 찾기"
|
|
className="h-9 pr-8 pl-8"
|
|
/>
|
|
{query && (
|
|
<button
|
|
type="button"
|
|
aria-label="검색어 지우기"
|
|
onClick={() => setQuery('')}
|
|
className="absolute top-1/2 right-2 -translate-y-1/2 cursor-pointer text-muted-foreground transition-colors hover:text-foreground"
|
|
>
|
|
<X className="size-3.5" />
|
|
</button>
|
|
)}
|
|
</div>
|
|
|
|
{/* 건수를 배지가 아니라 칸 안에 붙인다 — "34가 어디 있나"는 칸을 눌러 보기 전에 보여야 한다. */}
|
|
<div className="flex items-center gap-0.5 rounded-md border border-border p-0.5">
|
|
{FILTER_TABS.map((key) => (
|
|
<button
|
|
key={key}
|
|
type="button"
|
|
aria-pressed={filter === key}
|
|
onClick={() => setFilter(key)}
|
|
className={cn(
|
|
'h-8 cursor-pointer rounded px-2.5 text-xs font-medium transition-colors',
|
|
filter === key
|
|
? 'bg-muted text-foreground'
|
|
: 'text-muted-foreground hover:text-foreground',
|
|
)}
|
|
>
|
|
{FILTER_LABEL[key]}
|
|
<span className="ml-1 tabular-nums opacity-60">{counts[key]}</span>
|
|
</button>
|
|
))}
|
|
</div>
|
|
</div>
|
|
)}
|
|
|
|
{/* 처음 온 사람의 빈 화면과 섞지 않는다 — 사이트가 35개인데 "아직 없습니다" 라고 하면 사장님은 목록이 아니라 자기 사이트가 사라진 줄 안다. */}
|
|
{!isLoading && !isError && rows.length > 0 && visible.length === 0 && (
|
|
<EmptyState
|
|
icon={SearchX}
|
|
title="조건에 맞는 사이트가 없습니다"
|
|
description={`가진 사이트 ${rows.length}개 중에 없습니다. 검색어를 줄이거나 다른 칸을 보세요.`}
|
|
action={
|
|
<Button size="sm" onClick={resetView}>
|
|
조건 지우기
|
|
</Button>
|
|
}
|
|
/>
|
|
)}
|
|
|
|
{visible.length > 0 && (
|
|
/* 줄이 아니라 카드다. */
|
|
<ul className="grid grid-cols-1 gap-4 sm:grid-cols-2 xl:grid-cols-3">
|
|
{visible.map((row) => {
|
|
const Icon = CATEGORY_ICON[row.category] ?? Building2;
|
|
const badge = statusBadge(row);
|
|
const url = publishedUrl(row);
|
|
const isLive = bucketOf(row) === 'live';
|
|
const editHref = `/builder?placeId=${row.place_id}`;
|
|
|
|
return (
|
|
/* 카드는 **상태와 무관하게 같은 골격**이다. */
|
|
<li
|
|
key={row.place_id}
|
|
className="group relative flex h-full flex-col overflow-hidden rounded-xl border border-border bg-card transition-shadow hover:shadow-md"
|
|
>
|
|
<Link to={editHref} className="block">
|
|
<SiteThumb row={row} Icon={Icon} />
|
|
</Link>
|
|
|
|
{/* 배지는 그림 위에 얹는다 — 카드에서 상태는 제목보다 먼저 읽혀야 한다. */}
|
|
<Badge variant={badge.variant} className="absolute top-2.5 left-2.5 shadow-sm">
|
|
{badge.label}
|
|
</Badge>
|
|
|
|
<div className="flex flex-1 flex-col p-3.5">
|
|
<Link to={editHref} className="block min-w-0">
|
|
<p className="truncate text-sm font-semibold">{row.name}</p>
|
|
{/* 나가 있는 카드만 주소를 진하게. */}
|
|
<p
|
|
className={cn(
|
|
'mt-1 truncate text-xs',
|
|
isLive ? 'font-medium text-foreground' : 'text-muted-foreground',
|
|
)}
|
|
>
|
|
{url ?? (row.domain ? `주소 예약됨 · ${row.domain}` : '주소를 아직 정하지 않았습니다')}
|
|
</p>
|
|
{/* 같은 상호가 여럿일 때 가르는 값 — 주소와 시각. */}
|
|
<p className="mt-1 mb-3 truncate text-[11px] text-muted-foreground/70">
|
|
{[row.road_address, whenLabel(row)].filter(Boolean).join(' · ')}
|
|
</p>
|
|
</Link>
|
|
|
|
<div className="mt-auto flex items-center gap-1.5 border-t border-border pt-3">
|
|
<Button size="sm" className="flex-1" onClick={() => navigate(editHref)}>
|
|
<Pencil />
|
|
편집
|
|
</Button>
|
|
{url && (
|
|
<a
|
|
href={url}
|
|
target="_blank"
|
|
rel="noopener noreferrer"
|
|
className="inline-flex h-8 items-center gap-1.5 rounded-md border border-border px-2.5 text-xs font-medium transition-colors hover:bg-muted"
|
|
>
|
|
<ExternalLink className="size-3.5" />
|
|
열기
|
|
</a>
|
|
)}
|
|
<Button
|
|
size="icon"
|
|
variant="ghost"
|
|
aria-label="관리 메뉴"
|
|
isLoading={busyId === row.place_id}
|
|
onClick={() => setMenuId(menuId === row.place_id ? null : row.place_id)}
|
|
>
|
|
{busyId === row.place_id ? null : <MoreHorizontal />}
|
|
</Button>
|
|
</div>
|
|
</div>
|
|
|
|
{menuId === row.place_id && (
|
|
<>
|
|
{/* 바깥을 눌러 닫는다. */}
|
|
<button
|
|
type="button"
|
|
aria-label="닫기"
|
|
className="fixed inset-0 z-10 cursor-default"
|
|
onClick={() => setMenuId(null)}
|
|
/>
|
|
<div className="absolute right-3.5 bottom-12 z-20 w-52 rounded-md border border-border bg-card py-1 shadow-md">
|
|
<button
|
|
type="button"
|
|
onClick={() => {
|
|
setMenuId(null);
|
|
navigate(editHref);
|
|
}}
|
|
className="flex w-full cursor-pointer items-center gap-2 px-3 py-2 text-left text-xs transition-colors hover:bg-muted"
|
|
>
|
|
<Pencil className="size-3.5" />
|
|
디자인·컨텐츠 관리
|
|
</button>
|
|
<div className="my-1 border-t border-border" />
|
|
<button
|
|
type="button"
|
|
disabled={row.status !== SiteStatus.PUBLISHED}
|
|
onClick={() => handleUnpublish(row)}
|
|
className="w-full cursor-pointer px-3 py-2 text-left text-xs text-destructive transition-colors hover:bg-muted disabled:cursor-not-allowed disabled:opacity-40"
|
|
>
|
|
발행 내리기
|
|
</button>
|
|
</div>
|
|
</>
|
|
)}
|
|
</li>
|
|
);
|
|
})}
|
|
</ul>
|
|
)}
|
|
|
|
</PageContainer>
|
|
|
|
{/* 떠 있는 대화창. */}
|
|
<AgentChatDock sites={rows.map((row) => ({place_id: String(row.place_id), name: row.name}))} />
|
|
</AppShell>
|
|
);
|
|
}
|
|
|
|
// 라우트 모듈은 default export 를 요구한다(routes.ts 가 이 파일을 가리킨다).
|
|
export default SitesPage;
|