Files
o2o-weather/admin/src/pages/HistoryPage.tsx
T

208 lines
11 KiB
TypeScript

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<Status, { label: string; tone: string }> = {
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<string, string> = { 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<string, string>) => 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 (
<div className="mx-auto flex max-w-[1440px] flex-col gap-5 px-4 py-5 sm:px-6">
<header className="flex flex-wrap items-center justify-between gap-x-6 gap-y-3">
<div className="flex min-w-0 flex-col gap-0.5">
<h1 className="text-[20px] font-bold tracking-[-0.02em]">만든 카드</h1>
<p className="text-[13px] text-muted">올리거나 승인 대기로 저장한 카드가 서버에 쌓여요. 장마다 JPEG로 다시 내려받을 수 있어요.</p>
</div>
{targets.length > 1 && (
<div role="tablist" aria-label="올린 곳" className="flex gap-1 rounded-xl border border-line bg-panel p-1">
{targets.map((t) => (
<button key={t.id} role="tab" aria-selected={t.id === target?.id} onClick={() => set({ target: t.id })} className={`rounded-lg px-4 py-2 text-[14px] font-bold transition-colors duration-150 ${t.id === target?.id ? 'bg-ink text-white' : 'text-ink-soft hover:bg-rail'}`}>
{t.label}
</button>
))}
</div>
)}
</header>
{target ? <CardList target={target} status={status} onStatus={(s) => set({ status: s ? String(s) : '' })} /> : <p className="rounded-xl border border-bad/30 bg-bad-soft px-5 py-4 text-[14px] text-bad">올릴 곳이 없어요. 관리자 서버에 ADMIN_API_KEY(로컬)·KING_ADMIN_API_KEY(킹서버)를 주고 다시 켜 주세요.</p>}
</div>
)
}
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<number | null>(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 (
<div className="flex flex-col gap-4">
<div role="radiogroup" aria-label="상태" className="flex flex-wrap gap-1.5">
{([0, 2, 1, 3] as const).map((s) => (
<button key={s} role="radio" aria-checked={status === s} onClick={() => onStatus(s)} className={`rounded-full border px-3 py-1 text-[12px] font-semibold transition-colors duration-150 ${status === s ? 'border-ink bg-ink text-white' : 'border-line bg-panel text-ink hover:border-ink-soft'}`}>
{s === 0 ? '전체' : STATUS[s].label} <span className={status === s ? 'text-white/70' : 'text-muted'}>{counts[s]}</span>
</button>
))}
</div>
{error && (
<div role="alert" className="rounded-xl border border-bad/30 bg-bad-soft px-5 py-4 text-[14px] text-bad">
{target.label} 목록을 받지 못했어요: {error instanceof Error ? error.message : String(error)}
</div>
)}
{isLoading && (
<div className="flex flex-col gap-3" aria-busy="true">
{[0, 1].map((i) => (
<div key={i} className="h-44 animate-pulse rounded-2xl bg-rail" />
))}
</div>
)}
{data && shown.length === 0 && <p className="rounded-2xl border border-dashed border-line bg-panel px-5 py-10 text-center text-[14px] text-muted">{status ? `${STATUS[status].label} 카드가 없어요.` : `${target.label}에 저장한 카드가 아직 없어요. 인스타 카드 탭에서 만들어 올려 보세요.`}</p>}
<ul className="m-0 flex list-none flex-col gap-3 p-0">
{shown.map((c) => {
const st = STATUS[c.status]
const mine = note?.id === c.card_id ? note : null
return (
<li key={c.card_id} className="grid gap-4 rounded-2xl border border-line bg-panel p-4 md:grid-cols-[minmax(0,1fr)_176px]">
<div className="flex min-w-0 flex-col gap-3">
<div className="flex flex-wrap items-center gap-x-2.5 gap-y-1">
<span className={`rounded-full px-2 py-0.5 text-[12px] font-bold ${st.tone}`}>{st.label}</span>
<b className="text-[15px]">{c.title}</b>
<span className="text-[12px] text-muted">
{TEMPLATE[c.template] ?? c.template}
{c.topic ? ` · ${c.topic}` : ''} · {c.image_urls.length}장 · 카드 {c.card_id}
</span>
</div>
<ol className="m-0 flex list-none gap-2 overflow-x-auto p-0.5">
{c.image_urls.map((u, i) => (
<li key={u} className="shrink-0">
<a href={`${target.api}${u}`} download={`card-${c.card_id}-${i + 1}.jpg`} target="_blank" rel="noreferrer" title={`${i + 1}장 내려받기`} className="block overflow-hidden rounded-lg outline-offset-2 transition-shadow duration-150 hover:shadow-[0_6px_18px_#28304a22] hover:outline-2 hover:outline-ink">
<img src={`${target.api}${u}`} alt={`${c.title} ${i + 1}장`} loading="lazy" className={`object-cover ${i === 0 ? 'h-[200px] w-[160px]' : 'h-[200px] w-[160px] opacity-90'}`} />
</a>
</li>
))}
</ol>
<dl className="grid grid-cols-[64px_1fr] gap-x-3 gap-y-0.5 text-[12px]">
<dt className="text-muted">만든 때</dt>
<dd className="m-0">{when(c.created_at)}</dd>
{c.published_at && (
<>
<dt className="text-muted">올린 때</dt>
<dd className="m-0">
{when(c.published_at)} · 포스트 {c.post_id} ·{' '}
<a href={target.site} target="_blank" rel="noreferrer" className="font-semibold text-rust underline-offset-2 hover:underline">
피드에서 보기
</a>
</dd>
</>
)}
{c.ig_media_id && (
<>
<dt className="text-muted">인스타</dt>
<dd className="m-0">올림 · {c.ig_media_id}</dd>
</>
)}
</dl>
{mine && (
<p role={mine.bad ? 'alert' : 'status'} className={`text-[12px] font-semibold ${mine.bad ? 'text-bad' : 'text-ink-soft'}`}>
{mine.bad ? `처리하지 못했어요: ${mine.text}` : mine.text}
</p>
)}
</div>
<div className="flex shrink-0 flex-col gap-2">
<button onClick={() => downloadAll(c)} className="rounded-lg border border-line px-3 py-2 text-[13px] font-bold text-ink hover:bg-rail">
JPEG {c.image_urls.length}장 내려받기
</button>
{c.status === 1 && (
<button onClick={() => act(c, 'publish')} disabled={busy === c.card_id} className="rounded-lg bg-ink px-3 py-2 text-[13px] font-bold text-white hover:opacity-90 disabled:opacity-40">
오늘 피드에 올리기
</button>
)}
{c.status === 2 && !c.ig_media_id && (
<button onClick={() => act(c, 'instagram')} disabled={busy === c.card_id} className="rounded-lg border border-ink px-3 py-2 text-[13px] font-bold text-ink hover:bg-rail disabled:opacity-40">
{busy === c.card_id ? '인스타에 올리는 중…' : '인스타에 올리기'}
</button>
)}
{c.status === 1 && (
<button onClick={() => act(c, 'reject')} disabled={busy === c.card_id} className="rounded-lg px-3 py-2 text-[13px] font-semibold text-muted hover:bg-rail disabled:opacity-40">
반려
</button>
)}
</div>
</li>
)
})}
</ul>
</div>
)
}