import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { useNavigate } from 'react-router-dom'; import { requestAssistantChat } from '../copilot/assistantChatStream'; import { assistantProgressToolLabel } from '../i18n/assistantLabel'; import { FileText, ImagePlus, Keyboard, Loader2, MessageCircle, Mic, Plus, Send, Trash2, X } from 'lucide-react'; import { useAuth } from '../hooks/useAuth'; import { useServerVoiceRecording } from '../hooks/useServerVoiceRecording'; import { useMenuLayout } from '../hooks/useMenuLayout'; import { supabase } from '../supabase/client'; import { canShowOrderEntryIntakeFab, stashOrderEntryIntake } from './order/orderEntryIntake'; import { compressOrderRecognitionImage, isGeneralImageFile } from '../utils/imageFileLimits'; import { DateRangeFilterButton } from './ui/DateRangeFilterButton'; import { SearchableSelect } from './ui/SearchableSelect'; import { buildInvoiceAllocations } from './finance/StatementInvoiceUploadBox'; import { fetchCustomerInvoicesApi, fetchInvoiceStatementLinksApi, fetchInvoicesApi, ocrInvoiceApi, saveCustomerInvoiceApi, saveInvoiceApi, uploadInvoiceFileApi, type InvoiceOcrResult, } from '../utils/supplierInvoiceApi'; import { attachCustomerInvoiceStatus, attachSupplierInvoiceStatus, isCustomerInvoicePoolStatement, } from '../utils/statementInvoiceStatus'; import { defaultStatementDateRange } from '../utils/statements'; import { listCustomerStatementsApi, listSupplierStatementsApi } from '../utils/workflowApi'; import { isSupplierInvoiceFile, isSupplierInvoiceImage, isSupplierInvoicePdf, prepareSupplierInvoiceFile, } from '../utils/supplierInvoiceFile'; import { filterRuntimeMenuByAccess, flattenVisiblePages } from '../utils/menuAccessFilter'; import { applySetFields, getCopilotSnapshot, runPageAction, waitForCopilotPath } from '../copilot/copilotPageBus'; import { buildApiUrl } from '../lib/apiConfig'; import { readAuthSessionRaw } from '../lib/authSession'; import { getOperatingBranchHeader, readOperatingBranchCode } from '../utils/operatingBranch'; import { useI18n } from '../i18n/I18nProvider'; import { assistantColumnLabel, assistantQueryTitle } from '../i18n/assistantLabel'; import { confirmDialog } from '../utils/confirmDialog'; export { canShowOrderEntryIntakeFab } from './order/orderEntryIntake'; type ChatRole = 'user' | 'assistant'; type ToolTraceItem = { name: string; ok: boolean; summary: string }; type ChatMessage = { role: ChatRole; content: string; toolTrace?: ToolTraceItem[]; shellNotes?: string[] }; const TOOL_LABELS: Record = { list_orders: '查询订单', list_self_purchases: '查询自采', list_preparations: '查询备货', list_pages: '列出功能页', list_customers: '列出客户', open_page: '打开页面', open_self_purchase: '打开采购管理', open_supplier_prep: '打开备货表', set_page_fields: '改页筛选', run_page_action: '执行页操作', describe_page: '查看当前页', get_current_time: '当前时间', get_order_detail: '订单详情', prepare_order_edit: '改订单明细', list_customer_directory: '查询客户档案', list_after_sales: '查询售后', open_after_sales: '打开售后管理', get_after_sale_order_context: '售后订单上下文', create_after_sale: '新建售后', accept_after_sale: '受理售后', reject_after_sale: '驳回售后', handle_after_sale: '处理售后', complete_preparation: '完成备货', upload_customer_invoice: '上传客户发票', upload_supplier_invoice: '上传供应商发票', }; type InvoicePartyKind = 'customer' | 'supplier'; type InvoicePendingSave = { party: InvoicePartyKind; partyCode: string; partyName: string; file: File; storedPath: string | null; invoiceNo: string; invoiceDate: string | null; amount: number; taxRate: number | null; taxAmount: number | null; ocr: InvoiceOcrResult; allocations: Array<{ statement_no: string; amount: number }>; }; const SUPPLIER_INVOICE_LOOKBACK_FROM = '2020-01-01'; type QueryPayload = { capability?: string; title?: string; summary?: string; count?: number; total_amount?: number; date_from?: string; date_to?: string; search?: string; page?: number; page_size?: number; browse_id?: string; has_date?: boolean; has_search?: boolean; columns?: string[]; rows?: Array>; }; type OrderDraftRow = { client_id: string; id?: string; sku_code: string; item_name: string; category_code: string; category_name?: string; quantity: string; unit: string; sale_price: string; processing_method?: string; processing_owner?: string; supplier_code?: string; is_extra_dish?: boolean; remark?: string; highlighted?: boolean; removed?: boolean; }; type PreviewPayload = { action_type?: string; capability?: string; target_type?: string; target_id?: string; summary?: string; diff?: Array<{ field?: string; before?: unknown; after?: unknown }>; impact?: string; draft?: { kind?: string; order_code?: string; rows?: Array>; }; }; type PickPayload = { pick_id?: string; slot?: string; prompt?: string; options?: Array<{ id?: string; label?: string }>; }; function lastNeedConfirmAction(trace?: ToolTraceItem[]): string | null { const row = [...(trace || [])].reverse().find((item) => !item.ok && /确认|need_confirm/.test(item.summary || '')); return row?.name || null; } function failedToolTrace(trace?: ToolTraceItem[]): ToolTraceItem[] | undefined { const failed = (trace || []).filter((row) => !row.ok); return failed.length ? failed : undefined; } function asDraftRows(preview: PreviewPayload | null): OrderDraftRow[] { const rows = preview?.draft?.kind === 'order_items' ? preview.draft.rows || [] : []; return rows.map((row, index) => { const id = String(row.id || '').trim(); return { client_id: id || `tmp-${index}`, id: id || undefined, sku_code: String(row.sku_code || ''), item_name: String(row.item_name || ''), category_code: String(row.category_code || ''), category_name: String(row.category_name || ''), quantity: row.quantity == null ? '' : String(row.quantity), unit: String(row.unit || ''), sale_price: row.sale_price == null ? '' : String(row.sale_price), processing_method: row.processing_method != null ? String(row.processing_method) : undefined, processing_owner: row.processing_owner != null ? String(row.processing_owner) : undefined, supplier_code: row.supplier_code != null ? String(row.supplier_code) : undefined, is_extra_dish: Boolean(row.is_extra_dish), remark: row.remark != null ? String(row.remark) : undefined, highlighted: Boolean(row.highlighted), removed: Boolean(row.removed), }; }); } function draftRowsToConfirmItems(rows: OrderDraftRow[]) { return rows.map((row, index) => ({ id: row.id || `tmp-${index}`, sku_code: row.sku_code.trim() || null, item_name: row.item_name.trim() || null, category_code: row.category_code.trim() || null, category_name: row.category_name || null, quantity: row.quantity === '' ? 0 : Number(row.quantity), unit: row.unit || null, price: row.sale_price === '' ? 0 : Number(row.sale_price), processing_method: row.processing_method || null, processing_owner: row.processing_owner || null, supplier_code: row.supplier_code || null, is_extra_dish: Boolean(row.is_extra_dish), remark: row.remark || null, is_returned: Boolean(row.removed), })); } function toolLabel(name: string): string { return TOOL_LABELS[name] || name; } /** * P2b-7 流式进度标签:先用既有 TOOL_LABELS(界面本来就在工具轨迹里显示这套名字), * 再用 `assistant.progress.tool.*`(2026-09-23 按开发者要求补齐 25 个工具,三语同步)。 * 仅用于助手自己的进度行;两者都没有则空串 —— 宁可不显示名字,也不露裸工具名。 */ function progressLabelFor(name: string, t: (key: string) => string): string { const raw = String(name || '').replace(/^plan:/, ''); return TOOL_LABELS[raw] || assistantProgressToolLabel(t, raw); } type UiAction = { type: string; path?: string; label?: string; web?: { path?: string }; miniprogram?: { page?: string }; customer_code?: string; items?: unknown[]; text?: string; patches?: Array<{ name?: string; value?: unknown; item_id?: string; sku_name?: string }>; action_id?: string; payload?: QueryPayload & PreviewPayload & PickPayload; }; function asText(value: unknown): string { if (value == null || value === '') return '—'; if (typeof value === 'string') { const text = value.trim(); if (/^(https?:\/\/|data:|blob:)/i.test(text) || /\.(jpe?g|png|gif|webp|bmp|pdf)(\?|#|$)/i.test(text)) { return '—'; } } if (typeof value === 'object') return JSON.stringify(value); return String(value); } const WELCOME = '说明你要查或要做的事即可。缺客户、路径等信息我会问你;写操作(如下单)必须你确认。'; function authHeaders(): Record { const headers: Record = { 'Content-Type': 'application/json', ...getOperatingBranchHeader(), }; try { const raw = readAuthSessionRaw(); if (raw) { const session = JSON.parse(raw); if (session?.access_token) headers.Authorization = `Bearer ${session.access_token}`; } } catch { // ignore } return headers; } export const OrderEntryIntakeFab: React.FC = () => { const { hasRole, hasPermission, user, profile } = useAuth(); /** 助手「+」里客户/供应商发票上传入口:仅 admin(设计 20260923-assistant-upload-admin-only) */ const canOpenStatementInvoice = hasRole('admin'); const { menuItems } = useMenuLayout(); const { t, locale } = useI18n(); const navigate = useNavigate(); const visible = canShowOrderEntryIntakeFab(hasRole, hasPermission); const visiblePages = useMemo( () => flattenVisiblePages(filterRuntimeMenuByAccess(menuItems, hasPermission, hasRole)), [menuItems, hasPermission, hasRole] ); const [hintModule, setHintModule] = useState(null); const sessionIdRef = useRef(''); /** * 会话代次:切换会话(新对话 / 打开历史)时自增。 * 任何异步响应(历史加载、/chat、/confirm)回来前先比对,过期一律丢弃 —— * 否则过期响应会覆盖 session_id、把消息串进新会话、并把旧 ui_actions 作用到当前页面。 * 见 .cursor/rules/frontend-ui-discipline.mdc(generation + 实体 id;订单详情事故 20260911)。 */ const conversationGen = useRef(0); const [open, setOpen] = useState(false); const [messages, setMessages] = useState([{ role: 'assistant', content: WELCOME }]); const [input, setInput] = useState(''); const [imageDataUrl, setImageDataUrl] = useState(null); const [invoiceKind, setInvoiceKind] = useState(null); const [invoicePartyCode, setInvoicePartyCode] = useState(''); const [invoicePartyOptions, setInvoicePartyOptions] = useState>([]); const invoicePartyCodeRef = useRef(''); const [invoiceDateRange, setInvoiceDateRange] = useState<{ start: string; end: string } | null>(null); const invoiceDateRangeRef = useRef<{ start: string; end: string } | null>(null); const [invoicePreview, setInvoicePreview] = useState<{ party: InvoicePartyKind; fileName: string; imageUrl: string | null; } | null>(null); const [loading, setLoading] = useState(false); /** P2b-7:流式进度标签(只展示既有 TOOL_LABELS 里的中文名,最多保留最近 4 个)。 */ const [progressLabels, setProgressLabels] = useState([]); const [error, setError] = useState(''); const [pendingConfirmId, setPendingConfirmId] = useState(null); const [queryCard, setQueryCard] = useState(null); const [querySearch, setQuerySearch] = useState(''); const [queryBrowseBusy, setQueryBrowseBusy] = useState(false); const browseGen = useRef(0); const querySearchTimer = useRef | null>(null); const [pickCard, setPickCard] = useState(null); const [pickFilter, setPickFilter] = useState(''); const [changePreview, setChangePreview] = useState(null); const [draftRows, setDraftRows] = useState([]); const [voucherError, setVoucherError] = useState(''); const [plusOpen, setPlusOpen] = useState(false); const [voiceMode, setVoiceMode] = useState(false); const [conversations, setConversations] = useState>([]); const [activeConversationId, setActiveConversationId] = useState(''); const fileInputRef = useRef(null); const customerInvoiceInputRef = useRef(null); const supplierInvoiceInputRef = useRef(null); const invoiceOcrGen = useRef(0); const invoicePendingRef = useRef(null); const listRef = useRef(null); const holdLockRef = useRef(false); const { isRecording, isTranscribing, error: voiceError, isSupported: isVoiceSupported, startRecording, stopRecording, } = useServerVoiceRecording({ onAudioReady: async ({ audioBase64, audioFormat }) => { const { data: result, error: transcribeError } = await supabase.functions.invoke('transcribe-audio', { body: { audioBase64, audioFormat }, }); if (transcribeError) throw new Error(transcribeError.message || '语音识别失败'); const spoken = String(result?.text || '').trim(); if (!spoken) throw new Error('未识别到语音,请重试'); setInput((prev) => (prev.trim() ? `${prev.trim()} ${spoken}` : spoken)); setVoiceMode(false); setError(''); }, onError: (message) => setError(message), }); const applyRestoredMessages = (id: string, rows: Array<{ role?: string; content?: string }>) => { const restored = (rows || []) .map((row) => ({ role: row.role === 'assistant' ? ('assistant' as const) : ('user' as const), content: String(row.content || '').trim(), })) .filter((row) => row.content); sessionIdRef.current = id; setActiveConversationId(id); setMessages(restored.length ? restored : [{ role: 'assistant', content: WELCOME }]); }; const fetchConversationMessages = async (id: string, gen: number) => { const msgRes = await fetch( buildApiUrl(`/mcp/order-entry/conversations/${encodeURIComponent(id)}/messages`), { headers: authHeaders() } ); const msgData = (await msgRes.json().catch(() => ({}))) as { messages?: Array<{ role?: string; content?: string }>; }; if (gen !== conversationGen.current) return; applyRestoredMessages(id, msgData.messages || []); }; const fetchConversationList = async () => { const listRes = await fetch(buildApiUrl('/mcp/order-entry/conversations?surface=web&client=web'), { headers: authHeaders(), }); const listData = (await listRes.json().catch(() => ({}))) as { conversations?: Array<{ id?: string; title?: string; updated_at?: string }>; }; return (listData.conversations || []) .map((row) => ({ id: String(row.id || '').trim(), title: String(row.title || '').trim(), updated_at: String(row.updated_at || ''), })) .filter((row) => row.id); }; const loadLatestConversation = async () => { const gen = ++conversationGen.current; try { const rows = await fetchConversationList(); if (gen !== conversationGen.current) return; setConversations(rows); const latestId = rows[0]?.id || ''; if (!latestId) { sessionIdRef.current = ''; setActiveConversationId(''); setMessages([{ role: 'assistant', content: WELCOME }]); return; } await fetchConversationMessages(latestId, gen); } catch { if (gen !== conversationGen.current) return; } }; useEffect(() => { conversationGen.current += 1; invoiceOcrGen.current += 1; invoicePendingRef.current = null; sessionIdRef.current = ''; setActiveConversationId(''); setConversations([]); setInvoicePreview(null); setInvoiceKind(null); setInvoicePartyCode(''); invoicePartyCodeRef.current = ''; setInvoicePartyOptions([]); setInvoiceDateRange(null); invoiceDateRangeRef.current = null; setMessages([{ role: 'assistant', content: WELCOME }]); }, [user?.id, profile?.branch_code]); useEffect( () => () => { if (querySearchTimer.current) clearTimeout(querySearchTimer.current); }, [] ); useEffect(() => { if (!open) return; listRef.current?.scrollTo({ top: listRef.current.scrollHeight }); }, [open, messages, loading]); useEffect(() => { setDraftRows(asDraftRows(changePreview)); setVoucherError(''); }, [changePreview]); useEffect(() => { if (voiceError) setError(voiceError); }, [voiceError]); const canSend = Boolean(input.trim() || imageDataUrl); const beginHoldTalk = async (e: React.PointerEvent) => { if (!isVoiceSupported || loading || isTranscribing) return; e.preventDefault(); holdLockRef.current = true; (e.currentTarget as HTMLElement).setPointerCapture(e.pointerId); await startRecording(); }; const endHoldTalk = (e: React.PointerEvent) => { if (!holdLockRef.current) return; holdLockRef.current = false; try { (e.currentTarget as HTMLElement).releasePointerCapture(e.pointerId); } catch { // ignore } stopRecording(); }; const onPickImage = async (file: File | undefined) => { if (!file) return; if (!isGeneralImageFile(file)) { setError('仅支持 JPG、PNG、WEBP 图片'); return; } try { setError(''); invoiceOcrGen.current += 1; invoicePendingRef.current = null; setInvoicePreview(null); setImageDataUrl(await compressOrderRecognitionImage(file)); } catch (err) { setError(err instanceof Error ? err.message : '图片处理失败'); } }; const clearAssistantImage = () => { setImageDataUrl(null); if (fileInputRef.current) fileInputRef.current.value = ''; }; const clearInvoiceAttach = () => { invoiceOcrGen.current += 1; invoicePendingRef.current = null; setInvoicePreview(null); }; const presentInvoiceConfirm = (draft: InvoicePendingSave) => { const capability = draft.party === 'customer' ? 'upload_customer_invoice' : 'upload_supplier_invoice'; invoicePendingRef.current = draft; setPendingConfirmId(capability); setChangePreview({ action_type: 'create', capability, target_type: draft.party === 'customer' ? 'customer' : 'supplier', target_id: draft.partyCode, summary: `${draft.party === 'customer' ? '客户' : '供应商'}发票 ${draft.invoiceNo}`, diff: [ { field: draft.party === 'customer' ? '客户' : '供应商', after: `${draft.partyName}(${draft.partyCode})`, }, { field: '发票号', after: draft.invoiceNo }, { field: '金额', after: draft.amount }, { field: '开票日期', after: draft.invoiceDate || '' }, { field: '结算区间', after: invoiceDateRangeRef.current ? `${invoiceDateRangeRef.current.start} ~ ${invoiceDateRangeRef.current.end}` : '', }, ], }); }; const loadInvoicePartyOptions = async (kind: InvoicePartyKind) => { const table = kind === 'customer' ? 'customers' : 'suppliers'; const codeCol = kind === 'customer' ? 'customer_code' : 'supplier_code'; const { data, error: loadError } = await supabase.from(table).select(`${codeCol}, company_name`).order('company_name'); if (loadError) throw new Error(loadError.message || '加载主体失败'); setInvoicePartyOptions( (data || []).map((row: Record) => { const value = String(row[codeCol] || ''); const label = String(row.company_name || value); return { value, label, searchText: `${label} ${value}` }; }) ); }; const releaseInvoiceFocus = () => { const active = document.activeElement; if (active instanceof HTMLElement) active.blur(); }; const openInvoiceFilePicker = (kind: InvoicePartyKind) => { const range = invoiceDateRangeRef.current; if (!range?.start || !range?.end) { setError(t('finance.invoiceUpload.needDate')); return; } if (!invoicePartyCodeRef.current) { setError( kind === 'customer' ? t('finance.invoiceUpload.needPartyCustomer') : t('finance.invoiceUpload.needPartySupplier') ); return; } setError(''); releaseInvoiceFocus(); (kind === 'customer' ? customerInvoiceInputRef : supplierInvoiceInputRef).current?.click(); }; const loadInvoiceAllocations = async ( party: InvoicePartyKind, partyCode: string, amount: number ): Promise> => { const range = invoiceDateRangeRef.current; if (!range?.start || !range?.end) throw new Error(t('finance.invoiceUpload.needDate')); if (party === 'customer') { const { data } = await listCustomerStatementsApi({ date_from: range.start, date_to: range.end, date_field: 'delivery_date', customer_code: partyCode, limit: 2000, }); const visible = (data || []).filter((row) => String(row.customer_code || '') === partyCode); const [invoices, links] = await Promise.all([ fetchCustomerInvoicesApi().catch(() => []), fetchInvoiceStatementLinksApi('customer').catch(() => []), ]); const boundInvoiceIds = new Set(links.map((link) => link.invoice_id)); const legacyInvoices = invoices.filter((inv) => !boundInvoiceIds.has(String(inv.id || ''))); const boundCover = new Map(); for (const link of links) { boundCover.set(link.statement_no, (boundCover.get(link.statement_no) || 0) + Number(link.amount || 0)); } const rows = attachCustomerInvoiceStatus(visible, legacyInvoices, visible, boundCover); const targets = [...rows] .filter((row) => isCustomerInvoicePoolStatement(row)) .sort((a, b) => `${a.cycle_code || ''}|${a.statement_no}`.localeCompare(`${b.cycle_code || ''}|${b.statement_no}`) ) .map((row) => ({ statement_no: row.statement_no, remaining: Number(row.invoice_remaining) || 0, })); return buildInvoiceAllocations(targets, amount); } const { data } = await listSupplierStatementsApi({ date_from: range.start, date_to: range.end, date_field: 'delivery_date', supplier_code: partyCode, limit: 2000, }); const visible = (data || []).filter((row) => String(row.supplier_code || '') === partyCode); let allocateRows = visible; if (range.end && visible.length) { try { const { data: prior } = await listSupplierStatementsApi({ date_from: SUPPLIER_INVOICE_LOOKBACK_FROM, date_to: range.end, date_field: 'delivery_date', supplier_code: partyCode, limit: 2000, }); const byNo = new Map(visible.map((row) => [row.statement_no, row])); for (const row of prior || []) { if (String(row.supplier_code || '') !== partyCode || byNo.has(row.statement_no)) continue; byNo.set(row.statement_no, row); } allocateRows = [...byNo.values()]; } catch { allocateRows = visible; } } const [invoices, links] = await Promise.all([ fetchInvoicesApi() .then((rows) => rows.filter((inv) => String(inv.invoice_type || 'supplier') === 'supplier')) .catch(() => []), fetchInvoiceStatementLinksApi('supplier').catch(() => []), ]); const boundInvoiceIds = new Set(links.map((link) => link.invoice_id)); const legacyInvoices = invoices.filter((inv) => !boundInvoiceIds.has(String(inv.id || ''))); const boundCover = new Map(); for (const link of links) { boundCover.set(link.statement_no, (boundCover.get(link.statement_no) || 0) + Number(link.amount || 0)); } const rows = attachSupplierInvoiceStatus(visible, legacyInvoices, allocateRows, boundCover); const targets = [...rows] .sort((a, b) => `${a.cycle_code || ''}|${a.statement_no}`.localeCompare(`${b.cycle_code || ''}|${b.statement_no}`) ) .map((row) => ({ statement_no: row.statement_no, remaining: Number(row.invoice_remaining) || 0, })); return buildInvoiceAllocations(targets, amount); }; const startInvoiceFlow = async (kind: InvoicePartyKind) => { if (!canOpenStatementInvoice || loading) return; setPlusOpen(false); setError(''); if (invoiceKind !== kind) { setInvoicePartyCode(''); invoicePartyCodeRef.current = ''; setInvoicePartyOptions([]); } if (!invoiceDateRangeRef.current) { const fallback = defaultStatementDateRange(); const next = { start: fallback.date_from, end: fallback.date_to }; invoiceDateRangeRef.current = next; setInvoiceDateRange(next); } setInvoiceKind(kind); try { await loadInvoicePartyOptions(kind); } catch (err) { setError(err instanceof Error ? err.message : '加载主体失败'); return; } if (invoicePartyCodeRef.current) { openInvoiceFilePicker(kind); } }; const onInvoicePartyChange = (code: string) => { setInvoicePartyCode(code); invoicePartyCodeRef.current = code; if (!code || !invoiceKind) return; openInvoiceFilePicker(invoiceKind); }; const cancelInvoiceParty = () => { invoiceOcrGen.current += 1; invoicePendingRef.current = null; setInvoicePreview(null); setInvoicePartyCode(''); invoicePartyCodeRef.current = ''; setInvoiceKind(null); setInvoicePartyOptions([]); setInvoiceDateRange(null); invoiceDateRangeRef.current = null; closePreview(); }; const onPickInvoice = async (party: InvoicePartyKind, file: File | undefined) => { if (!file || !canOpenStatementInvoice || loading) return; if (!isSupplierInvoiceFile(file)) { setError('仅支持 PDF 或图片发票'); return; } const partyCode = invoiceKind === party ? invoicePartyCodeRef.current : ''; const partyName = invoicePartyOptions.find((row) => row.value === partyCode)?.label || partyCode; const range = invoiceDateRangeRef.current; if (!range?.start || !range?.end) { setError(t('finance.invoiceUpload.needDate')); return; } if (!partyCode) { setError( party === 'customer' ? t('finance.invoiceUpload.needPartyCustomer') : t('finance.invoiceUpload.needPartySupplier') ); return; } const ocrGen = ++invoiceOcrGen.current; invoicePendingRef.current = null; setImageDataUrl(null); setError(''); setPlusOpen(false); setLoading(true); try { const prepared = await prepareSupplierInvoiceFile(file); if (ocrGen !== invoiceOcrGen.current) return; let storedPath: string | null = null; let imageUrl: string | null = null; let result: InvoiceOcrResult | null = null; if (isSupplierInvoicePdf(prepared)) { storedPath = await uploadInvoiceFileApi( prepared, party === 'customer' ? 'customer-invoices' : undefined ); if (ocrGen !== invoiceOcrGen.current) return; result = await ocrInvoiceApi({ path: storedPath }); } else if (isSupplierInvoiceImage(prepared)) { imageUrl = await new Promise((resolve, reject) => { const reader = new FileReader(); reader.onload = () => resolve(String(reader.result || '')); reader.onerror = () => reject(new Error('读取发票失败')); reader.readAsDataURL(prepared); }); if (ocrGen !== invoiceOcrGen.current) return; result = await ocrInvoiceApi({ imageBase64: imageUrl }); } if (ocrGen !== invoiceOcrGen.current) return; setInvoicePreview({ party, fileName: prepared.name, imageUrl }); if (!result) { setError(t('finance.supplierStmt.toastOcrFail')); return; } const invoiceNo = String(result.invoice_no || '').trim(); const amount = Number(result.total_amount ?? result.amount ?? 0); const invoiceDate = result.invoice_date && /^\d{4}-\d{2}-\d{2}$/.test(result.invoice_date) ? result.invoice_date : null; if (!invoiceNo) { setError(t('finance.supplierStmt.toastNeedInvoiceNo')); return; } if (!Number.isFinite(amount) || amount <= 0) { setError(t('finance.supplierStmt.toastNeedAmount')); return; } const allocations = await loadInvoiceAllocations(party, partyCode, amount); if (ocrGen !== invoiceOcrGen.current) return; if (!allocations.length) { setError(t('finance.invoiceUpload.bindEmpty')); return; } presentInvoiceConfirm({ party, partyCode, partyName, file: prepared, storedPath, invoiceNo, invoiceDate, amount, taxRate: result.tax_rate, taxAmount: result.tax_amount, ocr: result, allocations, }); } catch (err) { if (ocrGen !== invoiceOcrGen.current) return; setError(err instanceof Error ? err.message : '发票识别失败'); } finally { if (ocrGen === invoiceOcrGen.current) { setLoading(false); setProgressLabels([]); } } }; const parseIntake = async (customerCode: string, extraText?: string) => { const body: Record = { customerCode, includeParseCategory: true, }; if (imageDataUrl) { body.imageBase64 = imageDataUrl.split(',')[1] || imageDataUrl; } else { const text = (extraText || input).trim(); if (!text) throw new Error('请输入订单内容或上传图片'); body.text = text; } const { data: result, error: parseError } = await supabase.functions.invoke('parse-order-three-layer', { body, }); if (parseError) throw new Error(parseError.message || '解析失败'); if (!result?.items?.length) { throw new Error(result?.message || '未识别到商品,请重试或手动录入'); } stashOrderEntryIntake({ customer_code: customerCode, items: result.items, imageDataUrl: imageDataUrl || undefined, sourceText: extraText || input.trim() || undefined, }); window.dispatchEvent(new Event('order-entry-intake')); navigate('/customer-order', { state: { intakeNonce: Date.now() } }); clearAssistantImage(); return result.items.length as number; }; const applyPickedOption = async (option: { id: string; label: string }) => { if (loading || !pickCard?.pick_id || !option.id || !sessionIdRef.current) return; const gen = conversationGen.current; const pickId = pickCard.pick_id; const slot = String(pickCard.slot || ''); const withImage = Boolean(imageDataUrl); let follow: string | null = null; setLoading(true); setError(''); try { const res = await fetch(buildApiUrl('/mcp/order-entry/pick'), { method: 'POST', headers: authHeaders(), body: JSON.stringify({ client: 'web', session_id: sessionIdRef.current, pick_id: pickId, id: option.id, }), }); const data = (await res.json().catch(() => ({}))) as { ok?: boolean; slot?: string; id?: string; error_description?: string; }; if (gen !== conversationGen.current) return; if (!res.ok || !data.ok) { throw new Error(data.error_description || t('assistant.pick.failed')); } setPickCard(null); setPickFilter(''); const chosenSlot = data.slot || slot; const chosenId = data.id || option.id; if (chosenSlot === 'customer_code' && withImage) { const count = await parseIntake(chosenId); if (gen !== conversationGen.current) return; setMessages((prev) => [ ...prev, { role: 'assistant', content: `已识别 ${count} 行到录单页,尚未下单` }, ]); return; } follow = chosenSlot === 'customer_code' ? `客户 ${option.label}(${option.id})` : `${option.label}(${option.id})`; } catch (err) { if (gen !== conversationGen.current) return; setError(err instanceof Error ? err.message : t('assistant.pick.failed')); } finally { if (gen === conversationGen.current) setLoading(false); } if (follow && gen === conversationGen.current) { await send({ text: follow }); } }; const runUiActions = async (actions: UiAction[]) => { const notes: string[] = []; let lastNav: UiAction | undefined; for (let i = actions.length - 1; i >= 0; i -= 1) { if (actions[i].type === 'navigate') { lastNav = actions[i]; break; } } const rest = actions.filter( (action) => action.type !== 'navigate' && action.type !== 'show_query' && action.type !== 'request_pick' && action.type !== 'preview_change' ); const queued: UiAction[] = lastNav ? [lastNav, ...rest] : rest; for (const action of queued) { if (action.type === 'navigate') { const path = action.web?.path || action.path; if (!path) continue; const allowed = visiblePages.some((page) => page.path === path); if (!allowed) { notes.push(`无权打开 ${path}`); continue; } navigate(path); const ready = await waitForCopilotPath(path); notes.push(`已打开 ${action.label || path}${ready ? '' : '(页面控件尚未就绪)'}`); } else if (action.type === 'replace_items' && action.customer_code && action.items?.length) { stashOrderEntryIntake({ customer_code: action.customer_code, items: action.items, imageDataUrl: imageDataUrl || undefined, sourceText: input.trim() || undefined, }); window.dispatchEvent(new Event('order-entry-intake')); navigate('/customer-order', { state: { intakeNonce: Date.now() } }); notes.push(`已灌入 ${action.items.length} 行到录单页,尚未下单`); } else if (action.type === 'parse_intake' && action.customer_code) { const count = await parseIntake(action.customer_code, action.text); notes.push(`已识别 ${count} 行到录单页,尚未下单`); } else if (action.type === 'set_fields' && action.patches?.length) { const result = await applySetFields( action.patches.map((row) => ({ name: String(row.name || ''), value: row.value, item_id: row.item_id, sku_name: row.sku_name, })) ); notes.push(result.ok ? '已更新当前页' : result.error || '改字段失败'); } else if (action.type === 'run_action' && action.action_id) { const result = await runPageAction(action.action_id, action.payload); notes.push( result.ok ? action.action_id === 'request_commit' ? '请在页面确认提交' : '已执行页面操作' : result.error || '页面操作失败' ); } } return notes; }; const browseQuery = async (patch: Record) => { const browseId = queryCard?.browse_id; if (!browseId || !sessionIdRef.current || queryBrowseBusy) return; const gen = ++browseGen.current; setQueryBrowseBusy(true); setError(''); try { const res = await fetch(buildApiUrl('/mcp/order-entry/browse'), { method: 'POST', headers: authHeaders(), body: JSON.stringify({ client: 'web', session_id: sessionIdRef.current, browse_id: browseId, ...patch, }), }); const data = (await res.json().catch(() => ({}))) as { ok?: boolean; query?: QueryPayload; error_description?: string; }; if (gen !== browseGen.current) return; if (!res.ok || !data.ok || !data.query) { throw new Error(data.error_description || t('assistant.emptyRows')); } setQueryCard(data.query); if (data.query.search != null) setQuerySearch(String(data.query.search)); } catch (err) { if (gen !== browseGen.current) return; setError(err instanceof Error ? err.message : t('assistant.emptyRows')); } finally { if (gen === browseGen.current) setQueryBrowseBusy(false); } }; const send = async (override?: { text: string; confirmedActionId?: string }) => { const text = override?.text ?? input.trim(); if (loading) return; const gen = conversationGen.current; if (!override && !text && !imageDataUrl) { setError('请输入问题、点菜单或上传图片'); return; } if (missingOperatingBranch()) { setError(t('assistant.branchRequired')); return; } if (!text && !imageDataUrl) return; setLoading(true); setProgressLabels([]); setError(''); const userText = override ? text : imageDataUrl ? `${text || '请按附图点菜单识别灌入录单页'}(已附点菜单图片)` : text; const nextMessages = [...messages, { role: 'user' as const, content: userText }]; setMessages(nextMessages); if (!override) setInput(''); try { if (!sessionIdRef.current) { sessionIdRef.current = typeof crypto !== 'undefined' && crypto.randomUUID ? crypto.randomUUID() : `sess-${Date.now()}`; setActiveConversationId(sessionIdRef.current); } // P2b-7:优先 SSE(能实时显示进度),任何异常自动回退非流式 /chat(弱网/老代理行为不变) const { payload } = await requestAssistantChat({ apiUrl: buildApiUrl, headers: authHeaders(), body: { client: 'web', session_id: sessionIdRef.current, hint_module: hintModule, text: userText, visible_pages: visiblePages, snapshot: getCopilotSnapshot(), locale, }, onProgress: (event) => { if (gen !== conversationGen.current) return; // 过期进度不得写入 const name = typeof event.name === 'string' ? event.name : ''; if (!name) return; const label = progressLabelFor(name, t); if (!label) return; setProgressLabels((prev) => (prev.includes(label) ? prev : [...prev, label].slice(-4))); }, }); if (gen !== conversationGen.current) return; // 会话已切换:丢弃过期响应 const data = payload as { reply?: string; session_id?: string; error_description?: string; error?: string; ui_actions?: UiAction[]; modules?: string[]; tool_trace?: ToolTraceItem[]; }; if (gen !== conversationGen.current) return; if (data.session_id) { sessionIdRef.current = data.session_id; setActiveConversationId(data.session_id); } void fetchConversationList() .then((rows) => { if (gen === conversationGen.current) setConversations(rows); }) .catch(() => undefined); if (data.modules?.[0]) setHintModule(data.modules[0]); const actions = data.ui_actions || []; const query = actions.find((row) => row.type === 'show_query')?.payload || null; const pick = actions.find((row) => row.type === 'request_pick')?.payload || null; const preview = actions.find((row) => row.type === 'preview_change')?.payload || null; setQueryCard(query && (query.rows?.length || query.summary || query.browse_id) ? query : null); setQuerySearch(query?.search ? String(query.search) : ''); browseGen.current += 1; setPickCard(pick && pick.pick_id && pick.options?.length ? pick : null); setPickFilter(''); setChangePreview(preview && preview.capability ? preview : null); const notes = await runUiActions(actions); setPendingConfirmId(preview?.capability || lastNeedConfirmAction(data.tool_trace)); setMessages((prev) => [ ...prev, { role: 'assistant', content: data.reply || (notes.length ? '' : '已处理。'), toolTrace: failedToolTrace(data.tool_trace), shellNotes: notes.length ? notes : undefined, }, ]); } catch (err) { if (gen !== conversationGen.current) return; setError(err instanceof Error ? err.message : '助手失败'); setMessages((prev) => [...prev, { role: 'assistant', content: err instanceof Error ? err.message : '助手失败' }]); } finally { if (gen === conversationGen.current) { setLoading(false); setProgressLabels([]); clearAssistantImage(); } } }; const closePreview = () => { invoicePendingRef.current = null; setChangePreview(null); setPendingConfirmId(null); setVoucherError(''); setDraftRows([]); }; const cancelPreview = async () => { const localInvoice = Boolean( changePreview?.capability === 'upload_customer_invoice' || changePreview?.capability === 'upload_supplier_invoice' ); closePreview(); if (localInvoice || !sessionIdRef.current) return; try { await fetch(buildApiUrl('/mcp/order-entry/confirm'), { method: 'POST', headers: authHeaders(), body: JSON.stringify({ client: 'web', session_id: sessionIdRef.current, cancel: true }), }); } catch { // ignore } }; /** * 超管必须先选「操作分公司」:助手的作用域(租户 schema / 取数过滤 / LLM 配置 / 落库) * 全部取操作分公司,缺失时服务端会 400 branch_required —— 这里先拦一次,省一次往返。 * 普通账号不写 operating branch(useAuth 会清空),因此不能对他们做这个检查。 */ const missingOperatingBranch = () => hasRole(['super_admin']) && !readOperatingBranchCode(); const deleteConversation = async (id: string) => { if (!id) return; const ok = await confirmDialog({ message: t('assistant.history.deleteConfirm'), danger: true, }); if (!ok) return; try { const res = await fetch(buildApiUrl(`/mcp/order-entry/conversations/${encodeURIComponent(id)}`), { method: 'DELETE', headers: authHeaders(), }); if (!res.ok) { const data = (await res.json().catch(() => ({}))) as { error_description?: string }; throw new Error(data.error_description || t('assistant.history.deleteFailed')); } if (id === sessionIdRef.current) { // 删的是当前会话:直接开新会话(列表与进行中的请求都会被重置) startNewConversation(); return; } const rows = await fetchConversationList(); setConversations(rows); } catch (err) { setError(err instanceof Error ? err.message : t('assistant.history.deleteFailed')); } }; const startNewConversation = () => { conversationGen.current += 1; invoiceOcrGen.current += 1; setInvoicePreview(null); clearAssistantImage(); setLoading(false); setHintModule(null); setQueryCard(null); setQuerySearch(''); setQueryBrowseBusy(false); browseGen.current += 1; setPickCard(null); setPickFilter(''); setError(''); closePreview(); const previousId = sessionIdRef.current; sessionIdRef.current = ''; setActiveConversationId(''); setMessages([{ role: 'assistant', content: WELCOME }]); if (!previousId) return; void fetch(buildApiUrl('/mcp/order-entry/confirm'), { method: 'POST', headers: authHeaders(), body: JSON.stringify({ client: 'web', session_id: previousId, cancel: true }), }).catch(() => undefined); }; const openHistoryConversation = async (id: string) => { if (id === sessionIdRef.current) return; const gen = ++conversationGen.current; invoiceOcrGen.current += 1; setInvoicePreview(null); clearAssistantImage(); setLoading(false); closePreview(); setQueryCard(null); setQuerySearch(''); setQueryBrowseBusy(false); browseGen.current += 1; setPickCard(null); setPickFilter(''); setError(''); try { await fetchConversationMessages(id, gen); } catch { if (gen !== conversationGen.current) return; } }; const confirmWrite = async (capability: string) => { if (loading || !capability) return; if (missingOperatingBranch()) { setError(t('assistant.branchRequired')); return; } const gen = conversationGen.current; setLoading(true); setError(''); setVoucherError(''); if (capability === 'upload_customer_invoice' || capability === 'upload_supplier_invoice') { const pending = invoicePendingRef.current; try { if ( !pending?.partyCode || (pending.party === 'customer') !== (capability === 'upload_customer_invoice') ) { throw new Error('没有待确认的发票'); } let invoiceUrl = pending.storedPath; if (!invoiceUrl) { invoiceUrl = await uploadInvoiceFileApi( pending.file, pending.party === 'customer' ? 'customer-invoices' : undefined ); } if (gen !== conversationGen.current) return; const record = { invoice_no: pending.invoiceNo, invoice_type: pending.party === 'customer' ? 'customer' : 'supplier', customer_code: pending.party === 'customer' ? pending.partyCode : null, supplier_code: pending.party === 'supplier' ? pending.partyCode : null, amount: pending.amount, tax_rate: pending.taxRate, tax_amount: pending.taxAmount, invoice_url: invoiceUrl, invoice_date: pending.invoiceDate, ocr_data: pending.ocr, allocations: pending.allocations, }; if (pending.party === 'customer') await saveCustomerInvoiceApi(record); else await saveInvoiceApi(record); if (gen !== conversationGen.current) return; setInvoicePreview(null); closePreview(); setMessages((prev) => [...prev, { role: 'assistant', content: `已写入发票 ${pending.invoiceNo}` }]); } catch (err) { if (gen !== conversationGen.current) return; setVoucherError(err instanceof Error ? err.message : '确认失败'); } finally { if (gen === conversationGen.current) setLoading(false); } return; } const isOrderDraft = changePreview?.draft?.kind === 'order_items'; const orderCode = changePreview?.draft?.order_code || changePreview?.target_id; try { const res = await fetch(buildApiUrl('/mcp/order-entry/confirm'), { method: 'POST', headers: authHeaders(), body: JSON.stringify({ client: 'web', session_id: sessionIdRef.current, confirmed_action_id: capability, ...(isOrderDraft ? { order_code: orderCode, items: draftRowsToConfirmItems(draftRows) } : {}), }), }); if (gen !== conversationGen.current) return; // 会话已切换:丢弃过期响应 const data = (await res.json().catch(() => ({}))) as { reply?: string; error_description?: string; error?: string; tool_trace?: ToolTraceItem[]; }; if (gen !== conversationGen.current) return; if (!res.ok) { throw new Error(data.error_description || data.error || '确认失败'); } closePreview(); setMessages((prev) => [ ...prev, { role: 'assistant', content: data.reply || t('assistant.preview.confirm'), toolTrace: failedToolTrace(data.tool_trace), }, ]); } catch (err) { if (gen !== conversationGen.current) return; const message = err instanceof Error ? err.message : '确认失败'; setVoucherError(message); } finally { if (gen === conversationGen.current) setLoading(false); } }; const handleKeyDown = useCallback( (e: React.KeyboardEvent) => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); void send(); } }, // eslint-disable-next-line react-hooks/exhaustive-deps [input, imageDataUrl, loading, messages, visiblePages, hintModule, locale] ); if (!visible) return null; const writeVoucher: PreviewPayload | null = changePreview || (pendingConfirmId ? { capability: pendingConfirmId, action_type: 'update', summary: toolLabel(pendingConfirmId) } : null); const isDeleteVoucher = writeVoucher?.action_type === 'delete'; const isOrderDraft = writeVoucher?.draft?.kind === 'order_items'; const previewTitle = writeVoucher?.action_type === 'delete' ? t('assistant.preview.deleteTitle') : writeVoucher?.action_type === 'create' ? t('assistant.preview.createTitle') : t('assistant.preview.updateTitle'); return ( <> {open && (
工作助手
{hintModule === 'order-entry' ? '当前:录单 · 提交须你确认' : hintModule === 'order-management' ? '当前:订单管理 · 可筛日期与搜索' : hintModule === 'self-purchase' ? '当前:采购管理' : hintModule === 'supplier-prep' ? '当前:备货表' : hintModule === 'after-sales' ? '当前:售后管理 · 写操作须你确认' : '导航到功能 · 查询默认在对话与卡片中展示'}
{messages.map((msg, idx) => (
{msg.content ?
{msg.content}
: null} {msg.role === 'assistant' && (failedToolTrace(msg.toolTrace)?.length || msg.shellNotes?.length) ? (
{failedToolTrace(msg.toolTrace)?.map((row, tIdx) => (
{toolLabel(row.name)}:{row.summary} (未成功)
))} {msg.shellNotes?.map((note, nIdx) => (
{note}
))}
) : null}
))} {loading ? (
{progressLabels.length ? progressLabels.join('、') : '处理中…'}
) : null}
{ void onPickImage(e.target.files?.[0]); e.target.value = ''; setPlusOpen(false); }} /> { void onPickInvoice('customer', e.target.files?.[0]); e.target.value = ''; }} /> { void onPickInvoice('supplier', e.target.files?.[0]); e.target.value = ''; }} /> {invoiceKind ? (
{ invoiceDateRangeRef.current = range; setInvoiceDateRange(range); }} emptyLabel={t('common.dateRange.empty')} panelClassName="z-[11000]" />
) : null} {imageDataUrl ? (
待识别
) : null} {invoicePreview ? (
{invoicePreview.imageUrl ? ( ) : (
{invoicePreview.fileName}
)}
) : null} {error ?
{error}
: null}
{voiceMode ? ( ) : (