// ===== redbook_nrgc · workflows.jsx build v=20260823-batch-fix-v6 ===== console.info('[redbook_nrgc] workflows.jsx build v=20260823-batch-fix-v6 · 批量改类目/赛道 + 分页修复版'); // 微趋势图:用于商品监控表「近7日增长」单元格 // 视觉:纯折线 + 底部面积渐变(area gradient);无坐标轴/网格/标签; // 自适应 Y(dataMin→dataMax);按趋势着色 // 交互:hover 弹出 原生气泡(MM-DD: value);点击冒泡到 <tr> 打开抽屉 // 注:与 app.jsx 内的同名组件逻辑一致,单独在此注入以避开脚本加载顺序耦合 function WeekSparkline({points=[]}){ // 取所有有限数值;保留原顺序(旧→新) const values=points .map(x=>Number(x.sales_number)) .filter(v=>Number.isFinite(v)); // 0 点:占位(保持表格行高稳定) if(values.length<1){ return ( <div className="week-sparkline week-sparkline-placeholder" role="img" aria-label="近7日销量趋势待积累" > <span>待积累</span> </div> ); } const width=100; const height=35; const paddingX=2; const paddingY=4; // 单点:绿色圆点 + 数值(无折线,无横轴) if(values.length===1){ const value=values[0]; const cx=width/2; const cy=height/2; return ( <svg className="week-sparkline week-sparkline-single up" viewBox={`0 0 ${width} ${height}`} role="img" aria-label={`仅今日采集:${fmtNum(value)}`} > <circle cx={cx} cy={cy} r="3.4" fill="currentColor"/> <text x={cx+7} y={cy+3.4} fontSize="9" fontWeight="700" fill="currentColor" > {fmtNum(value)} </text> </svg> ); } // 多点:自适应 Y(不强制从 0 起),约 5% 上下内边距 const minRaw=Math.min(...values); const maxRaw=Math.max(...values); const span=Math.max(maxRaw-minRaw,1); const unit= span>=1000 ? 50 : span>=100 ? 10 : span>=20 ? 2 : 1; const pad=Math.max(span*0.05,unit*0.5); const yMin=Math.max(0,Math.floor((minRaw-pad)/unit)*unit); const yMax=Math.ceil((maxRaw+pad)/unit)*unit; const yRange=Math.max(yMax-yMin,1); const plotW=width-paddingX*2; const plotH=height-paddingY*2; const xOf=i=>paddingX+(i*plotW)/(values.length-1); const yOf=v=>paddingY+((yMax-v)/yRange)*plotH; // 构造折线与每个点的 (x, y) const coords=values.map((v,i)=>[xOf(i),yOf(v)]); const linePath=coords .map(([px,py],i)=>`${i?'L':'M'} ${px.toFixed(1)} ${py.toFixed(1)}`) .join(' '); // 面积闭合路径:折线 + 末端拉到底边 + 起点拉到底边,回到起点 const baseY=height-paddingY; // 折线底部 y(与 yOf(yMin) 等价) const areaPath=`${linePath} L ${coords[coords.length-1][0].toFixed(1)} ${baseY} L ${coords[0][0].toFixed(1)} ${baseY} Z`; // 趋势方向:末点 >= 首点 →涨(up/绿);否则 → 跌(down/红) const rising=values[values.length-1]>=values[0]; const directionClass=rising?'up':'down'; const gradientId=rising?'spark-area-up':'spark-area-down'; // 给每个点叠加透明的 hover 命中区(更宽的透明 circle) return ( <svg className={`week-sparkline ${directionClass}`} viewBox={`0 0 ${width} ${height}`} role="img" aria-label={`近7日销量从 ${fmtNum(values[0])} 变化至 ${fmtNum(values[values.length-1])}`} > <defs> <linearGradient id={gradientId} x1="0" y1="0" x2="0" y2="1"> <stop offset="0%" stopColor="currentColor" stopOpacity="0.32"/> <stop offset="100%" stopColor="currentColor" stopOpacity="0"/> </linearGradient> </defs> <path className="week-sparkline-area" d={areaPath} fill={`url(#${gradientId})`}/> <path className="week-sparkline-line" d={linePath}/> {points.map((row,i)=>{ if(!Number.isFinite(Number(row.sales_number)))return null; const [px,py]=coords[i]; const dateShort=String(row.date||row.scraped_at||'').slice(5); // "MM-DD" return ( <g key={`${row.date}-${i}`}> <circle className="week-sparkline-hit" cx={px} cy={py} r="6" /> <circle className="week-sparkline-point" cx={px} cy={py} r="1.6" /> <title>{`${dateShort}: ${fmtNum(values[i])}`} ); })} ); } function Icon({name,size=16}){ const ref=useRef(null); useEffect(()=>{if(window.lucide&&ref.current)window.lucide.createIcons({nodes:[ref.current]})},[name]); return ; } function DataProgress({value,total=3}){ const safe=Math.max(0,Math.min(total,Number(value)||0)),percent=Math.round(safe/total*100); return
{percent}{safe}/{total} 项{safe===total?'资料完整':'待补资料'}
; } function optionListFromMap(map,color='#1769aa'){ return Object.entries(map||{}).map(([key,name])=>({key,name,color})); } function normalizeFilterList(value){ return Array.isArray(value)?value.filter(Boolean):(value?[value]:[]); } // 计算浮层位置:用 viewport 坐标 + position:fixed,避免被 overflow:hidden 的祖先裁切 function computePopoverStyle(anchorRect, opts={}){ if(!anchorRect)return {display:'none'}; const {width:popW=340,height:popH=260,offset=6,gap=8}=opts; const margin=gap; let top=anchorRect.bottom+offset; let left=anchorRect.left; // 视口下方空间不足时翻到上方 if(top+popH>window.innerHeight-margin){ const flipped=anchorRect.top-popH-offset; if(flipped>=margin)top=flipped; else top=Math.max(margin,window.innerHeight-popH-margin); } // 视口右侧溢出 → 左移;左侧溢出 → 右移 const maxLeft=window.innerWidth-popW-margin; if(left>maxLeft)left=maxLeft; if(leftwindow.innerHeight-margin){ const flipped=anchorRect.top-menuH-offset; if(flipped>=margin)top=flipped; else top=Math.max(margin,window.innerHeight-menuH-margin); } const maxLeft=window.innerWidth-menuW-margin; if(left>maxLeft)left=maxLeft; if(left0){ return `${aiScore}/10`; } const score=product?.system_opportunity_score ?? product?.opportunity_score; return `${fmtNum(score,'0')}分`; } function productDecisionSourceText(product){ if(product?.opportunity_source==='manual')return '人工判断'; if(product?.ai_report_status==='success'&&product?.ai_score!=null)return 'AI测品'; return '规则判断'; } function productDecisionMeta(product){ return `${productScoreLabel(product)} · ${productDecisionSourceText(product)}`; } function localizeAiReportHtml(value){ return String(value||'') .replace(/置信度:\s*(high|medium|low)<\/strong>/gi,(_,v)=>`判断把握:${aiConfidenceText(v)}`) .replace(/置信度:\s*(high|medium|low)/gi,(_,v)=>`判断把握:${aiConfidenceText(v)}`) .replace(/优先级:\s*(high|medium|low)<\/strong>/gi,(_,v)=>`优先级:${aiPriorityText(v)}`) .replace(/状态:?\s*(success|failed|not_configured|pending|running)<\/strong>/gi,(_,v)=>`生成状态:${aiStatusText(v)}`); } function ProductDecisionSelect({value,options=[],placeholder='未设置',clearLabel='清空',busy=false,onSave,onCreate,onDelete}){ const [expanded,setExpanded]=useState(false),[query,setQuery]=useState(''),[menuStyle,setMenuStyle]=useState(null); const ref=useRef(null);const triggerRef=useRef(null);const menuRef=useRef(null); const current=options.find(item=>item.key===value)||options.find(item=>item.name===value)||(value?{key:value,name:value,color:'#1769aa'}:null); const visible=options.filter(item=>!query.trim()||item.name.toLowerCase().includes(query.trim().toLowerCase())||item.key.toLowerCase().includes(query.trim().toLowerCase())); useEffect(()=>{ if(!expanded)return; function update(){const triggerEl=triggerRef.current;if(triggerEl)setMenuStyle(computeMenuStyle(triggerEl.getBoundingClientRect()))} function close(e){if(triggerRef.current?.contains(e.target))return;if(menuRef.current?.contains(e.target))return;setExpanded(false)} function escape(e){if(e.key==='Escape')setExpanded(false)} update(); window.addEventListener('scroll',update,true); window.addEventListener('resize',update); document.addEventListener('pointerdown',close); document.addEventListener('keydown',escape); return()=>{window.removeEventListener('scroll',update,true);window.removeEventListener('resize',update);document.removeEventListener('pointerdown',close);document.removeEventListener('keydown',escape)}; },[expanded]); async function choose(option){if(busy)return;await onSave(option);setExpanded(false)} async function create(){const name=query.trim();if(!name||busy)return;const option=await onCreate(name);if(option){await choose(option);setQuery('')}} function toggle(e){e.stopPropagation();const triggerEl=triggerRef.current;if(!triggerEl)return;setMenuStyle(computeMenuStyle(triggerEl.getBoundingClientRect()));setExpanded(value=>!value)} const menuNode=expanded&&menuStyle?ReactDOM.createPortal(
e.stopPropagation()} onClick={e=>e.stopPropagation()}>setQuery(e.target.value)} onKeyDown={e=>{if(e.key==='Enter'){e.preventDefault();create()}}} placeholder="查找或创建选项"/>{visible.map(option=>
{onDelete&&}
)}{!visible.length&&
暂无匹配选项
}{query.trim()&&!options.some(item=>item.name.toLowerCase()===query.trim().toLowerCase())&&}
,document.body):null; return
{menuNode}
; } function ProductDecisionFilterSelect({options=[],value=[],placeholder='筛选',busy=false,onChange,onCreate,onDelete}){ const [expanded,setExpanded]=useState(false);const [draft,setDraft]=useState('');const [menuStyle,setMenuStyle]=useState(null); const ref=useRef(null);const triggerRef=useRef(null);const menuRef=useRef(null);const selected=normalizeFilterList(value); const visible=options.filter(option=>!draft.trim()||option.name.toLowerCase().includes(draft.trim().toLowerCase())||option.key.toLowerCase().includes(draft.trim().toLowerCase())); useEffect(()=>{ if(!expanded)return; function update(){const triggerEl=triggerRef.current;if(triggerEl)setMenuStyle(computeMenuStyle(triggerEl.getBoundingClientRect()))} function close(e){if(triggerRef.current?.contains(e.target))return;if(menuRef.current?.contains(e.target))return;setExpanded(false)} function escape(e){if(e.key==='Escape')setExpanded(false)} update(); window.addEventListener('scroll',update,true); window.addEventListener('resize',update); document.addEventListener('pointerdown',close); document.addEventListener('keydown',escape); return()=>{window.removeEventListener('scroll',update,true);window.removeEventListener('resize',update);document.removeEventListener('pointerdown',close);document.removeEventListener('keydown',escape)}; },[expanded]); async function create(){const name=draft.trim();if(!name||busy||!onCreate)return;const option=await onCreate(name);if(option){onChange([...selected.filter(key=>key!==option.key),option.key]);setDraft('')}} function toggle(option){onChange(selected.includes(option.key)?selected.filter(key=>key!==option.key):[...selected,option.key])} function toggleExpand(e){e.stopPropagation();const triggerEl=triggerRef.current;if(!triggerEl)return;setMenuStyle(computeMenuStyle(triggerEl.getBoundingClientRect()));setExpanded(value=>!value)} const menuNode=expanded&&menuStyle?ReactDOM.createPortal(
e.stopPropagation()} onClick={e=>e.stopPropagation()}>{visible.map(option=>
{onDelete&&}
)}{!visible.length&&
暂无匹配选项
}
setDraft(e.target.value)} onKeyDown={e=>{if(e.key==='Enter'){e.preventDefault();create()}}}/>
新增选项会同步到表格和运营设置
,document.body):null; return
{menuNode}
; } /** BulkCategoryMultiSelect:紧凑的批量改类目控件。 * - 触发器:胶囊按钮,显示当前已选数量或占位提示 * - 弹层:搜索框 + 滚动列表(多选 checkbox)+ 应用/清空 * - 选中状态本地维护,点"应用"才提交到 onApply;点"清空"重置本地 * - 数据契约:options=[{name,color}], value=[name...], onApply(names) */ function BulkCategoryMultiSelect({options=[],value=[],busy=false,placeholder='📁 批量改类目 ▾',onApply}){ const [expanded,setExpanded]=useState(false);const [draft,setDraft]=useState('');const [draftSelected,setDraftSelected]=useState(value);const [menuStyle,setMenuStyle]=useState(null); const triggerRef=useRef(null);const menuRef=useRef(null); useEffect(()=>{setDraftSelected(value)},[value,expanded]); const visible=options.filter(option=>!draft.trim()||option.name.toLowerCase().includes(draft.trim().toLowerCase())); useEffect(()=>{ if(!expanded)return; function update(){const triggerEl=triggerRef.current;if(triggerEl)setMenuStyle(computeMenuStyle(triggerEl.getBoundingClientRect()))} function close(e){if(triggerRef.current?.contains(e.target))return;if(menuRef.current?.contains(e.target))return;setExpanded(false)} function escape(e){if(e.key==='Escape')setExpanded(false)} update(); window.addEventListener('scroll',update,true); window.addEventListener('resize',update); document.addEventListener('pointerdown',close); document.addEventListener('keydown',escape); return()=>{window.removeEventListener('scroll',update,true);window.removeEventListener('resize',update);document.removeEventListener('pointerdown',close);document.removeEventListener('keydown',escape)}; },[expanded]); function toggle(name){setDraftSelected(current=>current.includes(name)?current.filter(item=>item!==name):[...current,name])} function toggleExpand(e){e.stopPropagation();const triggerEl=triggerRef.current;if(!triggerEl)return;setMenuStyle(computeMenuStyle(triggerEl.getBoundingClientRect()));setExpanded(value=>!value)} function apply(){if(!draftSelected.length||busy)return;onApply(draftSelected);setExpanded(false)} function clearDraft(){setDraftSelected([]);setDraft('')} const menuNode=expanded&&menuStyle?ReactDOM.createPortal(
e.stopPropagation()} onClick={e=>e.stopPropagation()}>
setDraft(e.target.value)} placeholder="搜索类目"/>
{visible.length?visible.map(option=>{const checked=draftSelected.includes(option.name);return }):
{draft.trim()?`未找到 “${draft.trim()}”`:'字典为空,请先在表格里创建类目'}
}
{draftSelected.length?`已选 ${draftSelected.length} 项`:'未选中任何项'}
,document.body):null; const displayValue=value.length?`已选 ${value.length} 项`:placeholder; return
{menuNode}
; } /** BulkPrimaryTrackSelect:紧凑的批量改赛道控件(单选)。 * 与 BulkCategoryMultiSelect 共用触发器/弹层样式,placeholder 默认带图标 + ▾ */ function BulkPrimaryTrackSelect({tracks=[],value='',busy=false,placeholder='🎯 批量改赛道 ▾',onApply}){ const [expanded,setExpanded]=useState(false);const [draft,setDraft]=useState('');const [menuStyle,setMenuStyle]=useState(null); const triggerRef=useRef(null);const menuRef=useRef(null); const visible=tracks.filter(track=>!draft.trim()||track.toLowerCase().includes(draft.trim().toLowerCase())); useEffect(()=>{ if(!expanded)return; function update(){const triggerEl=triggerRef.current;if(triggerEl)setMenuStyle(computeMenuStyle(triggerEl.getBoundingClientRect()))} function close(e){if(triggerRef.current?.contains(e.target))return;if(menuRef.current?.contains(e.target))return;setExpanded(false)} function escape(e){if(e.key==='Escape')setExpanded(false)} update(); window.addEventListener('scroll',update,true); window.addEventListener('resize',update); document.addEventListener('pointerdown',close); document.addEventListener('keydown',escape); return()=>{window.removeEventListener('scroll',update,true);window.removeEventListener('resize',update);document.removeEventListener('pointerdown',close);document.removeEventListener('keydown',escape)}; },[expanded]); function toggleExpand(e){e.stopPropagation();const triggerEl=triggerRef.current;if(!triggerEl)return;setMenuStyle(computeMenuStyle(triggerEl.getBoundingClientRect()));setExpanded(value=>!value)} function pick(track){if(busy)return;onApply(track);setExpanded(false);setDraft('')} const menuNode=expanded&&menuStyle?ReactDOM.createPortal(
e.stopPropagation()} onClick={e=>e.stopPropagation()}>
setDraft(e.target.value)} placeholder="搜索赛道"/>
{visible.length?visible.map(track=>{const active=value===track;return }):
{draft.trim()?`未找到 “${draft.trim()}”`:'暂无赛道'}
}
{value?`当前:${value}`:'未选择'}
,document.body):null; const displayValue=value||placeholder; return
{menuNode}
; } function updateUrl(values,push=false){ const url=new URL(location.href); Object.entries(values).forEach(([key,value])=>value===null||value===undefined||value===''?url.searchParams.delete(key):url.searchParams.set(key,String(value))); history[push?'pushState':'replaceState']({},'',url); } function ComparableTrendChart({rows=[]}){ const ref=useRef(null); useEffect(()=>{if(!ref.current||!window.echarts)return;const chart=echarts.init(ref.current);chart.setOption({animation:false,tooltip:{trigger:'axis',formatter:items=>{const row=rows[items[0]?.dataIndex]||{};return [`${row.date||''}`,`可比商品:${row.comparable_count||0}/${row.eligible_count||0}`,`覆盖率:${row.coverage_rate||0}%`,...items.map(item=>`${item.marker}${item.seriesName}:${Number.isFinite(item.value)?fmtNum(item.value):'无可比数据'}`)].join('
')}},legend:{data:['可比商品净增长','可信覆盖率']},grid:{left:58,right:55,top:42,bottom:36},xAxis:{type:'category',data:rows.map(x=>String(x.date||'').slice(5))},yAxis:[{type:'value',name:'销量增长',min:0,splitLine:{lineStyle:{color:'#edf0f3'}}},{type:'value',name:'覆盖率',min:0,max:100,axisLabel:{formatter:'{value}%'}}],series:[{name:'可比商品净增长',type:'bar',data:rows.map(x=>x.sales_growth),barMaxWidth:30,itemStyle:{color:'#16835b',borderRadius:[3,3,0,0]}},{name:'可信覆盖率',type:'line',yAxisIndex:1,data:rows.map(x=>x.coverage_rate),smooth:.25,symbolSize:6,lineStyle:{width:2,color:'#1769aa'},itemStyle:{color:'#1769aa'}}]});const resize=()=>chart.resize();window.addEventListener('resize',resize);return()=>{window.removeEventListener('resize',resize);chart.dispose()}},[rows]); return
; } const HOT_SALES_DELTA = 3; // 飙升:今日增长最低门槛(件) const HOT_SALES_MIN_BASE = 10; // 飙升:累计销量最低门槛(件) const WORKBENCH_CARD_PREVIEW_N = 5; // 工作台首屏榜单预览条数 const WORKBENCH_DETAIL_PAGE_SIZE = 50; // 榜单弹窗每页展示条数 function buildHoverItem(payload, sourceType) { const id = payload && payload.id != null ? payload.id : 'unknown'; const kind = sourceType === 'shop' ? 'shop' : 'product'; const title = sourceType === 'shop' ? (payload?.name || '店铺名待采集') : productTitle(payload || {}); return { id: `hover-${kind}-${id}`, sourceType, sourceId: id, payload: payload || {}, title, }; } function MiniQuickView({item, anchorRect, onClose, onOpen}) { const isProduct = item.sourceType === 'product'; const p = item.payload || {}; const currentPrice = Number(p.current_price || 0); const currentSales = Number(p.current_sales_number || 0); const todayGrowth = Number(p.today_growth || 0); const opportunityScore = Number(p.opportunity_score || 0); const iconName = isProduct ? 'package' : 'store'; const iconTone = isProduct ? 'up' : 'neutral'; const style = {}; if (anchorRect && typeof window !== 'undefined') { const gap = 8; const cardW = 320; const cardH = 240; const winW = window.innerWidth; const winH = window.innerHeight; let left = anchorRect.right + gap; let top = anchorRect.top; if (left + cardW > winW - 12) { left = Math.max(12, anchorRect.left - gap - cardW); } if (left < 12) left = 12; if (top + cardH > winH - 12) { top = Math.max(12, winH - cardH - 12); } if (top < 12) top = 12; style.left = `${left}px`; style.top = `${top}px`; } function go(e) { e.stopPropagation(); onOpen(p, item.sourceType); onClose(); } return (
{item.title}
{isProduct ? ( <>
当前价 {currentPrice > 0 ? `¥${fmtNum(currentPrice, '0.00')}` : '—'}
累计销量 {fmtNum(currentSales)}
今日变化 0 ? 'metric-up' : todayGrowth < 0 ? 'metric-down' : ''}> {fmtDelta(todayGrowth)}
{opportunityScore > 0 && (
测品分 {productScoreLabel(p)}
)} ) : ( <>
店铺粉丝 {p.follower_count ? fmtNum(p.follower_count) : '—'}
今日销量变化 0 ? 'metric-up' : Number(p.today_sales_growth) < 0 ? 'metric-down' : ''}> {fmtDelta(p.today_sales_growth)}
今日上新 {fmtDelta(p.today_new_products)}
)}
); } function WorkbenchRankModal({dialog,onClose,onProduct,onNavigate}) { const [page,setPage]=useState(1); useEffect(()=>setPage(1),[dialog?.title]); if(!dialog)return null; const rows=dialog.rows||[],isShop=dialog.kind==='shop',pageCount=Math.max(1,Math.ceil(rows.length/WORKBENCH_DETAIL_PAGE_SIZE)),safePage=Math.min(page,pageCount),start=(safePage-1)*WORKBENCH_DETAIL_PAGE_SIZE,visible=rows.slice(start,start+WORKBENCH_DETAIL_PAGE_SIZE); const goSource=()=>{onClose();onNavigate(isShop?'shops':'products')}; const openRow=row=>{if(isShop){goSource();return}onClose();onProduct(row)}; return
e.target===e.currentTarget&&onClose()}>

{dialog.title}

{dialog.subtitle} · 共 {fmtNum(rows.length,'0')} 条,每页 {WORKBENCH_DETAIL_PAGE_SIZE} 条
联动来源{dialog.source}
{isShop?:}{visible.map((row,i)=>{const rank=start+i+1;return isShop?openRow(row)}>:openRow(row)}>})}
排名店铺粉丝今日销量变化今日上新最近更新
排名商品赛道 / 类目成交价当前销量今日增长近7日增长机会
{rank}{row.name||'店铺名待采集'}{fmtNum(row.follower_count,'未知')}0?'metric-up':Number(row.today_sales_growth)<0?'metric-down':'muted'}>{fmtDelta(row.today_sales_growth)}{fmtDelta(row.today_new_products)}{fmtTime(row.last_scraped_at)}
{rank}
{productTitle(row)}{row.shop_name||'店铺未知'}
{row.primary_track||'未设置'} / {row.category||'未设置'}{fmtMoney(row.current_price)}{fmtNum(row.current_sales_number,'未知')}0?'metric-up':'muted'}>{fmtDelta(row.today_growth)}0?'metric-up':'muted'}>{fmtDelta(row.growth_7d)}{productScoreLabel(row)} · {row.opportunity_label||'待判断'}
{!visible.length&&暂无数据}
当前显示 {rows.length?`${fmtNum(start+1)}-${fmtNum(start+visible.length)}`:'0'} / {fmtNum(rows.length,'0')} 条
第 {safePage} / {pageCount} 页
; } function WorkbenchPage({overview,schedule,onProduct,onNavigate,onAdd}){ const metrics=overview.metrics||{},coverage=overview.coverage||{},trend=overview.market_trend_7d||[]; const failedJobsCount=Number(metrics.collection_failed_jobs||0); const productAnomalyCount=Number(metrics.collection_anomalies||0); // 优先显示 job 级失败数(与采集中心的待处理队列口径一致),否则兜底商品异常 const anomalyCount=failedJobsCount>0?failedJobsCount:productAnomalyCount; const anomalySource=failedJobsCount>0?'jobs':'products'; const growthDelta=Number(metrics.today_sales_growth||0); const growthTone=growthDelta>0?'metric-up':growthDelta<0?'metric-down':'metric-flat'; const anomalyTone=anomalyCount>0?'metric-down':'metric-flat'; const growthAll=overview.growth_products||[]; const shopAll=overview.shop_activity||[]; const hotSurgeAll=growthAll.filter(p=>Number(p.today_growth||0)>=HOT_SALES_DELTA&&Number(p.current_sales_number||0)>=HOT_SALES_MIN_BASE); const hotSurgeCount=hotSurgeAll.length; const hotSurgeList=hotSurgeAll.slice(0,WORKBENCH_CARD_PREVIEW_N); const growthList=growthAll.slice(0,WORKBENCH_CARD_PREVIEW_N); const shopList=shopAll.slice(0,WORKBENCH_CARD_PREVIEW_N); const [hover,setHover]=useState(null); const [rankDialog,setRankDialog]=useState(null); const hoverTimerRef=useRef(null); const closeTimerRef=useRef(null); const cancelTimers=()=>{ if(hoverTimerRef.current){clearTimeout(hoverTimerRef.current);hoverTimerRef.current=null} if(closeTimerRef.current){clearTimeout(closeTimerRef.current);closeTimerRef.current=null} }; const handleRowEnter=(item,e)=>{ cancelTimers(); const rect=e.currentTarget.getBoundingClientRect(); hoverTimerRef.current=setTimeout(()=>setHover({item,rect}),300); }; const handleRowLeave=()=>{ if(hoverTimerRef.current){clearTimeout(hoverTimerRef.current);hoverTimerRef.current=null} closeTimerRef.current=setTimeout(()=>setHover(null),200); }; const handleQuickviewEnter=()=>{ if(closeTimerRef.current){clearTimeout(closeTimerRef.current);closeTimerRef.current=null} }; const handleQuickviewLeave=()=>{ if(hoverTimerRef.current){clearTimeout(hoverTimerRef.current);hoverTimerRef.current=null} closeTimerRef.current=setTimeout(()=>setHover(null),200); }; const closeQuickview=()=>{cancelTimers();setHover(null)}; useEffect(()=>()=>cancelTimers(),[]); const goProducts=()=>onNavigate('products'); const goShops=()=>onNavigate('shops'); const goOpportunities=()=>onNavigate('opportunities'); const goJobs=()=>onNavigate({jobId:null,filter:anomalyCount>0?'failed':null}); const openHoverItem=(payload,sourceType)=>{ if(sourceType==='shop') goShops(); else onProduct(payload); }; const openRankDialog=type=>{ const configs={ growth:{kind:'product',title:'商品增长榜',subtitle:'今日销量净增长倒序',source:'来自商品监控的全部商品 today_growth,不是关键词页榜单。',rows:growthAll}, shop:{kind:'shop',title:'店铺动态榜',subtitle:'今日销量变化与上新倒序',source:'来自店铺监控的全部店铺快照。',rows:shopAll}, surge:{kind:'product',title:'异动飙升 Top',subtitle:`今日增长 ≥ ${HOT_SALES_DELTA} 且累计销量 ≥ ${HOT_SALES_MIN_BASE}`,source:'来自商品增长榜,再按异动门槛筛选。',rows:hotSurgeAll}, }; setRankDialog(configs[type]); }; return ( <> {/* ===== 顶部状态条(紧凑) ===== */}
0?'has-anomaly':''}`}> {anomalyCount>0 ? ( ) : ( 采集正常 )} 上次采集 {fmtTime(overview.last_scraped_at)} · 下次 {schedule?.daily_time||'00:00'} 自动更新
{/* ===== KPI 4 卡:今日增长 / 异动飙升 / 机会商品 / 采集异常 ===== */}
今日增长
{fmtDelta(metrics.today_sales_growth)}
{fmtNum(metrics.successful_today||0,'0')} 个商品今日有快照
异动飙升
{fmtNum(hotSurgeCount,'0')}
今日 ≥ {HOT_SALES_DELTA} 件 且 累计 ≥ {HOT_SALES_MIN_BASE}
机会商品
{fmtNum(metrics.opportunity_products,'0')}
{fmtNum(metrics.data_accumulating||0,'0')} 个仍在积累
采集异常
{fmtNum(metrics.collection_anomalies,'0')}
{anomalyCount?(anomalySource==='jobs'?`${failedJobsCount} 个失败任务待处理`:'已隔离,不计入增长'):'暂无异常'}
{anomalyCount>0 && ( 查看采集中心 )}
{/* ===== 主区:三分并排(商品增长榜 / 店铺动态榜 / 异动飙升 Top) ===== */}

商品增长榜

今日销量净增长(按 today_growth 倒序)
{growthList.length ? (
{growthList.map((p,i)=>( ))}
) : ( 今日暂无商品增长 )} {growthAll.length>growthList.length&&}

店铺动态榜

今日上新与销量变化
{shopList.length ? (
{shopList.map((s,i)=>{ const sg=Number(s.today_sales_growth||0); const np=Number(s.today_new_products||0); const tone=sg>0?'up':sg<0?'down':'flat'; return ( ); })}
) : ( 今日暂无店铺动态 )} {shopAll.length>shopList.length&&}

异动飙升 Top

今日增长 ≥ {HOT_SALES_DELTA} 且 累计 ≥ {HOT_SALES_MIN_BASE}
{hotSurgeList.length ? (
{hotSurgeList.map((p,i)=>( ))}
) : ( 今日无异动飙升 )} {hotSurgeAll.length>hotSurgeList.length&&}
{/* ===== 底部:弱化趋势图 ===== */}

近 7 日大盘趋势

为今日快讯提供「趋势性 vs 单日噪音」的参照
=70?'green':'amber'}> {coverage.rate>=70?'覆盖可信':'谨慎解读'}
{trend.some(x=>x.comparable_count) ? ( ) : ( 尚无相邻日期可比数据 )}
{/* ===== Mini QuickView 浮层 ===== */} {hover && (
)} setRankDialog(null)} onProduct={onProduct} onNavigate={onNavigate}/> ); } /** * 共享折线图组件 —— 矩阵缩略图 / 关键词浮层 / 详情弹窗全部走这一个。 * props: * - points : [{sales_number, date, scraped_at, growth}] 原始快照 * - variant : 'growth' | 'keyword' 决定 CSS class 前缀与样式 * - width/height : 视口尺寸 * - left/right/top/bottom : 边距 * - showDelta : 多点时是否在每个点上方叠加 ±N 增量(keyword 默认 true) * - interactive : 是否启用 hover 十字线 + tooltip * - showArea : 是否在折线下方填充 area(growth 默认 true) * - emptyText : 无数据时的占位文字 */ function MiniTrendChart({ points = [], rows: inputRows = [], variant = 'growth', width = 320, height = 170, left = 44, right = 14, top = 18, bottom = 30, showDelta = false, compact = false, // 表格列用:关闭坐标轴 / 关闭交互 / 关闭 area,只画折线+圆点+数值 interactive = true, showArea = true, emptyText = '有效日期不足,暂不能绘制趋势', }) { const [hover, setHover] = useState(null); const chartRows = (points?.length ? points : inputRows).filter(x => Number.isFinite(Number(x.sales_number))); const values = chartRows.map(x => Number(x.sales_number)); // compact 模式:表格列用,关闭坐标轴 / 关闭交互 / 关闭 area / 默认小尺寸 const effLeft = compact ? 6 : left; const effRight = compact ? 6 : right; const effTop = compact ? 4 : top; const effBottom = compact ? 12 : bottom; const effWidth = compact ? 120 : width; const effHeight = compact ? 36 : height; const effShowArea = showArea && !compact; const effShowDelta = showDelta && !compact; const effInteractive = interactive && !compact; const plotW = effWidth - effLeft - effRight; const plotH = effHeight - effTop - effBottom; // CSS class 前缀:growth-* / keyword-* const P = variant === 'keyword' ? 'keyword' : 'growth'; const wrapperClass = `${P}-chart-interactive ${compact ? `${P}-chart-compact` : ''}`.trim(); const svgClass = variant === 'keyword' ? `${P}-tiny-chart axis-chart` : `${P}-mini-svg readable`; if (values.length < 1) { return variant === 'keyword' ?
待积累
:
{emptyText}
; } // ── 单点分支:domain=[value, value*1.1],圆点强制落在 X 轴上 ── if (values.length === 1) { const value = values[0]; const row = chartRows[0]; const cx = effLeft + 4; const yMin = value; const yMax = value ? value * 1.1 : 1; // 顶部留 10% 空间放数值标签 const yRange = Math.max(yMax - yMin, 1); // value === yMin ⇒ cy = top + plotH ⇒ 圆点贴底(X 轴) const cy = effTop + (yMax - value) / yRange * plotH; const labelY = Math.max(10, cy - 10); const dotR = compact ? 3 : (variant === 'keyword' ? 3.6 : 4); return (
{!compact && ( )} {!compact && ( /* Y 轴只渲染真实值,不再画 ±N% 填充产生的幽灵小数 */ {fmtNum(value)} )} {fmtNum(value)} {!compact && ( {String(row.date || row.scraped_at || '').slice(5).replace('-', '')} )} {!compact && ( 首日 · 仅 1 个有效点 )}
); } // ── 多点分支:Y 轴按数据规模自适应,聚焦真实变化区间(不硬编码 min:0)── const minRaw = Math.min(...values); const maxRaw = Math.max(...values); const span = Math.max(maxRaw - minRaw, 1); const unit = compact ? (span >= 1000 ? 100 : span >= 100 ? 50 : span >= 20 ? 10 : 1) : (span >= 1000 ? 100 : span >= 100 ? 50 : span >= 20 ? 10 : span >= 5 ? 2 : 1); const pad = Math.max(span * 0.04, unit * 0.5); const min = Math.max(0, Math.floor((minRaw - pad) / unit) * unit); const max = Math.ceil((maxRaw + pad) / unit) * unit; const range = Math.max(max - min, 1); const x = i => effLeft + i * plotW / (values.length - 1); const y = v => effTop + (max - v) / range * plotH; const coords = values.map((v, i) => [x(i), y(v)]); const linePath = coords.map(([px, py], i) => `${i ? 'L' : 'M'} ${px.toFixed(1)} ${py.toFixed(1)}`).join(' '); const areaPath = effShowArea ? `${linePath} L ${x(values.length - 1).toFixed(1)} ${(effHeight - effBottom).toFixed(1)} L ${x(0).toFixed(1)} ${(effHeight - effBottom).toFixed(1)} Z` : ''; const ticks = compact ? [] : [max, Math.round((max + min) / 2), min]; function onMove(event) { if (!effInteractive) return; const rect = event.currentTarget.getBoundingClientRect(); const scale = effWidth / rect.width; const localX = (event.clientX - rect.left) * scale; const index = Math.max(0, Math.min(chartRows.length - 1, Math.round((localX - effLeft) / plotW * (chartRows.length - 1)))); setHover(index); } const active = effInteractive && hover != null ? { index: hover, row: chartRows[hover], value: values[hover], x: x(hover), y: y(values[hover]) } : null; const keywordHover = active && variant === 'keyword' && !compact ? (() => { const boxW = 86; const boxH = 36; const boxX = Math.max(4, Math.min(effWidth - boxW - 4, active.x + (active.x > effWidth - boxW - 10 ? -boxW - 8 : 8))); const boxY = Math.max(4, Math.min(effHeight - boxH - effBottom + 4, active.y - boxH - 8)); const prev = active.index > 0 ? values[active.index - 1] : null; const sourceDelta = active.row.growth ?? active.row.periodDelta; const delta = sourceDelta == null && prev != null ? active.value - prev : sourceDelta; return { x: boxX, y: boxY, width: boxW, height: boxH, date: String(active.row.date || active.row.scraped_at || '').slice(5).replace('-', '/'), delta, }; })() : null; return (
setHover(null)} > {!compact && ticks.map((tick, i) => ( {fmtNum(tick)} ))} {!compact && ( )} {!compact && ( )} {effShowArea && } {active && !keywordHover && ( )} {chartRows.map((row, i) => { const [px, py] = coords[i]; const activePoint = hover === i; const dotRadius = compact ? 2.4 : (variant === 'keyword' ? 2.4 : activePoint ? 4 : 3); const prev = i ? values[i - 1] : null; const delta = prev === null ? null : values[i] - prev; const valueY = compact ? Math.max(effTop + 8, py - 6) : Math.max(11, py - 13); const deltaY = Math.max(valueY + 10, py - 3); const dateAnchor = i === 0 ? 'start' : i === chartRows.length - 1 ? 'end' : 'middle'; const dateLabel = String(row.date || row.scraped_at || '').slice(5).replace('-', ''); return ( {fmtNum(values[i])} {effShowDelta && delta !== null && delta !== 0 && deltaY < effHeight - effBottom - 2 && ( 0 ? 'up' : 'down'}`} x={px} y={deltaY} textAnchor="middle" > {delta > 0 ? `+${fmtNum(delta)}` : fmtNum(delta)} )} {!compact && ( {dateLabel} )} ); })} {keywordHover && ( {keywordHover.date || '当前点'} 销量 {fmtNum(active.value)} {keywordHover.delta == null ? '增长 待积累' : `增长 ${fmtDelta(keywordHover.delta)}`} )} {effInteractive && ( )} {active && variant === 'growth' && !compact && (
{fmtTime(active.row.scraped_at || active.row.date)} 总销量:{fmtNum(active.value)} 当日增长:{(active.row.growth ?? active.row.periodDelta) == null ? '待积累' : fmtDelta(active.row.growth ?? active.row.periodDelta)}
)}
); } // 兼容旧名:矩阵缩略图仍引用 GrowthMiniChart function GrowthMiniChart(props) { return ; } // 关键词浮层仍引用 KeywordTinyChart function KeywordTinyChart(props) { return ; } function GrowthInsightPopover({product,type,anchorRect,onClose}){ const points=(product.sales_sparkline_7d||[]).filter(x=>Number.isFinite(Number(x.sales_number))).slice(-7),historyPoints=[...points].sort((a,b)=>String(b.scraped_at||b.date||'').localeCompare(String(a.scraped_at||a.date||''))),today=type==='today',delta=today?product.today_growth:product.growth_7d; // 浮层用 React Portal 渲染到 body,避免被单元格 overflow:hidden 裁切 const [style,setStyle]=useState(()=>computePopoverStyle(anchorRect)); useEffect(()=>{ if(!anchorRect)return; function update(){setStyle(computePopoverStyle(anchorRect))} update(); window.addEventListener('scroll',update,true); window.addEventListener('resize',update); return()=>{window.removeEventListener('scroll',update,true);window.removeEventListener('resize',update)}; },[anchorRect]); if(!anchorRect)return null; const node=
e.stopPropagation()} onClick={e=>e.stopPropagation()}>
{today?'今日增长':'近7日增长'}{today?'最近7个采集日的销量与增量':'最近7个采集日的销量趋势'}
{today?<>
本次增加0?'metric-up':Number(delta)<0?'metric-down':'muted'}>{fmtDelta(delta)}
当前总销量{fmtNum(product.current_sales_number,'未知')}
{historyPoints.length?<>
采集时间(最新)总销量增长
{historyPoints.map((row,index)=>
{fmtTime(row.scraped_at||row.date)}{fmtNum(row.sales_number)}0?'metric-up':Number(row.growth)<0?'metric-down':'muted'}>{row.growth==null?'待积累':fmtDelta(row.growth)}
)}:
暂无可信快照
}
:
}
; return ReactDOM.createPortal(node,document.body); } function productSignal(product){ const week=Number(product.growth_7d),today=Number(product.today_growth),score=Number(product.opportunity_score)||0; if(product.status==='warning'||product.status==='failed'||(product.anomalies||[]).length) return {label:'观测异常',tone:'red',summary:'数据异常,已隔离,不计入正常增长。'}; if(week>=1000||today>=100) return {label:'爆发前夕',tone:'red',summary:'近期增长明显,近7日增加 '+fmtDelta(week)+'。'}; if(week>0||today>0) return {label:'稳定出单',tone:'green',summary:'销量仍在增加,近7日增长 '+fmtDelta(week)+'。'}; if((product.daily_data_days||0)<2) return {label:'数据积累中',tone:'amber',summary:'有效日期不足,暂时不能判断稳定趋势。'}; if(score>=60) return {label:'值得观察',tone:'blue',summary:'机会分 '+score+',建议结合店铺与货源继续判断。'}; return {label:'暂未入选',tone:'default',summary:'当前没有明显增长信号。'}; } function ProductTableV2({products,onProduct,onReload,onJobs,resetToken=0}){ const params=new URLSearchParams(location.search);const savedId=params.get('filterSet');let saved={};try{saved=savedId?JSON.parse(sessionStorage.getItem(`filters:${savedId}`)||'{}'):{} }catch{} const [filters,setFilters]=useState({q:params.get('q')||'',track:params.get('track')||'',category:params.get('category')||'',secondaryCategory:params.get('secondaryCategory')||'',type:normalizeFilterList(saved.type),stage:normalizeFilterList(saved.stage),monitor:saved.monitor||''}); const initialPageSize=[20,50,100].includes(Number(localStorage.getItem('productPageSize')))?Number(localStorage.getItem('productPageSize')):20; const [sort,setSort]=useState(params.get('sort')||'updated'),[view,setView]=useState(params.get('view')||'decision'),[selected,setSelected]=useState([]),[page,setPage]=useState(1),[pageSize,setPageSize]=useState(initialPageSize),[jumpPage,setJumpPage]=useState('1'),[busy,setBusy]=useState(false),[menuId,setMenuId]=useState(null),[menuAnchorRect,setMenuAnchorRect]=useState(null),[growthView,setGrowthView]=useState(null),[advancedOpen,setAdvancedOpen]=useState(false),[categoryCatalog,setCategoryCatalog]=useState([]),[categoryBusyId,setCategoryBusyId]=useState(null),[bulkAiCategories,setBulkAiCategories]=useState([]),[bulkPrimaryTrack,setBulkPrimaryTrack]=useState(''),[opportunityTypeOptions,setOpportunityTypeOptions]=useState([]),[opportunityStageOptions,setOpportunityStageOptions]=useState([]); useEffect(()=>{if(!resetToken)return;setFilters({q:'',track:'',category:'',secondaryCategory:'',type:[],stage:[],monitor:''});setSort('updated');setView('decision');setSelected([]);setPage(1);setJumpPage('1');setMenuId(null);setGrowthView(null);setAdvancedOpen(false)},[resetToken]); useEffect(()=>{api('/api/product-category-options').then(setCategoryCatalog).catch(()=>setCategoryCatalog([]))},[]); async function loadDecisionOptions(){const [types,stages]=await Promise.all([api('/api/product-opportunity-type-options'),api('/api/product-opportunity-stage-options')]);setOpportunityTypeOptions(types);setOpportunityStageOptions(stages)} useEffect(()=>{loadDecisionOptions().catch(()=>{setOpportunityTypeOptions(optionListFromMap(TYPES));setOpportunityStageOptions(optionListFromMap(STAGES,'#6941c6'))})},[]); const categoryOptions=useMemo(()=>buildProductCategoryOptions(products,categoryCatalog),[categoryCatalog,products]); const primaryCategories=useMemo(()=>primaryCategoryOptions(categoryOptions).map(item=>item.name),[categoryOptions]); const secondaryCategories=useMemo(()=>secondaryCategoryOptions(categoryOptions,filters.category).map(item=>item.name),[categoryOptions,filters.category]); useEffect(()=>{if(filters.secondaryCategory&&!secondaryCategories.includes(filters.secondaryCategory))setFilters(current=>({...current,secondaryCategory:''}))},[filters.secondaryCategory,secondaryCategories]); useEffect(()=>{const complex={type:filters.type,stage:filters.stage,monitor:filters.monitor};let filterSet='';if(filters.type.length||filters.stage.length||filters.monitor){filterSet=savedId||Math.random().toString(36).slice(2,9);sessionStorage.setItem(`filters:${filterSet}`,JSON.stringify(complex))}updateUrl({q:filters.q,track:filters.track,category:filters.category,secondaryCategory:filters.secondaryCategory,sort:sort==='updated'?null:sort,view:view==='decision'?null:view,filterSet})},[filters,sort,view]); const filtered=useMemo(()=>{const q=filters.q.trim().toLowerCase(),key={sales:'current_sales_number',today:'today_growth',week:'growth_7d',revenue:'estimated_revenue',updated:'last_scraped_at'}[sort];return [...products].filter(p=>{const levels=productCategoryLevels(p);return (!q||[p.name,p.shop_name,p.url,levels.primary,levels.secondary,p.tags].some(x=>String(x||'').toLowerCase().includes(q)))&&(!filters.track||p.primary_track===filters.track)&&(!filters.category||levels.primary===filters.category)&&(!filters.secondaryCategory||levels.secondary===filters.secondaryCategory)&&(!filters.type.length||filters.type.includes(p.opportunity_type))&&(!filters.stage.length||filters.stage.includes(p.opportunity_stage))&&(!filters.monitor||String(Boolean(p.scheduled_monitoring))===filters.monitor)}).sort((a,b)=>key==='last_scraped_at'?String(b[key]||'').localeCompare(String(a[key]||'')):Number(b[key]??-Infinity)-Number(a[key]??-Infinity))},[products,filters,sort]); const total=Math.max(1,Math.ceil(filtered.length/pageSize)),rows=filtered.slice((page-1)*pageSize,page*pageSize),pageIds=rows.map(p=>p.id),filteredIds=filtered.map(p=>p.id),all=Boolean(pageIds.length)&&pageIds.every(id=>selected.includes(id)),allFiltered=Boolean(filteredIds.length)&&filteredIds.every(id=>selected.includes(id)); useEffect(()=>setPage(1),[filters,sort,pageSize]);useEffect(()=>setSelected([]),[filters]);useEffect(()=>{if(page>total)setPage(total);setJumpPage(String(Math.min(page,total)))},[page,total]);useEffect(()=>localStorage.setItem('productPageSize',String(pageSize)),[pageSize]); useEffect(()=>{const close=(event)=>{if(!event.target.closest('.row-menu,.row-menu-panel'))setMenuId(null);if(!event.target.closest('.growth-trigger,.growth-popover'))setGrowthView(null)};document.addEventListener('mousedown',close);return()=>document.removeEventListener('mousedown',close)},[]); useEffect(()=>{document.querySelectorAll('.supplier-company-cell').forEach(cell=>cell.setAttribute('title',cell.querySelector('strong')?.textContent||''))},[rows]); function goToPage(value){const target=Math.min(total,Math.max(1,Number(value)||1));setPage(target);setJumpPage(String(target))} function togglePageSelection(){setSelected(current=>all?current.filter(id=>!pageIds.includes(id)):[...new Set([...current,...pageIds])])} function toggleFilteredSelection(){setSelected(current=>allFiltered?current.filter(id=>!filteredIds.includes(id)):[...new Set([...current,...filteredIds])])} function setFilter(key,value){setFilters(current=>key==='category'?{...current,category:value,secondaryCategory:secondaryBelongsToPrimary(categoryOptions,current.secondaryCategory,value)?current.secondaryCategory:''}:{...current,[key]:value})} // 批量更新:真实 PATCH /api/products/batch,成功后提示已更新数量 + 清空选择 + 刷新列表 async function batch(payload,message=''){ if(!selected.length)return; setBusy(true); try{ const result=await api('/api/products/batch',{method:'PATCH',body:JSON.stringify({ids:selected,...payload})}); const count=Number(result?.updated)||selected.length; setSelected([]); setBulkAiCategories([]); setBulkPrimaryTrack(''); await onReload(); // 成功反馈:避免用户怀疑「是不是没生效」 const tip=message||`已更新 ${count} 个商品`; window.dispatchEvent(new CustomEvent('xhs-toast',{detail:{type:'success',text:tip}})); }catch(e){ window.dispatchEvent(new CustomEvent('xhs-toast',{detail:{type:'error',text:e.message}})); alert(e.message); }finally{setBusy(false)} } async function scrape(ids,mode='fast'){ if(!ids.length)return; setBusy(true); try{ const created=await api('/api/products/batch/scrape',{method:'POST',body:JSON.stringify({ids,mode})}); setSelected([]); await onReload(); onJobs(created); window.dispatchEvent(new CustomEvent('xhs-toast',{detail:{type:'success',text:`已提交 ${ids.length} 个商品的${mode==='deep'?'深度重采':'快速采集'}任务`}})); }catch(e){ window.dispatchEvent(new CustomEvent('xhs-toast',{detail:{type:'error',text:e.message}})); alert(e.message); }finally{setBusy(false)} } async function removeProduct(product){if(!confirm(`确认删除“${productTitle(product)}”吗?删除后该商品的采集记录也会一并移除。`))return;setMenuId(null);setBusy(true);try{await api(`/api/products/${product.id}`,{method:'DELETE'});setSelected(ids=>ids.filter(id=>id!==product.id));await onReload()}catch(e){alert(e.message)}finally{setBusy(false)}} async function deleteSelectedProducts(){if(!selected.length)return;if(!confirm(`确认删除选中的 ${selected.length} 个商品监控吗?删除后采集记录也会一并移除。`))return;setBusy(true);try{for(const id of selected)await api(`/api/products/${id}`,{method:'DELETE'});setSelected([]);await onReload()}catch(e){alert(e.message)}finally{setBusy(false)}} async function setProductMonitoring(product,value){try{await api(`/api/products/${product.id}`,{method:'PATCH',body:JSON.stringify({scheduled_monitoring:value})});await onReload()}catch(e){alert(e.message)}} async function saveProductCategories(product,categoryLevels){setCategoryBusyId(product.id);try{await api(`/api/products/${product.id}/categories`,{method:'PUT',body:JSON.stringify(categoryLevels)});await onReload();return true}catch(e){alert(e.message);return false}finally{setCategoryBusyId(null)}} async function autoMatchCategories(){ const selectedRows=filtered.filter(product=>selected.includes(product.id)); const incomplete=filtered.filter(product=>{const levels=productCategoryLevels(product);return !levels.primary||!levels.secondary}); const source=selectedRows.length?selectedRows:incomplete.length?incomplete:filtered; const ids=source.slice(0,200).map(product=>product.id); if(!ids.length)return alert('当前没有可匹配类目的商品'); if(source.length>200&&!confirm('当前商品超过 200 个,本次先处理前 200 个,继续吗?'))return; setBusy(true); try{ const result=await api('/api/products/categories/auto-match',{method:'POST',body:JSON.stringify({ids})}); const updated=Number(result.updated)||0,unchanged=Number(result.unchanged)||0,uncategorized=(result.results||[]).filter(item=>(item.categories||[]).includes('待归类')).length; const text=`已更新 ${updated} 个商品类目${unchanged?`,${unchanged} 个已是最新`:''}${uncategorized?`,${uncategorized} 个归为待归类`:''}`; window.dispatchEvent(new CustomEvent('xhs-toast',{detail:{type:updated?'success':'',text}})); alert(text); setSelected(current=>current.filter(id=>!ids.includes(id))); await onReload(); }catch(e){alert(e.message)}finally{setBusy(false)} } async function createCategoryOption(name,color){try{const option=await api('/api/product-category-options',{method:'POST',body:JSON.stringify({name,color})});setCategoryCatalog(current=>[...current.filter(item=>item.name!==option.name),option]);return option}catch(e){alert(e.message);return null}} async function deleteCategoryOption(option){try{await api(`/api/product-category-options/${encodeURIComponent(option.name)}`,{method:'DELETE'});setCategoryCatalog(current=>current.filter(item=>item.name!==option.name));await onReload()}catch(e){window.dispatchEvent(new CustomEvent('xhs-toast',{detail:{type:'error',text:e.message}}))}} async function createOpportunityTypeOption(name){try{const option=await api('/api/product-opportunity-type-options',{method:'POST',body:JSON.stringify({name,color:'#1769aa'})});setOpportunityTypeOptions(current=>[...current.filter(item=>item.key!==option.key),option]);return option}catch(e){alert(e.message);return null}} async function deleteOpportunityTypeOption(option){if(!confirm(`删除机会判断“${option.name}”吗?使用它的商品会回到系统判断。`))return;try{await api(`/api/product-opportunity-type-options/${encodeURIComponent(option.key)}`,{method:'DELETE'});setOpportunityTypeOptions(current=>current.filter(item=>item.key!==option.key));setFilters(current=>({...current,type:normalizeFilterList(current.type).filter(key=>key!==option.key)}));await onReload()}catch(e){alert(e.message)}} async function createOpportunityStageOption(name){try{const option=await api('/api/product-opportunity-stage-options',{method:'POST',body:JSON.stringify({name,color:'#6941c6'})});setOpportunityStageOptions(current=>[...current.filter(item=>item.key!==option.key),option]);return option}catch(e){alert(e.message);return null}} async function deleteOpportunityStageOption(option){if(!confirm(`删除机会阶段“${option.name}”吗?使用它的商品会移出机会池。`))return;try{await api(`/api/product-opportunity-stage-options/${encodeURIComponent(option.key)}`,{method:'DELETE'});setOpportunityStageOptions(current=>current.filter(item=>item.key!==option.key));setFilters(current=>({...current,stage:normalizeFilterList(current.stage).filter(key=>key!==option.key)}));await onReload()}catch(e){alert(e.message)}} async function saveOpportunityType(product,option){const payload=option?{manual_opportunity_type:option.key,manual_opportunity_label:option.name}:{manual_opportunity_type:'',manual_opportunity_label:''};await api(`/api/products/${product.id}/opportunity`,{method:'PATCH',body:JSON.stringify(payload)});await onReload()} async function saveOpportunityStage(product,option){await api(`/api/products/${product.id}/opportunity`,{method:'PATCH',body:JSON.stringify({opportunity_stage:option?.key||''})});await onReload()} const typeOptions=opportunityTypeOptions.length?opportunityTypeOptions:optionListFromMap(TYPES),stageOptions=opportunityStageOptions,defaultStageKey=stageOptions[0]?.key||''; // 行菜单(操作列 …)改用 Portal 渲染到 body,避开 td 的 overflow:hidden。 // 面板宽度 145px、右对齐到触发按钮,必要时翻到按钮上方。 function computeRowMenuStyle(rect){ if(!rect)return {display:'none'}; const panelW=145,offset=4,gap=8; const margin=gap; const panelH=240; let top=rect.bottom+offset; if(top+panelH>window.innerHeight-margin){ const flipped=rect.top-panelH-offset; if(flipped>=margin)top=flipped; else top=Math.max(margin,window.innerHeight-panelH-margin); } let left=rect.right-panelW; const maxLeft=window.innerWidth-panelW-margin; if(left>maxLeft)left=maxLeft; if(leftr.id===menuId):null; const rowMenuNode=rowMenuProduct&&menuAnchorRect?ReactDOM.createPortal(
e.stopPropagation()}>
,document.body):null; useEffect(()=>{ if(!menuId)return; function update(){ const el=rowMenuTriggerRef.current; if(!el||!rows.find(r=>r.id===menuId)){setMenuId(null);setMenuAnchorRect(null);return} setMenuAnchorRect(el.getBoundingClientRect()); } update(); window.addEventListener('scroll',update,true); window.addEventListener('resize',update); return()=>{window.removeEventListener('scroll',update,true);window.removeEventListener('resize',update)}; },[menuId,rows]); const advancedCount=(filters.type.length?1:0)+(filters.stage.length?1:0)+(filters.monitor?1:0),totalActive=(filters.q?1:0)+(filters.track?1:0)+(filters.category?1:0)+(filters.secondaryCategory?1:0)+(sort!=='updated'?1:0)+advancedCount; function clearProductFilters(){setFilters({q:'',track:'',category:'',secondaryCategory:'',type:[],stage:[],monitor:''});setSort('updated');setSelected([]);setPage(1)} return
商品筛选{totalActive?`已启用 ${totalActive} 个条件`:'默认查看全部商品'}
setFilter('q',e.target.value)} onKeyDown={e=>{if(e.key==='Enter')setPage(1)}} placeholder="搜索商品、店铺或链接"/>
{advancedOpen&&
setFilter('type',value)} onCreate={createOpportunityTypeOption} onDelete={deleteOpportunityTypeOption}/>setFilter('stage',value)} onCreate={createOpportunityStageOption} onDelete={deleteOpportunityStageOption}/>
}
{selected.length>0&&
已选择 {selected.length} 个{!allFiltered&&filtered.length>selected.length&&}{allFiltered&&已覆盖当前筛选全部商品}
}
商品列表共 {filtered.length} 个商品 · 当前 {rows.length?`${(page-1)*pageSize+1}-${Math.min(page*pageSize,filtered.length)}`:'0'} 条
{rows.map(p=>{const signal=productSignal(p);return })}
商品信息赛道一级类目二级类目价格 / 总销量今日增长近7日增长预估营收货源公司机会判断机会阶段监控状态更新 / 质量操作
e.stopPropagation()}>setSelected(x=>x.includes(p.id)?x.filter(id=>id!==p.id):[...x,p.id])}/>onProduct(p)} onKeyDown={e=>{if(e.key==='Enter')onProduct(p)}} tabIndex="0">
{productTitle(p)}
{p.shop_name||statusText(p.status)}
{p.business_tags?.length>0&&
{p.business_tags.slice(0,2).map(t=>)}
}
{p.primary_track||'未设置'}
{fmtMoney(p.current_price)}{fmtNum(p.current_sales_number,'未知')} 销量
{growthView?.id===p.id&&growthView.type==='today'&&setGrowthView(null)}/>}{growthView?.id===p.id&&growthView.type==='week'&&setGrowthView(null)}/>}{fmtMoney(p.estimated_revenue)}
{p.primary_supplier_candidate?.supplier_name||'未绑定'}{(p.primary_supplier_candidate?.supplier_platform||p.primary_supplier_candidate?.source_url)?'主货源':'待绑定'}
e.stopPropagation()}>saveOpportunityType(p,option)} onCreate={createOpportunityTypeOption} onDelete={deleteOpportunityTypeOption}/>{productDecisionMeta(p)}e.stopPropagation()}>saveOpportunityStage(p,option)} onCreate={createOpportunityStageOption} onDelete={deleteOpportunityStageOption}/>e.stopPropagation()}>setProductMonitoring(p,value)}/>
{fmtTime(p.last_scraped_at)}
{statusText(p.status)}
e.stopPropagation()}>
{!rows.length&&没有符合条件的商品}
{rows.map(p=>)}
共 {filtered.length} 条 · 当前 {rows.length?`${(page-1)*pageSize+1}-${Math.min(page*pageSize,filtered.length)}`:'0'} 条
每页已渲染 {rows.length} / {pageSize}
第 {page} / {total} 页
跳至setJumpPage(e.target.value)} onKeyDown={e=>{if(e.key==='Enter')goToPage(jumpPage)}}/>页
{rowMenuNode}
; } const STAGE_ORDER=['watching','planned','testing','adopted','abandoned']; function fallbackStageOptions(){return STAGE_ORDER.map(key=>({key,name:STAGES[key],color:'#6941c6'}))} function buildOpportunityStageGroups(options,pool){ const map=new Map(); (options?.length?options:fallbackStageOptions()).forEach(item=>item?.key&&map.set(item.key,{key:item.key,name:item.name||STAGES[item.key]||item.key,color:item.color||'#6941c6'})); (pool||[]).forEach(product=>{ const key=product.opportunity_stage; if(key&&!map.has(key))map.set(key,{key,name:STAGES[key]||key,color:'#98a2b3'}); }); return [...map.values()].map(item=>({id:item.key,label:item.name,color:item.color,match:s=>s===item.key})); } function OpportunityCard({product,onOpen,onStage,stageOptions=[]}){ // 看板卡片只保留识别 + 关键增长 + 状态流转;详情(主货源/利润/对标/运营记录/准备度等)走右侧抽屉 const growthDir=Number(product.growth_7d)>0?'up':Number(product.growth_7d)<0?'down':'flat'; const actions=stageOptions.length?stageOptions:fallbackStageOptions(); const actionList=product.opportunity_stage&&!actions.some(item=>item.key===product.opportunity_stage)?[...actions,{key:product.opportunity_stage,name:STAGES[product.opportunity_stage]||product.opportunity_stage,color:'#98a2b3'}]:actions; const currentStage=actionList.find(item=>item.key===product.opportunity_stage); return
onOpen(product)}>
{productTitle(product)}
{productScoreLabel(product)} 数据 {product.daily_data_days||0} 天
7日增长 {fmtDelta(product.growth_7d)}
e.stopPropagation()}>
{currentStage?.name||'未设置阶段'}
{actionList.map(option=>)}
; } const OPPORTUNITY_SORTS=[ {value:'default',label:'默认 · 机会分优先'}, {value:'joined_desc',label:'加入日期 · 从新到旧'}, {value:'joined_asc',label:'加入日期 · 从旧到新'}, {value:'growth_desc',label:'7日增长 · 高到低'}, {value:'days_desc',label:'数据天数 · 多到少'}, ]; function compareOpportunity(a,b,sort){ switch(sort){ case 'joined_desc':return (b.opportunity_added_at||'').localeCompare(a.opportunity_added_at||''); case 'joined_asc':return (a.opportunity_added_at||'').localeCompare(b.opportunity_added_at||''); case 'growth_desc':return Number(b.growth_7d||0)-Number(a.growth_7d||0); case 'days_desc':return Number(b.daily_data_days||0)-Number(a.daily_data_days||0); default:return Number(b.opportunity_score||0)-Number(a.opportunity_score||0); } } function OpportunityPageV2({products,onProduct,onNavigate,onReload,resetToken=0}){ const [stage,setStage]=useState(''),[view,setView]=useState('board'),[sort,setSort]=useState('default'); const [stageOptions,setStageOptions]=useState([]); const [listPage,setListPage]=useState(1),[listPageSize,setListPageSize]=useState(20),[listJumpPage,setListJumpPage]=useState('1'); const [columnPages,setColumnPages]=useState({}); const [signalView,setSignalView]=useState(null); const boardColumnSize=12; async function loadStageOptions(){try{setStageOptions(await api('/api/product-opportunity-stage-options'))}catch{setStageOptions(fallbackStageOptions())}} useEffect(()=>{loadStageOptions()},[]); useEffect(()=>{if(!resetToken)return;setStage('');setView('board');setSort('default');setListPage(1);setListJumpPage('1');setColumnPages({});setSignalView(null);loadStageOptions()},[resetToken]); useEffect(()=>setListPage(1),[stage,sort,listPageSize]); useEffect(()=>setColumnPages({}),[stage,sort]); useEffect(()=>{setSignalView(null)},[stage,sort,listPage,view]); async function changeStage(product,value){await api(`/api/products/${product.id}/opportunity`,{method:'PATCH',body:JSON.stringify({opportunity_stage:value})});await onReload();await loadStageOptions()} const pool=products.filter(p=>p.scheduled_monitoring&&p.opportunity_stage); const stageGroups=useMemo(()=>buildOpportunityStageGroups(stageOptions,pool),[stageOptions,products]); const cardStageOptions=stageGroups.map(group=>({key:group.id,name:group.label,color:group.color})); useEffect(()=>{if(stage&&!stageGroups.some(group=>group.id===stage))setStage('')},[stage,stageGroups]); const readinessReady=pool.filter(p=>p.readiness?.total&&p.readiness.completed===p.readiness.total).length,missingSource=pool.filter(p=>!p.primary_supplier_candidate).length,readyToCompare=pool.filter(p=>(p.daily_data_days||0)>=2).length; const sortedPool=[...pool].sort((a,b)=>compareOpportunity(a,b,sort)); // 列表视图分页 const listFiltered=sortedPool.filter(p=>!stage||p.opportunity_stage===stage); const listTotalPages=Math.max(1,Math.ceil(listFiltered.length/listPageSize)); const safeListPage=Math.min(listPage,listTotalPages); const listRows=listFiltered.slice((safeListPage-1)*listPageSize,safeListPage*listPageSize); function goListPage(value){const target=Math.min(listTotalPages,Math.max(1,Number(value)||1));setListPage(target);setListJumpPage(String(target))} useEffect(()=>setListJumpPage(String(safeListPage)),[safeListPage]); // 看板分组(stage 过滤下只显示匹配的一组) const visibleGroups=stage?stageGroups.filter(g=>g.match(stage)):stageGroups; function goColumnPage(groupId,delta){ setColumnPages(prev=>{ const group=visibleGroups.find(g=>g.id===groupId); if(!group)return prev; const items=sortedPool.filter(p=>group.match(p.opportunity_stage)); const total=Math.max(1,Math.ceil(items.length/boardColumnSize)); const current=Math.min(total,Math.max(1,prev[groupId]||1)); const next=Math.min(total,Math.max(1,current+delta)); return {...prev,[groupId]:next}; }); } if(!pool.length)return

机会池还没有待推进商品

机会池联动商品监控,只显示仍在监控且设置了机会阶段的商品;删除阶段词后,绑定它的商品会自动回到“未进机会池”。

; return ( <>
推进中
{pool.filter(p=>!['adopted','abandoned'].includes(p.opportunity_stage)).length}
待完成选品动作
测试准备完成
{readinessReady}
关键资料齐全
缺少主货源
{missingSource}
需要优先找货
数据可判断
{readyToCompare}
至少 2 个有效日期
联动逻辑:商品监控的机会阶段、机会池顶部筛选、卡片底部阶段按钮使用同一套状态;只显示"监控中 + 已设置机会阶段"的商品。
{stageGroups.map(group=>)}
{view==='board' ? (
{visibleGroups.map(group=>{ const items=sortedPool.filter(p=>group.match(p.opportunity_stage)); const total=Math.max(1,Math.ceil(items.length/boardColumnSize)); const current=Math.min(total,Math.max(1,columnPages[group.id]||1)); const pageItems=items.slice((current-1)*boardColumnSize,current*boardColumnSize); return (
{group.label} {items.length}
{pageItems.length ? ( pageItems.map(p=>) ) : (
{items.length===0 ? '暂无商品' : '本页为空'}
)}
{total>1 && (
{current} / {total}
)}
); })}
) : (
{listRows.map(p=>{ const todayOpen = signalView?.id===p.id && signalView.type==='today'; const weekOpen = signalView?.id===p.id && signalView.type==='week'; return ( onProduct(p)}> ); })}
商品 / 阶段 价格 / 总销量 今日增长 近7日增长 货源进度 利润 准备度 系统判断 数据积累 加入时间
{productTitle(p)}
{p.shop_name||statusText(p.status)}
{stageText(p.opportunity_stage)}
{fmtMoney(p.current_price)} {fmtNum(p.current_sales_number,'未知')} 销量
e.stopPropagation()}> {todayOpen && setSignalView(null)}/>} e.stopPropagation()}> {weekOpen && setSignalView(null)}/>} {p.primary_supplier_candidate?.supplier_name || '待找货'} · {p.source_candidate_count||0} 个候选 {p.profit?.complete ? `${fmtMoney(p.profit.net_profit)} / ${p.profit.margin}%` : '待核算'} {p.readiness?.completed||0}/{p.readiness?.total||4} {p.opportunity_label||'待判断'} {p.daily_data_days||0} 天 {fmtTime(p.opportunity_added_at)}
{!listRows.length && 没有符合条件的商品}
共 {listFiltered.length} 条 · 当前 {listRows.length ? `${(safeListPage-1)*listPageSize+1}-${Math.min(safeListPage*listPageSize,listFiltered.length)}` : '0'} 条
每页
第 {safeListPage} / {listTotalPages} 页
跳至 setListJumpPage(e.target.value)} onKeyDown={e=>{if(e.key==='Enter')goListPage(listJumpPage)}}/> 页
)} ); } const SUPPLIER_COOPERATION={contacting:'待联系',quoting:'沟通报价',sampling:'打样中',cooperating:'合作中',paused:'已暂停'}; function SupplierContactPanel({supplier,onSaved}){ const empty={name:'',platform:'1688',profile_url:'',main_categories:'',shipping_time:'',contact_name:'',contact_method:'',default_moq:'',payment_terms:'',return_policy:'',cooperation_status:'contacting',supports_dropship:false,rating:3,notes:''}; const normalize=value=>({...empty,...value,profile_url:value.profile_url||'',main_categories:value.main_categories||'',shipping_time:value.shipping_time||'',contact_name:value.contact_name||'',contact_method:value.contact_method||'',default_moq:value.default_moq||'',payment_terms:value.payment_terms||'',return_policy:value.return_policy||'',notes:value.notes==='一件起订'?'':(value.notes||''),supports_dropship:Boolean(value.supports_dropship),rating:value.rating||3}); const [form,setForm]=useState(normalize(supplier)),[dirty,setDirty]=useState({}),[busy,setBusy]=useState(false); useEffect(()=>{setForm(normalize(supplier));setDirty({})},[supplier.id,supplier.updated_at]); function field(key,value){setForm(current=>({...current,[key]:value}));setDirty(current=>({...current,[key]:true}))} async function save(){const nullable=new Set(['profile_url','main_categories','shipping_time','contact_name','contact_method','default_moq','payment_terms','return_policy','notes']);const payload=Object.fromEntries(Object.keys(dirty).map(key=>[key,nullable.has(key)?(form[key]||null):form[key]]));if(!Object.keys(payload).length)return;if('supports_dropship' in payload)payload.supports_dropship=Boolean(payload.supports_dropship);if('rating' in payload)payload.rating=Number(payload.rating);setBusy(true);try{await api(`/api/suppliers/${supplier.id}`,{method:'PATCH',body:JSON.stringify(payload)});await onSaved()}catch(e){alert(e.message)}finally{setBusy(false)}} return
工厂对接资料维护这家工厂的联系与合作条件,不填写单个商品报价
{SUPPLIER_COOPERATION[form.cooperation_status]}
field('name',e.target.value)}/>
field('profile_url',e.target.value)} placeholder="https://..."/>{form.profile_url&&打开}
field('contact_name',e.target.value)} placeholder="姓名或称呼"/>
field('contact_method',e.target.value)} placeholder="微信、电话或旺旺"/>
field('main_categories',e.target.value)} placeholder="例如:杯壶、餐厨"/>
field('shipping_time',e.target.value)} placeholder="例如:48小时内"/>
field('default_moq',e.target.value)} placeholder="例如:1件 / 100件"/>
field('supports_dropship',value)}/>
field('payment_terms',e.target.value)} placeholder="例如:现结、先30%定金"/>