nomadro/apps/admin/src/pages/Shop.tsx
Eric 4389ebe6cb Ship WeChat audit release 2026-11-02: realtime config, audit vip-ebook shell, admin ops.
Document test9 tag 2026-11-02 for upload; POST config pull + WS, fixed dark home, no debug bar.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-02 16:12:57 +08:00

738 lines
25 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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<string, string>
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<Tab>('products')
const [products, setProducts] = useState<Product[]>([])
const [orders, setOrders] = useState<ShopOrder[]>([])
const [offers, setOffers] = useState<ProductOffer[]>([])
const [draft, setDraft] = useState<Product>(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 (
<div className="wx-page">
<WxHead
eyebrow="设备商城"
title="电商"
desc="付费方案与 VIP / 小册同源道具。商品、卡密、实体发货分栏管理;每商品单独选道具。"
>
<button
type="button"
className="wx-btn wx-btn-ghost"
disabled={busy}
onClick={() => load().catch((e) => setErr(e.message || '加载失败'))}
>
刷新
</button>
</WxHead>
{err ? (
<WxToast kind="err" onClose={() => setErr('')}>
{err}
</WxToast>
) : null}
{msg ? (
<WxToast kind="ok" onClose={() => setMsg('')}>
{msg}
</WxToast>
) : null}
<div className="wx-stats" style={{ gridTemplateColumns: 'repeat(4, minmax(0, 1fr))' }}>
<div className="wx-stat">
<div className="wx-stat-label">商品</div>
<div className="wx-stat-val">{productStats.total}</div>
</div>
<div className="wx-stat">
<div className="wx-stat-label">上架中</div>
<div className="wx-stat-val">{productStats.on}</div>
</div>
<div className="wx-stat wx-stat--warn">
<div className="wx-stat-label">低库存(≤3)</div>
<div className="wx-stat-val">{productStats.low}</div>
</div>
<div className="wx-stat">
<div className="wx-stat-label">商城订单</div>
<div className="wx-stat-val">{productStats.orders}</div>
</div>
</div>
<WxTabs
value={tab}
onChange={setTab}
items={[
{ key: 'products', label: '商品', count: products.length },
{ key: 'carmis', label: '卡密', count: virtualProducts.length },
{ key: 'orders', label: '订单', count: orders.length },
]}
/>
{tab === 'products' ? (
<>
<section className="wx-panel monetize-panel">
<div className="wx-panel-head">
<div>
<h2>{draft.id ? `编辑 ${draft.id}` : '新建 / 编辑商品'}</h2>
<p>先点选付费方案(道具 + 价格),再填标题与类型后保存。</p>
</div>
</div>
<div className="offer-grid offer-grid-6" style={{ marginBottom: 16 }}>
{offers.map((o) => {
const active = o.key === activeOfferKey
const img = o.image ? `/${o.image.replace(/^\/+/, '')}` : ''
return (
<button
key={o.key}
type="button"
className={`offer-card ${active ? 'active' : ''}`}
disabled={busy}
onClick={() => pickOffer(o)}
>
{img ? (
<img className="offer-img" src={img} alt={o.label} />
) : (
<div className="offer-free-badge">{o.product_id.slice(0, 6)}</div>
)}
<strong>{o.label}</strong>
<span className="offer-id">{o.product_id}</span>
<em>{o.price_yuan}</em>
{o.remark ? <i className="offer-remark">{o.remark}</i> : null}
{active ? <b className="offer-on">已选</b> : null}
</button>
)
})}
</div>
<div className="wx-form-grid">
<label className="wx-field">
ID(空则自动)
<input
value={draft.id}
onChange={(e) => setDraft({ ...draft, id: e.target.value })}
placeholder="yt-device"
/>
</label>
<label className="wx-field">
标题
<input
value={draft.title}
onChange={(e) => setDraft({ ...draft, title: e.target.value })}
/>
</label>
<label className="wx-field">
分组
<input
value={draft.groupName}
onChange={(e) => setDraft({ ...draft, groupName: e.target.value })}
/>
</label>
<label className="wx-field">
类型
<select
value={draft.goodsType}
onChange={(e) =>
setDraft({ ...draft, goodsType: e.target.value as GoodsType })
}
>
<option value="virtual">虚拟发卡</option>
<option value="physical">实体发货</option>
</select>
</label>
<label className="wx-field">
库存
<input
type="number"
value={draft.stock}
onChange={(e) => setDraft({ ...draft, stock: Number(e.target.value) || 0 })}
/>
</label>
<label className="wx-field">
Emoji
<input
value={draft.coverEmoji}
onChange={(e) => setDraft({ ...draft, coverEmoji: e.target.value })}
/>
</label>
<label className="wx-field span-2">
描述
<input
value={draft.desc}
onChange={(e) => setDraft({ ...draft, desc: e.target.value })}
/>
</label>
</div>
<div className="wx-sticky-bar">
<div className="wx-muted">
道具 <code>{draft.wxProductId || '—'}</code> · {fmtYuan(draft.priceFen)} ·{' '}
{draft.offerKey || '未选方案'}
</div>
<div className="wx-row-actions">
<label style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 13 }}>
<input
type="checkbox"
checked={draft.enabled}
onChange={(e) => setDraft({ ...draft, enabled: e.target.checked })}
/>
上架
</label>
<button type="button" className="wx-btn-sm" onClick={() => setDraft(emptyProduct)}>
清空
</button>
<button type="button" className="wx-btn" disabled={busy} onClick={() => void saveProduct()}>
{busy ? '保存中…' : '保存商品'}
</button>
</div>
</div>
</section>
<div className="wx-toolbar">
<input
type="search"
value={q}
placeholder="筛选商品 ID / 标题 / 道具"
onChange={(e) => setQ(e.target.value)}
/>
</div>
<div className="wx-table-wrap">
{filteredProducts.length ? (
<table className="wx-table">
<thead>
<tr>
<th>商品</th>
<th>类型</th>
<th>道具</th>
<th>价格</th>
<th>库存</th>
<th>状态</th>
<th>操作</th>
</tr>
</thead>
<tbody>
{filteredProducts.map((p) => (
<tr key={p.id}>
<td>
<strong>
{p.coverEmoji} {p.title}
</strong>
<div className="wx-mono" style={{ marginTop: 4 }}>
{p.id}
</div>
</td>
<td>{p.goodsType === 'virtual' ? '虚拟' : '实体'}</td>
<td className="wx-mono">{p.wxProductId || '—'}</td>
<td>{fmtYuan(p.priceFen)}</td>
<td>
<WxBadge tone={p.stock <= 3 && p.goodsType === 'virtual' ? 'warn' : 'muted'}>
{p.stock}
</WxBadge>
</td>
<td>
<WxBadge tone={p.enabled ? 'ok' : 'muted'}>
{p.enabled ? '上架' : '下架'}
</WxBadge>
</td>
<td>
<div className="wx-row-actions">
<button
type="button"
className="wx-btn-sm primary"
onClick={() => {
setDraft(p)
window.scrollTo({ top: 0, behavior: 'smooth' })
}}
>
编辑
</button>
<button
type="button"
className="wx-btn-sm danger"
onClick={() => void removeProduct(p.id)}
>
删
</button>
</div>
</td>
</tr>
))}
</tbody>
</table>
) : (
<WxEmpty title="暂无商品" hint="上方选择付费方案并保存后出现" />
)}
</div>
</>
) : null}
{tab === 'carmis' ? (
<section className="wx-panel">
<div className="wx-panel-head">
<div>
<h2>导入卡密</h2>
<p>一行一个;导入后自动更新虚拟商品库存。</p>
</div>
</div>
<div className="wx-form-grid">
<label className="wx-field span-2">
虚拟商品
<select value={carmiProductId} onChange={(e) => setCarmiProductId(e.target.value)}>
<option value="">选择…</option>
{virtualProducts.map((p) => (
<option key={p.id} value={p.id}>
{p.title}(库存 {p.stock} · {p.wxProductId || '无道具'})
</option>
))}
</select>
</label>
<label className="wx-field span-2">
卡密列表(已识别 {carmiLines.length} 行)
<textarea
rows={12}
value={carmiText}
onChange={(e) => setCarmiText(e.target.value)}
placeholder={'CARD-001\nCARD-002'}
/>
</label>
</div>
<div className="wx-sticky-bar">
<span className="wx-muted">重复行会按服务端规则去重</span>
<button type="button" className="wx-btn" disabled={busy} onClick={() => void importCarmis()}>
{busy ? '导入中…' : `导入 ${carmiLines.length || ''}`.trim()}
</button>
</div>
</section>
) : null}
{tab === 'orders' ? (
<>
<div className="wx-chip-row">
{(
[
['all', '全部'],
['paid', '已支付'],
['ship', '待发货(实体)'],
] as const
).map(([k, label]) => (
<button
key={k}
type="button"
className={`wx-chip${orderFilter === k ? ' is-on' : ''}`}
onClick={() => setOrderFilter(k)}
>
{label}
</button>
))}
</div>
<div className="wx-table-wrap">
{filteredOrders.length ? (
<table className="wx-table">
<thead>
<tr>
<th>订单</th>
<th>商品</th>
<th>金额</th>
<th>状态</th>
<th>用户 / 履约</th>
<th>时间</th>
<th>发货</th>
</tr>
</thead>
<tbody>
{filteredOrders.map((o) => (
<tr key={o.id}>
<td>
<div className="wx-mono">{o.id}</div>
<button
type="button"
className="wx-btn-sm"
style={{ marginTop: 4 }}
onClick={() =>
void copyText(o.outTradeNo).then((ok) =>
setMsg(ok ? '已复制业务单号' : '复制失败'),
)
}
>
{shortId(o.outTradeNo, 10)}
</button>
</td>
<td>
{o.productTitle} ×{o.qty}
<div style={{ marginTop: 4 }}>
<WxBadge tone="muted">
{o.goodsType === 'virtual' ? '虚拟' : '实体'}
</WxBadge>
</div>
</td>
<td>{fmtYuan(o.amountFen)}</td>
<td>
<WxBadge tone={o.status === 'paid' ? 'ok' : 'warn'}>{o.status}</WxBadge>
</td>
<td style={{ maxWidth: 260, fontSize: 12 }}>
<div className="wx-mono">{shortId(o.openid, 12)}</div>
{o.email ? <div>{o.email}</div> : null}
{o.address?.userName ? (
<div>
{o.address.userName} {o.address.telNumber}
<br />
{o.address.provinceName}
{o.address.cityName}
{o.address.countyName}
{o.address.detailInfo}
</div>
) : null}
{o.carmis?.length ? (
<div className="wx-detail">卡密: {o.carmis.join(', ')}</div>
) : null}
{o.trackingNo ? (
<div>
物流 {o.expressCompany} {o.trackingNo}
</div>
) : null}
</td>
<td>{fmtTime(o.createdAt)}</td>
<td>
{o.goodsType === 'physical' && o.status === 'paid' && !o.trackingNo ? (
shipId === o.id ? (
<div style={{ display: 'grid', gap: 6 }}>
<input
placeholder="快递公司"
value={expressCompany}
onChange={(e) => setExpressCompany(e.target.value)}
/>
<input
placeholder="运单号"
value={trackingNo}
onChange={(e) => setTrackingNo(e.target.value)}
/>
<div className="wx-row-actions">
<button
type="button"
className="wx-btn-sm primary"
disabled={busy}
onClick={() => void ship(o.id)}
>
确认
</button>
<button
type="button"
className="wx-btn-sm"
onClick={() => setShipId('')}
>
取消
</button>
</div>
</div>
) : (
<button
type="button"
className="wx-btn-sm primary"
onClick={() => setShipId(o.id)}
>
发货
</button>
)
) : (
<div className="wx-row-actions">
{o.status !== 'refunded' && o.status !== 'cancelled' ? (
<button
type="button"
className="wx-btn-sm danger"
disabled={busy}
onClick={() => void markShopStatus(o.id, 'refunded')}
>
标退款
</button>
) : (
<span className="wx-muted">{o.status}</span>
)}
</div>
)}
</td>
</tr>
))}
</tbody>
</table>
) : (
<WxEmpty title="暂无订单" />
)}
</div>
</>
) : null}
</div>
)
}