import { useCallback, useEffect, useMemo, useState } from 'react' import { api } from '../api' import './BookEdit.css' import { WxBadge, WxEmpty, WxHead, WxTabs, WxToast, copyText, fmtTime, fmtYuan, shortId, } from '../components/wxUi' type GoodsType = 'virtual' | 'physical' type Product = { id: string title: string desc: string cover: string coverEmoji: string groupName: string goodsType: GoodsType priceFen: number stock: number wxProductId: string offerKey?: string sort: number enabled: boolean } type ProductOffer = { key: string label: string name: string product_id: string price_fen: number price_yuan: string free: boolean image: string remark?: string } type ShopOrder = { id: string outTradeNo: string openid: string productId: string productTitle: string goodsType: GoodsType qty: number amountFen: number status: string email: string address?: Record carmis?: string[] trackingNo?: string expressCompany?: string createdAt: number } type Tab = 'products' | 'carmis' | 'orders' const emptyProduct: Product = { id: '', title: '', desc: '', cover: '', coverEmoji: '🛒', groupName: '全部', goodsType: 'virtual', priceFen: 18800, stock: 0, wxProductId: '', offerKey: '', sort: 100, enabled: true, } export default function Shop() { const [tab, setTab] = useState('products') const [products, setProducts] = useState([]) const [orders, setOrders] = useState([]) const [offers, setOffers] = useState([]) const [draft, setDraft] = useState(emptyProduct) const [carmiProductId, setCarmiProductId] = useState('') const [carmiText, setCarmiText] = useState('') const [shipId, setShipId] = useState('') const [trackingNo, setTrackingNo] = useState('') const [expressCompany, setExpressCompany] = useState('') const [err, setErr] = useState('') const [msg, setMsg] = useState('') const [busy, setBusy] = useState(false) const [q, setQ] = useState('') const [orderFilter, setOrderFilter] = useState<'all' | 'paid' | 'ship'>('all') const load = useCallback(async () => { setErr('') const [p, o, offerRes] = await Promise.all([ api<{ items: Product[] }>('/api/admin/shop/products'), api<{ items: ShopOrder[] }>('/api/admin/shop/orders'), api<{ items: ProductOffer[] }>('/api/admin/product-offers'), ]) setProducts(p.items || []) setOrders(o.items || []) setOffers((offerRes.items || []).filter((x) => !x.free)) if (!carmiProductId && p.items?.length) { const v = p.items.find((x) => x.goodsType === 'virtual') if (v) setCarmiProductId(v.id) } }, [carmiProductId]) useEffect(() => { load().catch((e) => setErr(e.message || '加载失败')) }, [load]) const virtualProducts = useMemo( () => products.filter((p) => p.goodsType === 'virtual'), [products], ) const productStats = useMemo(() => { const on = products.filter((p) => p.enabled).length const low = products.filter((p) => p.goodsType === 'virtual' && p.stock <= 3).length return { total: products.length, on, low, orders: orders.length } }, [products, orders]) const filteredProducts = useMemo(() => { const needle = q.trim().toLowerCase() if (!needle) return products return products.filter( (p) => p.id.toLowerCase().includes(needle) || p.title.toLowerCase().includes(needle) || (p.wxProductId || '').toLowerCase().includes(needle) || (p.groupName || '').toLowerCase().includes(needle), ) }, [products, q]) const filteredOrders = useMemo(() => { return orders.filter((o) => { if (orderFilter === 'paid' && o.status !== 'paid') return false if (orderFilter === 'ship' && !(o.goodsType === 'physical' && o.status === 'paid' && !o.trackingNo)) return false return true }) }, [orders, orderFilter]) const activeOfferKey = useMemo(() => { if (draft.offerKey) return draft.offerKey return ( offers.find((o) => o.product_id === draft.wxProductId || o.key === draft.wxProductId)?.key || '' ) }, [draft.offerKey, draft.wxProductId, offers]) const carmiLines = useMemo( () => carmiText .split(/\r?\n/) .map((s) => s.trim()) .filter(Boolean), [carmiText], ) function pickOffer(o: ProductOffer) { setDraft((d) => ({ ...d, offerKey: o.key, wxProductId: o.product_id, priceFen: o.price_fen, })) } async function saveProduct() { if (!draft.title.trim()) { setErr('请填写商品标题') return } setBusy(true) setMsg('') setErr('') try { await api('/api/admin/shop/products', { method: 'POST', body: JSON.stringify(draft), }) setMsg( draft.wxProductId ? `已保存 · 道具 ${draft.wxProductId} · ${fmtYuan(draft.priceFen)}` : '商品已保存(未选道具)', ) setDraft(emptyProduct) await load() } catch (e) { setErr((e as Error).message || '保存失败') } finally { setBusy(false) } } async function removeProduct(id: string) { if (!confirm(`删除商品 ${id}?此操作不可撤销`)) return setBusy(true) try { await api(`/api/admin/shop/products/${id}`, { method: 'DELETE' }) setMsg(`已删除 ${id}`) if (draft.id === id) setDraft(emptyProduct) await load() } catch (e) { setErr((e as Error).message || '删除失败') } finally { setBusy(false) } } async function importCarmis() { if (!carmiProductId || !carmiLines.length) { setErr('请选择商品并粘贴卡密(一行一个)') return } setBusy(true) setErr('') setMsg('') try { const res = await api<{ imported: number; stock: number }>('/api/admin/shop/carmis', { method: 'POST', body: JSON.stringify({ productId: carmiProductId, codes: carmiLines }), }) setMsg(`已导入 ${res.imported} 条,当前库存 ${res.stock}`) setCarmiText('') await load() } catch (e) { setErr((e as Error).message || '导入失败') } finally { setBusy(false) } } async function markShopStatus(orderId: string, status: string) { if (!confirm('仅改本地订单状态,不直连微信退款。继续?')) return setBusy(true) setErr('') try { await api(`/api/admin/shop/orders/${orderId}/status`, { method: 'POST', body: JSON.stringify({ status }), }) setMsg('订单状态已更新') await load() } catch (e) { setErr((e as Error).message || '更新失败') } finally { setBusy(false) } } async function ship(orderId: string) { if (!trackingNo.trim()) { setErr('请填写运单号') return } setBusy(true) setErr('') setMsg('') try { await api(`/api/admin/shop/orders/${orderId}/ship`, { method: 'POST', body: JSON.stringify({ trackingNo, expressCompany, shipNote: '' }), }) setMsg('已标记发货') setShipId('') setTrackingNo('') setExpressCompany('') await load() } catch (e) { setErr((e as Error).message || '发货失败') } finally { setBusy(false) } } return (
{err ? ( setErr('')}> {err} ) : null} {msg ? ( setMsg('')}> {msg} ) : null}
商品
{productStats.total}
上架中
{productStats.on}
低库存(≤3)
{productStats.low}
商城订单
{productStats.orders}
{tab === 'products' ? ( <>

{draft.id ? `编辑 ${draft.id}` : '新建 / 编辑商品'}

先点选付费方案(道具 + 价格),再填标题与类型后保存。

{offers.map((o) => { const active = o.key === activeOfferKey const img = o.image ? `/${o.image.replace(/^\/+/, '')}` : '' return ( ) })}
道具 {draft.wxProductId || '—'} · {fmtYuan(draft.priceFen)} ·{' '} {draft.offerKey || '未选方案'}
setQ(e.target.value)} />
{filteredProducts.length ? ( {filteredProducts.map((p) => ( ))}
商品 类型 道具 价格 库存 状态 操作
{p.coverEmoji} {p.title}
{p.id}
{p.goodsType === 'virtual' ? '虚拟' : '实体'} {p.wxProductId || '—'} {fmtYuan(p.priceFen)} {p.stock} {p.enabled ? '上架' : '下架'}
) : ( )}
) : null} {tab === 'carmis' ? (

导入卡密

一行一个;导入后自动更新虚拟商品库存。