import { useQuery, useQueryClient } from '@tanstack/react-query' import { useEffect, useState } from 'react' import { useSearchParams } from 'react-router' import { cardAction, useTargets } from '../api/targets' import type { Target } from '../api/targets' type Card = { card_id: number; template: string; topic?: string; title: string; status: 1 | 2 | 3; post_id?: number; created_at: string; published_at?: string; image_urls: string[]; ig_media_id?: string } type Status = Card['status'] const STATUS: Record = { 2: { label: '올림', tone: 'bg-rust-soft text-rust' }, 1: { label: '승인 대기', tone: 'bg-warn-soft text-warn' }, 3: { label: '반려', tone: 'bg-rail text-muted' }, } const TEMPLATE: Record = { tarot: '날씨 타로', ootd: '오늘의 코디' } const DAY = ['일', '월', '화', '수', '목', '금', '토'] function when(iso: string) { const d = new Date(iso) return `${d.getMonth() + 1}.${d.getDate()} ${DAY[d.getDay()]} ${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}` } /** 발행된 포스트가 쌓이는 곳. 올릴 곳(로컬·킹서버)마다 날씨각 서버에 저장된 카드를 보여 주고, 다시 내려받거나 올리거나 인스타에 보낸다 */ export function HistoryPage() { const { data: targets = [] } = useTargets() const [params, setParams] = useSearchParams() const target = targets.find((t) => t.id === params.get('target')) ?? targets[0] const status = (Number(params.get('status')) || 0) as 0 | Status const set = (next: Record) => setParams((p) => { for (const [k, v] of Object.entries(next)) { if (v) p.set(k, v) else p.delete(k) } return p }, { replace: true }) return (

만든 카드

올리거나 승인 대기로 저장한 카드가 서버에 쌓여요. 장마다 JPEG로 다시 내려받을 수 있어요.

{targets.length > 1 && (
{targets.map((t) => ( ))}
)}
{target ? set({ status: s ? String(s) : '' })} /> :

올릴 곳이 없어요. 관리자 서버에 ADMIN_API_KEY(로컬)·KING_ADMIN_API_KEY(킹서버)를 주고 다시 켜 주세요.

}
) } function CardList({ target, status, onStatus }: { target: Target; status: 0 | Status; onStatus: (s: 0 | Status) => void }) { const qc = useQueryClient() const { data, error, isLoading } = useQuery({ queryKey: ['cards', target.id], queryFn: async () => { const r = await fetch(`/api/cards?target=${target.id}`) const body = await r.json() if (!r.ok || body.result?.success === false) throw new Error(body.error ?? body.result?.desc ?? `HTTP ${r.status}`) return body.items as Card[] }, }) const [busy, setBusy] = useState(null) const [note, setNote] = useState<{ id: number; text: string; bad?: boolean } | null>(null) useEffect(() => { if (!note || note.bad) return const t = setTimeout(() => setNote(null), 4000) return () => clearTimeout(t) }, [note]) const act = async (c: Card, what: 'publish' | 'reject' | 'instagram') => { setBusy(c.card_id) setNote(null) try { const r = await cardAction(target.id, c.card_id, what) await qc.invalidateQueries({ queryKey: ['cards', target.id] }) setNote({ id: c.card_id, text: what === 'instagram' ? `인스타에 올렸어요 (${r.ig_media_id})` : what === 'publish' ? `오늘 피드에 올렸어요 (포스트 ${r.post_id})` : '반려했어요' }) } catch (e) { setNote({ id: c.card_id, text: e instanceof Error ? e.message : String(e), bad: true }) } finally { setBusy(null) } } const downloadAll = (c: Card) => { c.image_urls.forEach((u, i) => setTimeout(() => { const a = document.createElement('a') a.href = `${target.api}${u}` a.download = `card-${c.card_id}-${i + 1}.jpg` a.target = '_blank' a.rel = 'noreferrer' a.click() }, i * 400), ) } const counts = { 0: data?.length ?? 0, 1: 0, 2: 0, 3: 0 } as Record<0 | Status, number> for (const c of data ?? []) counts[c.status] += 1 const shown = (data ?? []).filter((c) => !status || c.status === status) return (
{([0, 2, 1, 3] as const).map((s) => ( ))}
{error && (
{target.label} 목록을 받지 못했어요: {error instanceof Error ? error.message : String(error)}
)} {isLoading && (
{[0, 1].map((i) => (
))}
)} {data && shown.length === 0 &&

{status ? `${STATUS[status].label} 카드가 없어요.` : `${target.label}에 저장한 카드가 아직 없어요. 인스타 카드 탭에서 만들어 올려 보세요.`}

}
    {shown.map((c) => { const st = STATUS[c.status] const mine = note?.id === c.card_id ? note : null return (
  • {st.label} {c.title} {TEMPLATE[c.template] ?? c.template} {c.topic ? ` · ${c.topic}` : ''} · {c.image_urls.length}장 · 카드 {c.card_id}
      {c.image_urls.map((u, i) => (
    1. {`${c.title}
    2. ))}
    만든 때
    {when(c.created_at)}
    {c.published_at && ( <>
    올린 때
    {when(c.published_at)} · 포스트 {c.post_id} ·{' '} 피드에서 보기
    )} {c.ig_media_id && ( <>
    인스타
    올림 · {c.ig_media_id}
    )}
    {mine && (

    {mine.bad ? `처리하지 못했어요: ${mine.text}` : mine.text}

    )}
    {c.status === 1 && ( )} {c.status === 2 && !c.ig_media_id && ( )} {c.status === 1 && ( )}
  • ) })}
) }