feat: main 병합 + 인스타 올리기 API(/v1/card/{id}/instagram), 관리자 올릴 곳 선택(로컬·킹서버), 만든 카드 화면

This commit is contained in:
minaChoi committed 2026-10-23 15:48:09 +09:00
commit 572b2a05c8
188 files changed
+16605 -741

No files matched your search

+108 -24
View File
@@ -11,6 +11,8 @@ import { CATEGORIES, categoryOf, questionOf } from '../cards/topics'
import { GAK_DECK, gakByCode } from '../cards/gaks'
import type { IndexSummary } from '../api/client'
import { neededImages } from '../cards/images'
import { cardAction, postCard, useTargets } from '../api/targets'
import type { CardSummary, Target } from '../api/targets'
import { DEFAULT_STYLE, OOTD_STYLES } from '../cards/ootd'
import type { Copy, Template } from '../cards/templates'
@@ -314,21 +316,14 @@ function Editor({ template, data, overrides, onEdit }: { template: Template; dat
<PostBox
disabled={busy !== null || !made}
onPost={async (publish) => {
buildBody={async (publish) => {
const images = []
for (const i of slides.map((_, k) => k)) {
const node = refs.current[i]?.firstElementChild as HTMLElement | null
if (node) images.push(await toJpeg(node))
}
const { title, caption } = template.post(data, copy)
const res = await fetch('/api/post', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ template: template.id, topic: copy.topic ?? null, title, caption, texts: copy, images, publish }),
})
const body = await res.json()
if (!res.ok || body.result?.success === false) throw new Error(body.error ?? body.result?.desc ?? `HTTP ${res.status}`)
return body as { card_id: number; status: number; post_id?: number }
return { template: template.id, topic: copy.topic ?? null, title, caption, texts: copy, images, publish }
}}
/>
<CommandBox command={command} />
@@ -662,37 +657,126 @@ function HowBox({ template }: { template: Template }) {
)
}
/** 날씨각 피드에 올리기: 바로 게시하거나, 승인 대기로 저장(나중에 Teams 승인으로 게시) */
function PostBox({ disabled, onPost }: { disabled: boolean; onPost: (publish: boolean) => Promise<{ card_id: number; post_id?: number }> }) {
const [state, setState] = useState<{ busy?: boolean; done?: string; error?: string }>({})
type Posted = Record<string, { busy?: boolean; card?: CardSummary; error?: string; ig?: string; igBusy?: boolean; igError?: string }>
/** 날씨각 피드에 올리기: 올릴 곳(로컬·킹서버)을 골라 바로 게시하거나 승인 대기로 저장. 올린 뒤 인스타(@nalssigak)에도 */
function PostBox({ disabled, buildBody }: { disabled: boolean; buildBody: (publish: boolean) => Promise<unknown> }) {
const { data: targets = [] } = useTargets()
const [picked, setPicked] = useState<Target['id'][] | null>(null)
const chosen = picked ?? targets.map((t) => t.id)
const [busy, setBusy] = useState(false)
const [posted, setPosted] = useState<Posted>({})
const [error, setError] = useState('')
const run = async (publish: boolean) => {
setState({ busy: true })
setBusy(true)
setError('')
try {
const r = await onPost(publish)
setState({ done: publish ? `날씨각 피드에 올렸어요 (카드 ${r.card_id}, 포스트 ${r.post_id}). 오늘 피드 날씨 바로 아래에 보여요.` : `승인 대기로 저장했어요 (카드 ${r.card_id}).` })
const body = await buildBody(publish)
await Promise.all(
chosen.map(async (id) => {
setPosted((p) => ({ ...p, [id]: { busy: true } }))
try {
const card = await postCard(id, body)
setPosted((p) => ({ ...p, [id]: { card } }))
} catch (e) {
setPosted((p) => ({ ...p, [id]: { error: e instanceof Error ? e.message : String(e) } }))
}
}),
)
} catch (e) {
console.error(e)
setState({ error: e instanceof Error ? e.message : String(e) })
setError(`이미지를 만들지 못했어요: ${e instanceof Error ? e.message : String(e)}`)
} finally {
setBusy(false)
}
}
// 인스타는 이미지가 공개 주소여야 해서 킹서버에 올린 카드로만 올린다
const igTarget = targets.find((t) => t.id === 'king') ?? targets[0]
const igCard = igTarget ? posted[igTarget.id]?.card : undefined
const toInstagram = async () => {
if (!igTarget || !igCard) return
setPosted((p) => ({ ...p, [igTarget.id]: { ...p[igTarget.id], igBusy: true, igError: undefined } }))
try {
const r = await cardAction(igTarget.id, igCard.card_id, 'instagram')
setPosted((p) => ({ ...p, [igTarget.id]: { ...p[igTarget.id], igBusy: false, ig: r.ig_media_id } }))
} catch (e) {
setPosted((p) => ({ ...p, [igTarget.id]: { ...p[igTarget.id], igBusy: false, igError: e instanceof Error ? e.message : String(e) } }))
}
}
const ig = igTarget ? posted[igTarget.id] : undefined
return (
<section className="flex flex-col gap-2 border-t border-line pt-5">
<section className="flex flex-col gap-3 border-t border-line pt-5">
<h2 className="text-[15px] font-bold">날씨각에 올리기</h2>
<p className="text-[12px] leading-relaxed text-muted">지금 카드를 이미지로 만들어 오늘 전국 피드에 올려요. 내일 03시에 피드에서 빠져요.</p>
{targets.length === 0 ? (
<p className="text-[12px] text-muted">올릴 곳이 없어요. 관리자 서버에 ADMIN_API_KEY(로컬)·KING_ADMIN_API_KEY(킹서버)를 환경변수로 주고 다시 켜 주세요.</p>
) : (
<div className="flex flex-wrap items-center gap-x-4 gap-y-1 text-[13px]">
<span className="text-muted">올릴 곳</span>
{targets.map((t) => (
<label key={t.id} className="flex items-center gap-1.5 font-semibold">
<input type="checkbox" id={`target-${t.id}`} checked={chosen.includes(t.id)} onChange={(e) => setPicked(e.target.checked ? [...chosen, t.id] : chosen.filter((x) => x !== t.id))} className="accent-ink" />
{t.label}
</label>
))}
</div>
)}
<p className="text-[12px] leading-relaxed text-muted">지금 카드를 이미지로 만들어 고른 곳의 오늘 전국 피드에 올려요. 내일 03시에 피드에서 빠져요.</p>
<div className="flex gap-2">
<button onClick={() => run(true)} disabled={disabled || state.busy} className="flex-1 rounded-xl bg-ink px-4 py-2.5 text-[14px] font-bold text-white hover:opacity-90 disabled:opacity-40">
{state.busy ? '올리는 중…' : '지금 올리기'}
<button onClick={() => run(true)} disabled={disabled || busy || chosen.length === 0} className="flex-1 rounded-xl bg-ink px-4 py-2.5 text-[14px] font-bold text-white hover:opacity-90 disabled:opacity-40">
{busy ? '올리는 중…' : '지금 올리기'}
</button>
<button onClick={() => run(false)} disabled={disabled || state.busy} className="rounded-xl border border-ink px-3 py-2.5 text-[13px] font-bold text-ink hover:bg-rail disabled:opacity-40">
<button onClick={() => run(false)} disabled={disabled || busy || chosen.length === 0} className="rounded-xl border border-ink px-3 py-2.5 text-[13px] font-bold text-ink hover:bg-rail disabled:opacity-40">
승인 대기로 저장
</button>
</div>
{state.done && <p className="text-[12px] font-semibold text-ink-soft">{state.done}</p>}
{state.error && (
{error && (
<p role="alert" className="text-[12px] text-bad">
올리지 못했어요: {state.error}
{error}
</p>
)}
{Object.keys(posted).length > 0 && (
<ul className="m-0 flex list-none flex-col gap-1.5 p-0 text-[12px]">
{targets
.filter((t) => posted[t.id])
.map((t) => {
const r = posted[t.id]
return (
<li key={t.id} className="flex flex-wrap items-center gap-x-2 rounded-lg bg-page px-3 py-2">
<b>{t.label}</b>
{r.busy && <span className="text-muted">올리는 중…</span>}
{r.card && (
<>
<span className="text-ink-soft">
{r.card.status === 2 ? `올렸어요 · 카드 ${r.card.card_id} · 포스트 ${r.card.post_id}` : `승인 대기로 저장 · 카드 ${r.card.card_id}`}
</span>
{r.card.status === 2 && (
<a href={t.site} target="_blank" rel="noreferrer" className="font-semibold text-rust underline-offset-2 hover:underline">
피드에서 보기
</a>
)}
</>
)}
{r.error && <span className="text-bad">올리지 못했어요: {r.error}</span>}
</li>
)
})}
</ul>
)}
{igTarget && igCard?.status === 2 && (
<div className="flex flex-col gap-1.5 border-t border-line pt-3">
<button onClick={toInstagram} disabled={ig?.igBusy || !!ig?.ig} className="rounded-xl border border-ink px-4 py-2.5 text-[14px] font-bold text-ink hover:bg-rail disabled:opacity-40">
{ig?.ig ? `인스타에 올렸어요 (${ig.ig})` : ig?.igBusy ? '인스타에 올리는 중… (1분쯤)' : `인스타(@nalssigak)에도 올리기 · ${igTarget.label} 이미지로`}
</button>
{ig?.igError && (
<p role="alert" className="text-[12px] text-bad">
인스타에 올리지 못했어요: {ig.igError}
</p>
)}
</div>
)}
</section>
)
}
+154 -52
View File
@@ -1,99 +1,201 @@
import { useQuery, useQueryClient } from '@tanstack/react-query'
import { useState } from 'react'
import { API_BASE_URL } from '../api/setup'
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[] }
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<Card['status'], [string, string]> = { 1: ['승인 대기', 'bg-warn-soft text-warn'], 2: ['올림', 'bg-rust-soft text-rust'], 3: ['반려', 'bg-rail text-muted'] }
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 = ['일', '월', '화', '수', '목', '금', '토']
const when = (iso: string) => new Date(iso).toLocaleString('ko-KR', { month: 'numeric', day: 'numeric', hour: '2-digit', minute: '2-digit' })
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')}`
}
/** 만든 카드가 쌓이는 곳. 날씨각 서버(card_set·card_image)에 저장된 것을 보여 주고, 다시 내려받거나 올린다 */
/** 발행된 포스트가 쌓이는 곳. 올릴 곳(로컬·킹서버)마다 날씨각 서버에 저장된 카드를 보여 주고, 다시 내려받거나 올리거나 인스타에 보낸다 */
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'],
queryKey: ['cards', target.id],
queryFn: async () => {
const r = await fetch('/api/cards')
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 act = async (id: number, what: 'publish' | 'reject') => {
setBusy(id)
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 fetch(`/api/cards/${id}/${what}`, { method: 'POST' })
if (!r.ok) throw new Error((await r.json()).error)
await qc.invalidateQueries({ queryKey: ['cards'] })
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) {
console.error(e)
window.alert(`처리하지 못했어요: ${e instanceof Error ? e.message : String(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="mx-auto flex max-w-[1440px] flex-col gap-5 px-4 py-5 sm:px-6">
<header className="flex flex-col gap-0.5">
<h1 className="text-[20px] font-bold tracking-[-0.02em]">만든 카드</h1>
<p className="text-[13px] text-muted">'지금 올리기'나 '승인 대기로 저장'을 누른 카드가 날씨각 서버에 쌓여요. 장마다 JPEG로 다시 내려받을 수 있어요.</p>
</header>
<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">
목록을 받지 못했어요: {String(error instanceof Error ? error.message : error)}
{target.label} 목록을 받지 못했어요: {error instanceof Error ? error.message : String(error)}
</div>
)}
{isLoading && <div className="h-40 animate-pulse rounded-2xl bg-rail" aria-busy="true" />}
{data?.length === 0 && <p className="rounded-2xl border border-dashed border-line bg-panel px-5 py-10 text-center text-[14px] text-muted">아직 저장한 카드가 없어요.</p>}
{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">
{data?.map((c) => {
const [label, tone] = STATUS[c.status]
{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)_auto]">
<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-2 text-[13px]">
<span className={`rounded-full px-2 py-0.5 text-[12px] font-bold ${tone}`}>{label}</span>
<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-muted">
<span className="text-[12px] text-muted">
{TEMPLATE[c.template] ?? c.template}
{c.topic ? ` · ${c.topic}` : ''} · 카드 {c.card_id}
{c.post_id ? ` · 포스트 ${c.post_id}` : ''}
{c.topic ? ` · ${c.topic}` : ''} · {c.image_urls.length}장 · 카드 {c.card_id}
</span>
<span className="text-muted">만든 때 {when(c.created_at)}{c.published_at ? ` · 올린 때 ${when(c.published_at)}` : ''}</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={`${API_BASE_URL}${u}`} download={`card-${c.card_id}-${i + 1}.jpg`} target="_blank" rel="noreferrer" title={`${i + 1}장 내려받기`} className="block overflow-hidden rounded-md outline-offset-2 hover:outline-2 hover:outline-ink">
<img src={`${API_BASE_URL}${u}`} alt={`${c.title} ${i + 1}장`} loading="lazy" className="h-[135px] w-[108px] object-cover" />
<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 md:w-40">
<a
href={`${API_BASE_URL}${c.image_urls[0] ?? ''}`}
download={`card-${c.card_id}-1.jpg`}
target="_blank"
rel="noreferrer"
className="rounded-lg border border-line px-3 py-2 text-center text-[13px] font-bold text-ink hover:bg-rail"
>
이미지 열기
</a>
<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.card_id, '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>
<button onClick={() => act(c.card_id, '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>
</>
<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>