/* 既有 Context 模块同时导出 Provider、useStore 和共享工具;保持调用方兼容,只豁免 Fast Refresh 的组件独占限制。 */ /* eslint-disable react-refresh/only-export-components */ import React, { createContext, useCallback, useContext, useEffect, useMemo, useState } from 'react' import type { CompanyProfile, ScheduleTask, SearchBatch, SearchConditions, WatchRecord, WatchStatus, } from '../types' import { emptyProfile, HISTORY_STATUSES } from '../types' import { PROJECTS } from '../data/projects' import type { Project } from '../types' import { api } from './api' // D1 档案与关注由后端保存;原型数据不自动迁移进真实数据库。 interface Persisted { profile: CompanyProfile watch: WatchRecord[] tasks: ScheduleTask[] batches: SearchBatch[] customTags: string[] customProjects: Project[] } function loadPersisted(): Persisted { // 不加载旧浏览器演示公司、账号私有数据或虚构关注。 return { profile: { ...emptyProfile }, watch: [], tasks: [], batches: [], customTags: [], customProjects: [] } } export function nowStr(): string { const d = new Date() const p = (n: number) => String(n).padStart(2, '0') return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}` } export function uid(prefix: string): string { return `${prefix}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 7)}` } // ---------- 检索逻辑(严格按用户条件执行,不做二次过滤/重排) ---------- export function runSearch(conditions: SearchConditions): string[] { const kw = conditions.keyword.trim().toLowerCase() const region = conditions.region.trim() const min = conditions.budgetMin.trim() === '' ? null : Number(conditions.budgetMin) const max = conditions.budgetMax.trim() === '' ? null : Number(conditions.budgetMax) const now = new Date() const rangeDays = conditions.publishRange === '7d' ? 7 : conditions.publishRange === '30d' ? 30 : conditions.publishRange === '90d' ? 90 : null return PROJECTS.filter(p => { if (kw) { const hay = [p.name, p.purchaser, p.region, ...p.keywords].join(' ').toLowerCase() // 多个关键词用空格分隔,需全部命中 const terms = kw.split(/\s+/) if (!terms.every(t => hay.includes(t))) return false } if (region && !p.region.includes(region)) return false if (min !== null || max !== null) { // 预算条件仅在用户明确设置时生效;未披露预算的项目无法判断,按不命中处理 if (p.budget === null) return false if (min !== null && p.budget < min) return false if (max !== null && p.budget > max) return false } if (rangeDays !== null) { const pub = new Date(p.publishDate) if ((now.getTime() - pub.getTime()) / 86400000 > rangeDays) return false } return true }).map(p => p.id) } export function conditionsText(c: SearchConditions): string { const parts: string[] = [] if (c.keyword.trim()) parts.push(`关键词「${c.keyword.trim()}」`) if (c.region.trim()) parts.push(`地区「${c.region.trim()}」`) if (c.budgetMin.trim() || c.budgetMax.trim()) { parts.push(`预算 ${c.budgetMin.trim() || '不限'} ~ ${c.budgetMax.trim() || '不限'} 万元`) } const rangeMap = { '7d': '近 7 天', '30d': '近 30 天', '90d': '近 90 天', all: '全部时间' } parts.push(`发布于${rangeMap[c.publishRange]}`) return parts.join(' · ') } // ---------- Context ---------- interface Store { profile: CompanyProfile saveProfile: (p: CompanyProfile) => Promise watch: WatchRecord[] refreshWatch: () => Promise addWatch: (projectId: string) => Promise removeWatch: (projectId: string) => Promise setWatchStatus: (projectId: string, status: WatchStatus) => void setWatchNote: (projectId: string, note: string) => void isWatched: (projectId: string) => boolean toggleWatchTag: (projectId: string, tag: string) => void customTags: string[] addCustomTag: (tag: string) => void removeCustomTag: (tag: string) => void customProjects: Project[] addCustomProject: (p: Project) => void findProject: (id: string) => Project | undefined tasks: ScheduleTask[] saveTask: (t: ScheduleTask) => void deleteTask: (id: string) => void runTaskNow: (id: string) => void batches: SearchBatch[] addBatch: (b: SearchBatch) => void } const StoreContext = createContext(null) export function StoreProvider({ children }: { children: React.ReactNode }) { const [state, setState] = useState(loadPersisted) const [ready, setReady] = useState(false) const [loadError, setLoadError] = useState('') useEffect(() => { let active = true Promise.all([api('/company-profile'), api('/watch')]) .then(([profile, watch]) => { if (!active) return setState(s => ({ ...s, profile: { ...emptyProfile, ...profile }, watch })) setReady(true) }).catch(error => { if (active) setLoadError(error.message) }) return () => { active = false } }, []) const saveProfile = useCallback(async (p: CompanyProfile) => { const saved = await api('/company-profile', { method: 'PUT', body: JSON.stringify(p) }) const profile = { ...emptyProfile, ...saved } setState(s => ({ ...s, profile })) return profile }, []) // 服务器确认后再更新共享计数,保存失败时不显示虚假的关注成功。 const refreshWatch = useCallback(async () => { const watch = await api('/watch') setState(s => ({ ...s, watch })) }, []) const addWatch = useCallback(async (projectId: string) => { await api(`/watch/${encodeURIComponent(projectId)}`, { method: 'POST' }) await refreshWatch() }, [refreshWatch]) const removeWatch = useCallback(async (projectId: string) => { await api(`/watch/${encodeURIComponent(projectId)}`, { method: 'DELETE' }) await refreshWatch() }, [refreshWatch]) const setWatchStatus = useCallback((projectId: string, status: WatchStatus) => { setState(s => ({ ...s, watch: s.watch.map(w => w.projectId === projectId && w.status !== status ? { ...w, status, history: [...w.history, { status, time: nowStr(), note: w.note }] } : w), })) }, []) const setWatchNote = useCallback((projectId: string, note: string) => { setState(s => ({ ...s, watch: s.watch.map(w => w.projectId === projectId ? { ...w, note } : w) })) }, []) const toggleWatchTag = useCallback((projectId: string, tag: string) => { setState(s => ({ ...s, watch: s.watch.map(w => { if (w.projectId !== projectId) return w const has = w.tags.includes(tag) return { ...w, tags: has ? w.tags.filter(t => t !== tag) : [...w.tags, tag] } }), })) }, []) const addCustomTag = useCallback((tag: string) => { setState(s => s.customTags.includes(tag) ? s : { ...s, customTags: [...s.customTags, tag] }) }, []) const removeCustomTag = useCallback((tag: string) => { setState(s => ({ ...s, customTags: s.customTags.filter(t => t !== tag), // 删除标签时同步从各项目上去掉,避免残留失效标签 watch: s.watch.map(w => w.tags.includes(tag) ? { ...w, tags: w.tags.filter(t => t !== tag) } : w), })) }, []) const addCustomProject = useCallback((p: Project) => { setState(s => { if (s.customProjects.some(x => x.id === p.id) || PROJECTS.some(x => x.id === p.id)) return s const rec: WatchRecord = { version: 1, projectId: p.id, status: '已关注', note: '', tags: [], createdAt: nowStr(), history: [{ status: '已关注', time: nowStr(), note: '' }], } const watch = s.watch.some(w => w.projectId === p.id) ? s.watch : [rec, ...s.watch] return { ...s, customProjects: [p, ...s.customProjects], watch } }) }, []) const saveTask = useCallback((t: ScheduleTask) => { setState(s => { const idx = s.tasks.findIndex(x => x.id === t.id) if (idx >= 0) { // 编辑不覆盖过去运行记录 const next = [...s.tasks] next[idx] = { ...t, runs: s.tasks[idx].runs } return { ...s, tasks: next } } return { ...s, tasks: [...s.tasks, t] } }) }, []) const deleteTask = useCallback((id: string) => { setState(s => ({ ...s, tasks: s.tasks.filter(t => t.id !== id) })) }, []) const runTaskNow = useCallback((id: string) => { setState(s => ({ ...s, tasks: s.tasks.map(t => { if (t.id !== id) return t const ids = runSearch(t.conditions) return { ...t, runs: [{ time: nowStr(), status: 'success' as const, count: ids.length }, ...t.runs] } }), })) }, []) const addBatch = useCallback((b: SearchBatch) => { setState(s => ({ ...s, batches: [b, ...s.batches].slice(0, 30) })) }, []) const value = useMemo(() => ({ profile: state.profile, saveProfile, watch: state.watch, refreshWatch, addWatch, removeWatch, setWatchStatus, setWatchNote, isWatched: (pid: string) => state.watch.some(w => w.projectId === pid), toggleWatchTag, customTags: state.customTags, addCustomTag, removeCustomTag, customProjects: state.customProjects, addCustomProject, findProject: (id: string) => state.customProjects.find(p => p.id === id) ?? PROJECTS.find(p => p.id === id), tasks: state.tasks, saveTask, deleteTask, runTaskNow, batches: state.batches, addBatch, }), [state, saveProfile, refreshWatch, addWatch, removeWatch, setWatchStatus, setWatchNote, toggleWatchTag, addCustomTag, removeCustomTag, addCustomProject, saveTask, deleteTask, runTaskNow, addBatch]) // 必须等真实档案加载后再挂载表单,避免空值覆盖已保存数据。 if (loadError) return
{loadError}
if (!ready) return
正在读取公司档案…
return {children} } export function useStore(): Store { const ctx = useContext(StoreContext) if (!ctx) throw new Error('useStore must be used within StoreProvider') return ctx } export function isHistoryStatus(s: WatchStatus): boolean { return (HISTORY_STATUSES as string[]).includes(s) }