来源仓库:jxc/ai-fresh-delivery 来源提交:f0b1a180e2deb7e4673b9d1c8542619f7bc0f73d 快照树: 09f679334ff38f0ff25e907961c94a8223bcaedd(与来源 HEAD 工作树逐字节一致,3801 个文件) 按约定本仓库不带任何历史提交:来源仓库的历史中含真实凭据 (生产 SSH 私钥 deploy/id_rsa_tencent、server/.env、.env.tencent/.env.production/.env.gitea、 deploy/小程序AppSecret.txt,其中 MP_APPSECRET / S3 AccessKey 经哈希比对与线上同值), 整包推送会把这些凭据永久带入本仓库,故只取「当前版本」的单提交快照。 供应商系统后续开发自本提交开始。
2279 lines
90 KiB
TypeScript
2279 lines
90 KiB
TypeScript
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<string, string> = {
|
||
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<Record<string, unknown>>;
|
||
};
|
||
|
||
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<Record<string, unknown>>;
|
||
};
|
||
};
|
||
|
||
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<string, string> {
|
||
const headers: Record<string, string> = {
|
||
'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<string | null>(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<ChatMessage[]>([{ role: 'assistant', content: WELCOME }]);
|
||
const [input, setInput] = useState('');
|
||
const [imageDataUrl, setImageDataUrl] = useState<string | null>(null);
|
||
const [invoiceKind, setInvoiceKind] = useState<InvoicePartyKind | null>(null);
|
||
const [invoicePartyCode, setInvoicePartyCode] = useState('');
|
||
const [invoicePartyOptions, setInvoicePartyOptions] = useState<Array<{ value: string; label: string; searchText?: string }>>([]);
|
||
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<string[]>([]);
|
||
const [error, setError] = useState('');
|
||
const [pendingConfirmId, setPendingConfirmId] = useState<string | null>(null);
|
||
const [queryCard, setQueryCard] = useState<QueryPayload | null>(null);
|
||
const [querySearch, setQuerySearch] = useState('');
|
||
const [queryBrowseBusy, setQueryBrowseBusy] = useState(false);
|
||
const browseGen = useRef(0);
|
||
const querySearchTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||
const [pickCard, setPickCard] = useState<PickPayload | null>(null);
|
||
const [pickFilter, setPickFilter] = useState('');
|
||
const [changePreview, setChangePreview] = useState<PreviewPayload | null>(null);
|
||
const [draftRows, setDraftRows] = useState<OrderDraftRow[]>([]);
|
||
const [voucherError, setVoucherError] = useState('');
|
||
const [plusOpen, setPlusOpen] = useState(false);
|
||
const [voiceMode, setVoiceMode] = useState(false);
|
||
const [conversations, setConversations] = useState<Array<{ id: string; title: string; updated_at: string }>>([]);
|
||
const [activeConversationId, setActiveConversationId] = useState('');
|
||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||
const customerInvoiceInputRef = useRef<HTMLInputElement>(null);
|
||
const supplierInvoiceInputRef = useRef<HTMLInputElement>(null);
|
||
const invoiceOcrGen = useRef(0);
|
||
const invoicePendingRef = useRef<InvoicePendingSave | null>(null);
|
||
const listRef = useRef<HTMLDivElement>(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<string, unknown>) => {
|
||
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<Array<{ statement_no: string; amount: number }>> => {
|
||
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<string, number>();
|
||
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<string, number>();
|
||
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<string>((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<string, unknown> = {
|
||
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<string, unknown>) => {
|
||
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 (
|
||
<>
|
||
<button
|
||
type="button"
|
||
onClick={() =>
|
||
setOpen((prev) => {
|
||
if (!prev) {
|
||
void loadLatestConversation();
|
||
} else {
|
||
setPlusOpen(false);
|
||
setVoiceMode(false);
|
||
}
|
||
return !prev;
|
||
})
|
||
}
|
||
className="fixed bottom-5 right-5 z-[9998] w-14 h-14 rounded-full shadow-lg flex items-center justify-center transition-all duration-200 hover:scale-110"
|
||
style={{
|
||
backgroundColor: 'var(--app-theme-accent, #3b82f6)',
|
||
color: '#fff',
|
||
}}
|
||
aria-label={open ? '关闭助手' : '打开助手'}
|
||
>
|
||
{open ? <X size={24} /> : <MessageCircle size={24} />}
|
||
</button>
|
||
|
||
{open && (
|
||
<div
|
||
className="fixed bottom-20 right-5 z-[9999] w-[min(740px,calc(100vw-2rem))] h-[min(760px,calc(100vh-6.5rem))] rounded-2xl shadow-2xl flex overflow-hidden border"
|
||
style={{
|
||
backgroundColor: 'var(--app-bg-card, #fff)',
|
||
borderColor: 'var(--app-border, #e5e7eb)',
|
||
}}
|
||
>
|
||
<aside
|
||
className="w-[200px] shrink-0 flex flex-col border-r"
|
||
style={{
|
||
backgroundColor: 'var(--app-table-head, #f3f4f6)',
|
||
borderColor: 'var(--app-border, #e5e7eb)',
|
||
}}
|
||
>
|
||
<button
|
||
type="button"
|
||
className="mx-2 mt-3 mb-2 rounded-lg px-3 py-2 text-sm font-medium text-white shrink-0"
|
||
style={{ backgroundColor: 'var(--app-theme-accent, #3b82f6)' }}
|
||
onClick={startNewConversation}
|
||
>
|
||
新增会话
|
||
</button>
|
||
<div className="flex-1 min-h-0 overflow-y-auto px-1.5 pb-2">
|
||
{conversations.map((row) => (
|
||
<div
|
||
key={row.id}
|
||
className="flex items-center gap-0.5 mb-0.5 rounded-lg"
|
||
style={{
|
||
backgroundColor:
|
||
row.id === activeConversationId
|
||
? 'color-mix(in srgb, var(--app-theme-accent, #3b82f6) 16%, #fff)'
|
||
: 'transparent',
|
||
}}
|
||
>
|
||
<button
|
||
type="button"
|
||
className="flex-1 min-w-0 text-left px-2.5 py-2 text-sm truncate"
|
||
style={{ color: 'var(--app-text, #111827)' }}
|
||
onClick={() => void openHistoryConversation(row.id)}
|
||
>
|
||
{row.title || row.updated_at}
|
||
</button>
|
||
<button
|
||
type="button"
|
||
className="shrink-0 mr-1 p-1.5 rounded-md text-gray-400 hover:text-red-600 hover:bg-red-50"
|
||
title={t('assistant.history.delete')}
|
||
aria-label={t('assistant.history.delete')}
|
||
onClick={(e) => {
|
||
e.stopPropagation();
|
||
void deleteConversation(row.id);
|
||
}}
|
||
>
|
||
<Trash2 className="w-3.5 h-3.5" />
|
||
</button>
|
||
</div>
|
||
))}
|
||
</div>
|
||
</aside>
|
||
<div className="flex-1 min-w-0 flex flex-col">
|
||
<div
|
||
className="flex items-center justify-between px-4 py-3 shrink-0"
|
||
style={{ backgroundColor: 'var(--app-theme-accent, #3b82f6)', color: '#fff' }}
|
||
>
|
||
<div>
|
||
<div className="text-sm font-semibold">工作助手</div>
|
||
<div className="text-xs opacity-90">
|
||
{hintModule === 'order-entry'
|
||
? '当前:录单 · 提交须你确认'
|
||
: hintModule === 'order-management'
|
||
? '当前:订单管理 · 可筛日期与搜索'
|
||
: hintModule === 'self-purchase'
|
||
? '当前:采购管理'
|
||
: hintModule === 'supplier-prep'
|
||
? '当前:备货表'
|
||
: hintModule === 'after-sales'
|
||
? '当前:售后管理 · 写操作须你确认'
|
||
: '导航到功能 · 查询默认在对话与卡片中展示'}
|
||
</div>
|
||
</div>
|
||
<button type="button" onClick={() => setOpen(false)} aria-label="关闭" className="opacity-90 hover:opacity-100">
|
||
<X size={18} />
|
||
</button>
|
||
</div>
|
||
|
||
<div ref={listRef} className="flex-1 overflow-y-auto px-3 py-3 space-y-2 text-[15px] leading-relaxed">
|
||
{messages.map((msg, idx) => (
|
||
<div
|
||
key={`${msg.role}-${idx}`}
|
||
className={`flex ${msg.role === 'user' ? 'justify-end' : 'justify-start'}`}
|
||
>
|
||
<div
|
||
className={`rounded-lg px-3 py-2 whitespace-pre-wrap max-w-[82%] ${
|
||
msg.role === 'user' ? 'rounded-br-sm' : 'rounded-bl-sm'
|
||
}`}
|
||
style={{
|
||
backgroundColor: msg.role === 'user' ? 'var(--app-theme-accent, #3b82f6)' : 'var(--app-table-head, #f3f4f6)',
|
||
color: msg.role === 'user' ? '#fff' : 'inherit',
|
||
}}
|
||
>
|
||
{msg.content ? <div>{msg.content}</div> : null}
|
||
{msg.role === 'assistant' && (failedToolTrace(msg.toolTrace)?.length || msg.shellNotes?.length) ? (
|
||
<div
|
||
className="mt-2 pt-2 text-xs space-y-1"
|
||
style={{
|
||
borderTop: '1px solid color-mix(in srgb, currentColor 18%, transparent)',
|
||
opacity: 0.9,
|
||
}}
|
||
>
|
||
{failedToolTrace(msg.toolTrace)?.map((row, tIdx) => (
|
||
<div key={`${row.name}-${tIdx}`}>
|
||
{toolLabel(row.name)}:{row.summary}
|
||
(未成功)
|
||
</div>
|
||
))}
|
||
{msg.shellNotes?.map((note, nIdx) => (
|
||
<div key={`note-${nIdx}`}>{note}</div>
|
||
))}
|
||
</div>
|
||
) : null}
|
||
</div>
|
||
</div>
|
||
))}
|
||
{loading ? (
|
||
<div className="flex items-center gap-2 text-xs opacity-70">
|
||
<Loader2 size={14} className="animate-spin" />
|
||
{progressLabels.length ? progressLabels.join('、') : '处理中…'}
|
||
</div>
|
||
) : null}
|
||
</div>
|
||
|
||
<div
|
||
className="shrink-0 border-t"
|
||
style={{
|
||
borderColor: 'var(--app-border, #e5e7eb)',
|
||
backgroundColor: 'var(--app-table-head, #f3f4f6)',
|
||
}}
|
||
>
|
||
<input
|
||
ref={fileInputRef}
|
||
type="file"
|
||
accept="image/jpeg,image/png,image/webp"
|
||
className="hidden"
|
||
onChange={(e) => {
|
||
void onPickImage(e.target.files?.[0]);
|
||
e.target.value = '';
|
||
setPlusOpen(false);
|
||
}}
|
||
/>
|
||
<input
|
||
ref={customerInvoiceInputRef}
|
||
type="file"
|
||
accept=".pdf,image/*"
|
||
className="hidden"
|
||
onChange={(e) => {
|
||
void onPickInvoice('customer', e.target.files?.[0]);
|
||
e.target.value = '';
|
||
}}
|
||
/>
|
||
<input
|
||
ref={supplierInvoiceInputRef}
|
||
type="file"
|
||
accept=".pdf,image/*"
|
||
className="hidden"
|
||
onChange={(e) => {
|
||
void onPickInvoice('supplier', e.target.files?.[0]);
|
||
e.target.value = '';
|
||
}}
|
||
/>
|
||
{invoiceKind ? (
|
||
<div className="px-3 pt-2 space-y-2">
|
||
<DateRangeFilterButton
|
||
value={invoiceDateRange}
|
||
onChange={(range) => {
|
||
invoiceDateRangeRef.current = range;
|
||
setInvoiceDateRange(range);
|
||
}}
|
||
emptyLabel={t('common.dateRange.empty')}
|
||
panelClassName="z-[11000]"
|
||
/>
|
||
<div className="flex items-center gap-2">
|
||
<SearchableSelect
|
||
value={invoicePartyCode}
|
||
onChange={onInvoicePartyChange}
|
||
options={invoicePartyOptions}
|
||
placeholder={
|
||
invoiceKind === 'customer'
|
||
? t('finance.customerStmt.customerPh')
|
||
: t('finance.supplierStmt.supplierPh')
|
||
}
|
||
className="w-full min-w-0 flex-1"
|
||
portal
|
||
portalZIndex={11000}
|
||
/>
|
||
<button
|
||
type="button"
|
||
className="shrink-0 p-2 rounded-lg border opacity-70 hover:opacity-100"
|
||
style={{ borderColor: 'var(--app-border, #e5e7eb)' }}
|
||
aria-label={t('common.delete')}
|
||
onClick={cancelInvoiceParty}
|
||
>
|
||
<Trash2 size={16} />
|
||
</button>
|
||
</div>
|
||
</div>
|
||
) : null}
|
||
{imageDataUrl ? (
|
||
<div className="relative px-3 pt-2">
|
||
<img src={imageDataUrl} alt="待识别" className="w-full max-h-24 object-contain rounded-lg border" />
|
||
<button
|
||
type="button"
|
||
className="absolute top-3 right-5 rounded-full bg-black/60 text-white p-1"
|
||
onClick={clearAssistantImage}
|
||
aria-label="移除图片"
|
||
>
|
||
<X size={12} />
|
||
</button>
|
||
</div>
|
||
) : null}
|
||
{invoicePreview ? (
|
||
<div className="relative px-3 pt-2">
|
||
{invoicePreview.imageUrl ? (
|
||
<img
|
||
src={invoicePreview.imageUrl}
|
||
alt=""
|
||
className="w-full max-h-24 object-contain rounded-lg border"
|
||
/>
|
||
) : (
|
||
<div className="text-xs rounded-lg border px-2 py-2 truncate">{invoicePreview.fileName}</div>
|
||
)}
|
||
<button
|
||
type="button"
|
||
className="absolute top-3 right-5 rounded-full bg-black/60 text-white p-1"
|
||
onClick={() => {
|
||
clearInvoiceAttach();
|
||
closePreview();
|
||
}}
|
||
aria-label="移除发票"
|
||
>
|
||
<X size={12} />
|
||
</button>
|
||
</div>
|
||
) : null}
|
||
{error ? <div className="px-3 pt-2 text-xs text-red-600">{error}</div> : null}
|
||
|
||
<div className="flex items-end gap-1.5 px-2 py-2">
|
||
<button
|
||
type="button"
|
||
className="shrink-0 w-9 h-9 rounded-full flex items-center justify-center"
|
||
style={{ color: 'var(--app-text, #111827)' }}
|
||
aria-label={voiceMode ? '切换键盘' : '语音输入'}
|
||
onClick={() => {
|
||
setPlusOpen(false);
|
||
setVoiceMode((prev) => !prev);
|
||
}}
|
||
>
|
||
{voiceMode ? <Keyboard size={22} /> : <Mic size={22} />}
|
||
</button>
|
||
|
||
{voiceMode ? (
|
||
<button
|
||
type="button"
|
||
disabled={loading || isTranscribing || !isVoiceSupported}
|
||
onPointerDown={(e) => void beginHoldTalk(e)}
|
||
onPointerUp={endHoldTalk}
|
||
onPointerCancel={endHoldTalk}
|
||
onContextMenu={(e) => e.preventDefault()}
|
||
className="flex-1 h-9 rounded-lg text-sm font-medium select-none disabled:opacity-60"
|
||
style={{
|
||
backgroundColor: isRecording ? 'color-mix(in srgb, var(--app-theme-accent, #3b82f6) 18%, #fff)' : 'var(--app-bg-card, #fff)',
|
||
border: '1px solid var(--app-border, #e5e7eb)',
|
||
touchAction: 'none',
|
||
}}
|
||
>
|
||
{isTranscribing ? '识别中…' : isRecording ? '松开 结束' : isVoiceSupported ? '按住 说话' : '当前浏览器不支持录音'}
|
||
</button>
|
||
) : (
|
||
<textarea
|
||
value={input}
|
||
onChange={(e) => {
|
||
setInput(e.target.value);
|
||
if (plusOpen) setPlusOpen(false);
|
||
}}
|
||
onKeyDown={handleKeyDown}
|
||
rows={1}
|
||
placeholder="例如:竞价在哪 / 给张记食堂:土豆10斤"
|
||
className="flex-1 min-h-9 max-h-24 rounded-lg border px-3 py-1.5 text-sm resize-none leading-6"
|
||
style={{
|
||
borderColor: 'var(--app-border, #e5e7eb)',
|
||
backgroundColor: 'var(--app-bg-card, #fff)',
|
||
}}
|
||
/>
|
||
)}
|
||
|
||
{canSend && !voiceMode ? (
|
||
<button
|
||
type="button"
|
||
onClick={() => {
|
||
setPlusOpen(false);
|
||
void send();
|
||
}}
|
||
disabled={loading}
|
||
className="shrink-0 h-9 px-3 rounded-md text-sm font-medium text-white flex items-center gap-1 disabled:opacity-60"
|
||
style={{ backgroundColor: 'var(--app-theme-accent, #3b82f6)' }}
|
||
>
|
||
{loading ? <Loader2 size={14} className="animate-spin" /> : <Send size={14} />}
|
||
发送
|
||
</button>
|
||
) : (
|
||
<button
|
||
type="button"
|
||
className="shrink-0 w-9 h-9 rounded-full flex items-center justify-center"
|
||
aria-label="更多功能"
|
||
aria-expanded={plusOpen}
|
||
onClick={() => {
|
||
setVoiceMode(false);
|
||
setPlusOpen((prev) => !prev);
|
||
}}
|
||
>
|
||
<Plus size={22} />
|
||
</button>
|
||
)}
|
||
</div>
|
||
|
||
{plusOpen ? (
|
||
<div
|
||
className="grid grid-cols-4 gap-3 px-4 pb-3 pt-1"
|
||
style={{ backgroundColor: 'var(--app-table-head, #f3f4f6)' }}
|
||
>
|
||
<button
|
||
type="button"
|
||
className="flex flex-col items-center gap-1.5"
|
||
onClick={() => fileInputRef.current?.click()}
|
||
>
|
||
<span
|
||
className="w-12 h-12 rounded-xl flex items-center justify-center"
|
||
style={{
|
||
backgroundColor: 'var(--app-bg-card, #fff)',
|
||
border: '1px solid var(--app-border, #e5e7eb)',
|
||
}}
|
||
>
|
||
<ImagePlus size={22} />
|
||
</span>
|
||
<span className="text-[11px] leading-tight text-center">上传点菜单</span>
|
||
</button>
|
||
{(hasRole('super_admin') || hasPermission('system_manage')) && (
|
||
<button
|
||
type="button"
|
||
className="flex flex-col items-center gap-1.5"
|
||
onClick={() => {
|
||
const branchCode = readOperatingBranchCode();
|
||
if (hasRole('super_admin') && !branchCode) {
|
||
setError(t('assistant.branchRequired'));
|
||
return;
|
||
}
|
||
setPlusOpen(false);
|
||
// 不再是弹窗:跳到「系统配置 → 打印模板」并选中 AI 配送单模板这一分类
|
||
navigate('/system/print-templates?kind=ai_delivery_template');
|
||
}}
|
||
>
|
||
<span
|
||
className="w-12 h-12 rounded-xl flex items-center justify-center"
|
||
style={{
|
||
backgroundColor: 'var(--app-bg-card, #fff)',
|
||
border: '1px solid var(--app-border, #e5e7eb)',
|
||
}}
|
||
>
|
||
<FileText size={22} />
|
||
</span>
|
||
<span className="text-[11px] leading-tight text-center">{t('assistant.template.upload')}</span>
|
||
</button>
|
||
)}
|
||
<button
|
||
type="button"
|
||
className="flex flex-col items-center gap-1.5"
|
||
onClick={() => {
|
||
setPlusOpen(false);
|
||
setVoiceMode(true);
|
||
}}
|
||
>
|
||
<span
|
||
className="w-12 h-12 rounded-xl flex items-center justify-center"
|
||
style={{
|
||
backgroundColor: 'var(--app-bg-card, #fff)',
|
||
border: '1px solid var(--app-border, #e5e7eb)',
|
||
}}
|
||
>
|
||
<Mic size={22} />
|
||
</span>
|
||
<span className="text-[11px] leading-tight text-center">语音输入</span>
|
||
</button>
|
||
{canOpenStatementInvoice ? (
|
||
<>
|
||
<button
|
||
type="button"
|
||
className="flex flex-col items-center gap-1.5"
|
||
onClick={() => void startInvoiceFlow('customer')}
|
||
>
|
||
<span
|
||
className="w-12 h-12 rounded-xl flex items-center justify-center"
|
||
style={{
|
||
backgroundColor: 'var(--app-bg-card, #fff)',
|
||
border: '1px solid var(--app-border, #e5e7eb)',
|
||
}}
|
||
>
|
||
<FileText size={22} />
|
||
</span>
|
||
<span className="text-[11px] leading-tight text-center">客户发票上传</span>
|
||
</button>
|
||
<button
|
||
type="button"
|
||
className="flex flex-col items-center gap-1.5"
|
||
onClick={() => void startInvoiceFlow('supplier')}
|
||
>
|
||
<span
|
||
className="w-12 h-12 rounded-xl flex items-center justify-center"
|
||
style={{
|
||
backgroundColor: 'var(--app-bg-card, #fff)',
|
||
border: '1px solid var(--app-border, #e5e7eb)',
|
||
}}
|
||
>
|
||
<FileText size={22} />
|
||
</span>
|
||
<span className="text-[11px] leading-tight text-center">供应商发票上传</span>
|
||
</button>
|
||
</>
|
||
) : null}
|
||
</div>
|
||
) : null}
|
||
</div>
|
||
</div>
|
||
</div>
|
||
)}
|
||
|
||
{pickCard && !writeVoucher ? (
|
||
<div
|
||
className="fixed inset-0 z-[10000] flex items-center justify-center bg-black/40 p-4"
|
||
role="presentation"
|
||
onClick={() => setPickCard(null)}
|
||
>
|
||
<div
|
||
className="w-[min(480px,calc(100vw-2rem))] max-h-[min(70vh,560px)] overflow-hidden rounded-2xl border shadow-2xl flex flex-col"
|
||
style={{
|
||
backgroundColor: 'var(--app-bg-card, #fff)',
|
||
borderColor: 'var(--app-border, #e5e7eb)',
|
||
}}
|
||
role="dialog"
|
||
aria-label={
|
||
['customer_code', 'supplier_code', 'sku_code'].includes(String(pickCard.slot || ''))
|
||
? t(`assistant.pick.slot.${pickCard.slot}`)
|
||
: t('assistant.pick.slot.customer_code')
|
||
}
|
||
onClick={(e) => e.stopPropagation()}
|
||
>
|
||
<div className="flex items-center justify-between px-4 py-3 border-b shrink-0" style={{ borderColor: 'var(--app-border, #e5e7eb)' }}>
|
||
<div className="text-sm font-semibold">
|
||
{['customer_code', 'supplier_code', 'sku_code'].includes(String(pickCard.slot || ''))
|
||
? t(`assistant.pick.slot.${pickCard.slot}`)
|
||
: pickCard.prompt || t('assistant.pick.slot.customer_code')}
|
||
</div>
|
||
<button
|
||
type="button"
|
||
aria-label={t('common.close')}
|
||
onClick={() => setPickCard(null)}
|
||
className="p-1 opacity-70 hover:opacity-100"
|
||
>
|
||
<X size={18} />
|
||
</button>
|
||
</div>
|
||
{(pickCard.options?.length || 0) > 8 ? (
|
||
<div className="px-4 py-2 border-b shrink-0" style={{ borderColor: 'var(--app-border, #e5e7eb)' }}>
|
||
<input
|
||
type="search"
|
||
value={pickFilter}
|
||
onChange={(e) => setPickFilter(e.target.value)}
|
||
placeholder={t('assistant.pick.search')}
|
||
className="w-full rounded-lg border px-3 py-2 text-sm"
|
||
style={{ borderColor: 'var(--app-border, #e5e7eb)' }}
|
||
/>
|
||
</div>
|
||
) : null}
|
||
<div className="flex-1 overflow-auto">
|
||
{(() => {
|
||
const q = pickFilter.trim().toLowerCase();
|
||
const rows = (pickCard.options || [])
|
||
.map((row) => ({
|
||
id: String(row.id || '').trim(),
|
||
label: String(row.label || '').trim() || String(row.id || '').trim(),
|
||
}))
|
||
.filter((row) => row.id)
|
||
.filter(
|
||
(row) =>
|
||
!q ||
|
||
row.label.toLowerCase().includes(q) ||
|
||
row.id.toLowerCase().includes(q)
|
||
);
|
||
if (!rows.length) {
|
||
return <div className="px-4 py-6 text-sm opacity-70">{t('assistant.pick.empty')}</div>;
|
||
}
|
||
return (
|
||
<ul>
|
||
{rows.map((row) => (
|
||
<li key={row.id} className="border-b" style={{ borderColor: 'var(--app-border, #e5e7eb)' }}>
|
||
<button
|
||
type="button"
|
||
disabled={loading}
|
||
className="w-full text-left px-4 py-3 text-sm hover:bg-black/5 disabled:opacity-50"
|
||
onClick={() => void applyPickedOption(row)}
|
||
>
|
||
{row.label === row.id ? row.label : `${row.label}(${row.id})`}
|
||
</button>
|
||
</li>
|
||
))}
|
||
</ul>
|
||
);
|
||
})()}
|
||
</div>
|
||
<div className="px-4 py-3 border-t shrink-0 flex justify-end" style={{ borderColor: 'var(--app-border, #e5e7eb)' }}>
|
||
<button
|
||
type="button"
|
||
className="rounded-lg px-4 py-2 text-sm border"
|
||
style={{ borderColor: 'var(--app-border, #e5e7eb)' }}
|
||
onClick={() => setPickCard(null)}
|
||
>
|
||
{t('common.close')}
|
||
</button>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
) : null}
|
||
|
||
{queryCard && !writeVoucher ? (
|
||
<div
|
||
className="fixed inset-0 z-[10000] flex items-center justify-center bg-black/40 p-4"
|
||
role="presentation"
|
||
>
|
||
<div
|
||
className="w-[min(960px,calc(100vw-2rem))] max-h-[min(80vh,640px)] overflow-hidden rounded-2xl border shadow-2xl flex flex-col"
|
||
style={{
|
||
backgroundColor: 'var(--app-bg-card, #fff)',
|
||
borderColor: 'var(--app-border, #e5e7eb)',
|
||
}}
|
||
role="dialog"
|
||
aria-label={t('assistant.queryResult')}
|
||
onClick={(e) => e.stopPropagation()}
|
||
>
|
||
<div className="flex items-center justify-between px-4 py-3 border-b shrink-0" style={{ borderColor: 'var(--app-border, #e5e7eb)' }}>
|
||
<div>
|
||
<div className="text-sm font-semibold">
|
||
{assistantQueryTitle(t, queryCard.capability, queryCard.title)}
|
||
{queryCard.count != null ? t('assistant.rowCount', { count: queryCard.count }) : ''}
|
||
</div>
|
||
{queryCard.summary ? <div className="text-xs opacity-80 mt-0.5">{queryCard.summary}</div> : null}
|
||
</div>
|
||
<button type="button" aria-label={t('common.close')} onClick={() => setQueryCard(null)} className="p-1 opacity-70 hover:opacity-100">
|
||
<X size={18} />
|
||
</button>
|
||
</div>
|
||
{queryCard.browse_id && (queryCard.has_search || queryCard.has_date) ? (
|
||
<div
|
||
className="flex flex-wrap items-center gap-2 px-4 py-2 border-b shrink-0"
|
||
style={{ borderColor: 'var(--app-border, #e5e7eb)' }}
|
||
>
|
||
{queryCard.has_search ? (
|
||
<input
|
||
type="search"
|
||
value={querySearch}
|
||
disabled={queryBrowseBusy}
|
||
placeholder={t('common.search')}
|
||
className="rounded-lg border px-3 py-1.5 text-sm min-w-[12rem] flex-1"
|
||
style={{ borderColor: 'var(--app-border, #e5e7eb)' }}
|
||
onChange={(e) => {
|
||
const next = e.target.value;
|
||
setQuerySearch(next);
|
||
if (querySearchTimer.current) clearTimeout(querySearchTimer.current);
|
||
querySearchTimer.current = setTimeout(() => {
|
||
void browseQuery({ search: next, page: 1 });
|
||
}, 300);
|
||
}}
|
||
/>
|
||
) : null}
|
||
{queryCard.has_date ? (
|
||
<DateRangeFilterButton
|
||
value={
|
||
queryCard.date_from && queryCard.date_to
|
||
? { start: queryCard.date_from, end: queryCard.date_to }
|
||
: null
|
||
}
|
||
onChange={(range) => {
|
||
if (!range?.start || !range?.end) return;
|
||
void browseQuery({ date_from: range.start, date_to: range.end, page: 1 });
|
||
}}
|
||
emptyLabel={t('common.dateRange.empty')}
|
||
panelClassName="z-[11000]"
|
||
/>
|
||
) : null}
|
||
</div>
|
||
) : null}
|
||
{queryCard.columns?.length && queryCard.rows?.length ? (
|
||
<div className="flex-1 overflow-auto">
|
||
<table className="w-full text-sm table-auto border-collapse">
|
||
<thead className="sticky top-0" style={{ backgroundColor: 'var(--app-table-head, #f3f4f6)' }}>
|
||
<tr>
|
||
{queryCard.columns.map((col) => (
|
||
<th
|
||
key={col}
|
||
className="text-left font-medium px-3 py-2 whitespace-nowrap border"
|
||
style={{ borderColor: 'var(--app-border, #e5e7eb)' }}
|
||
>
|
||
{assistantColumnLabel(t, col)}
|
||
</th>
|
||
))}
|
||
</tr>
|
||
</thead>
|
||
<tbody>
|
||
{queryCard.rows.map((row, idx) => (
|
||
<tr key={idx}>
|
||
{queryCard.columns?.map((col) => (
|
||
<td
|
||
key={col}
|
||
className="px-3 py-2 whitespace-nowrap border"
|
||
style={{ borderColor: 'var(--app-border, #e5e7eb)' }}
|
||
>
|
||
{asText(row[col])}
|
||
</td>
|
||
))}
|
||
</tr>
|
||
))}
|
||
</tbody>
|
||
</table>
|
||
</div>
|
||
) : (
|
||
<div className="px-4 py-6 text-sm opacity-70">{t('assistant.emptyRows')}</div>
|
||
)}
|
||
<div className="px-4 py-3 border-t shrink-0 flex items-center justify-between gap-2" style={{ borderColor: 'var(--app-border, #e5e7eb)' }}>
|
||
{queryCard.browse_id ? (
|
||
<div className="flex items-center gap-2">
|
||
<button
|
||
type="button"
|
||
className="rounded-lg px-3 py-2 text-sm border disabled:opacity-40"
|
||
style={{ borderColor: 'var(--app-border, #e5e7eb)' }}
|
||
disabled={queryBrowseBusy || (queryCard.page || 1) <= 1}
|
||
onClick={() => void browseQuery({ page: Math.max(1, (queryCard.page || 1) - 1) })}
|
||
>
|
||
{t('common.pager.prev')}
|
||
</button>
|
||
<span className="text-sm opacity-80">
|
||
{t('common.pager.summary', {
|
||
total: queryCard.count ?? queryCard.rows?.length ?? 0,
|
||
item: t('common.pager.itemDefault'),
|
||
page: queryCard.page || 1,
|
||
pages: Math.max(
|
||
1,
|
||
Math.ceil((queryCard.count || queryCard.rows?.length || 0) / (queryCard.page_size || 20))
|
||
),
|
||
})}
|
||
</span>
|
||
<button
|
||
type="button"
|
||
className="rounded-lg px-3 py-2 text-sm border disabled:opacity-40"
|
||
style={{ borderColor: 'var(--app-border, #e5e7eb)' }}
|
||
disabled={
|
||
queryBrowseBusy ||
|
||
(queryCard.page || 1) >=
|
||
Math.max(
|
||
1,
|
||
Math.ceil((queryCard.count || queryCard.rows?.length || 0) / (queryCard.page_size || 20))
|
||
)
|
||
}
|
||
onClick={() => void browseQuery({ page: (queryCard.page || 1) + 1 })}
|
||
>
|
||
{t('common.pager.next')}
|
||
</button>
|
||
</div>
|
||
) : (
|
||
<span />
|
||
)}
|
||
<button
|
||
type="button"
|
||
className="rounded-lg px-4 py-2 text-sm border"
|
||
style={{ borderColor: 'var(--app-border, #e5e7eb)' }}
|
||
onClick={() => setQueryCard(null)}
|
||
>
|
||
{t('common.close')}
|
||
</button>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
) : null}
|
||
|
||
{writeVoucher ? (
|
||
<div className="fixed inset-0 z-[10000] flex items-center justify-center bg-black/40 p-4" role="presentation">
|
||
<div
|
||
className={`${isOrderDraft ? 'w-[min(960px,calc(100vw-2rem))]' : 'w-[min(480px,calc(100vw-2rem))]'} max-h-[min(80vh,640px)] overflow-auto rounded-2xl border shadow-2xl p-4 space-y-3`}
|
||
style={{
|
||
backgroundColor: 'var(--app-bg-card, #fff)',
|
||
borderColor: isDeleteVoucher ? '#fecaca' : 'var(--app-border, #e5e7eb)',
|
||
}}
|
||
role="dialog"
|
||
aria-label={previewTitle}
|
||
>
|
||
<div className="flex items-start justify-between gap-2">
|
||
<div>
|
||
<div className="text-base font-semibold">{previewTitle}</div>
|
||
<div className="text-sm mt-1">{writeVoucher.summary || toolLabel(writeVoucher.capability || '')}</div>
|
||
<div className="text-xs opacity-80 mt-1">
|
||
{t('assistant.preview.target')}
|
||
{writeVoucher.target_id ? ` · ${writeVoucher.target_id}` : ''}
|
||
{writeVoucher.capability ? ` · ${toolLabel(writeVoucher.capability)}` : ''}
|
||
</div>
|
||
</div>
|
||
<button
|
||
type="button"
|
||
aria-label={t('common.close')}
|
||
className="p-1 opacity-70 hover:opacity-100"
|
||
onClick={() => void cancelPreview()}
|
||
>
|
||
<X size={18} />
|
||
</button>
|
||
</div>
|
||
{isOrderDraft ? (
|
||
<div className="space-y-2">
|
||
<div className="text-xs opacity-70">{t('assistant.draft.hint')}</div>
|
||
<div className="overflow-auto rounded-lg border" style={{ borderColor: 'var(--app-border, #e5e7eb)' }}>
|
||
<table className="w-full text-sm table-auto border-collapse">
|
||
<thead style={{ backgroundColor: 'var(--app-table-head, #f3f4f6)' }}>
|
||
<tr>
|
||
<th className="text-left font-medium px-2 py-2 border" style={{ borderColor: 'var(--app-border, #e5e7eb)' }}>
|
||
{t('assistant.col.item_name')}
|
||
</th>
|
||
<th className="text-left font-medium px-2 py-2 border" style={{ borderColor: 'var(--app-border, #e5e7eb)' }}>
|
||
{t('assistant.col.sku_code')}
|
||
</th>
|
||
<th className="text-left font-medium px-2 py-2 border" style={{ borderColor: 'var(--app-border, #e5e7eb)' }}>
|
||
{t('assistant.col.category_code')}
|
||
</th>
|
||
<th className="text-left font-medium px-2 py-2 border" style={{ borderColor: 'var(--app-border, #e5e7eb)' }}>
|
||
{t('assistant.col.quantity')}
|
||
</th>
|
||
<th className="text-left font-medium px-2 py-2 border" style={{ borderColor: 'var(--app-border, #e5e7eb)' }}>
|
||
{t('assistant.col.sale_price')}
|
||
</th>
|
||
<th className="px-2 py-2 border" style={{ borderColor: 'var(--app-border, #e5e7eb)' }} />
|
||
</tr>
|
||
</thead>
|
||
<tbody>
|
||
{draftRows.map((row) => (
|
||
<tr
|
||
key={row.client_id}
|
||
style={{
|
||
backgroundColor: row.highlighted ? 'color-mix(in srgb, #f59e0b 16%, transparent)' : undefined,
|
||
opacity: row.removed ? 0.45 : 1,
|
||
textDecoration: row.removed ? 'line-through' : undefined,
|
||
}}
|
||
>
|
||
<td className="px-2 py-1 border" style={{ borderColor: 'var(--app-border, #e5e7eb)' }}>
|
||
<input
|
||
className="w-full bg-transparent outline-none"
|
||
value={row.item_name}
|
||
disabled={row.removed}
|
||
onChange={(e) =>
|
||
setDraftRows((prev) =>
|
||
prev.map((item) =>
|
||
item.client_id === row.client_id ? { ...item, item_name: e.target.value } : item
|
||
)
|
||
)
|
||
}
|
||
/>
|
||
</td>
|
||
<td className="px-2 py-1 border" style={{ borderColor: 'var(--app-border, #e5e7eb)' }}>
|
||
<input
|
||
className="w-full bg-transparent outline-none"
|
||
value={row.sku_code}
|
||
disabled={row.removed}
|
||
onChange={(e) =>
|
||
setDraftRows((prev) =>
|
||
prev.map((item) =>
|
||
item.client_id === row.client_id ? { ...item, sku_code: e.target.value } : item
|
||
)
|
||
)
|
||
}
|
||
/>
|
||
</td>
|
||
<td className="px-2 py-1 border" style={{ borderColor: 'var(--app-border, #e5e7eb)' }}>
|
||
<input
|
||
className="w-full bg-transparent outline-none"
|
||
value={row.category_code}
|
||
disabled={row.removed}
|
||
onChange={(e) =>
|
||
setDraftRows((prev) =>
|
||
prev.map((item) =>
|
||
item.client_id === row.client_id ? { ...item, category_code: e.target.value } : item
|
||
)
|
||
)
|
||
}
|
||
/>
|
||
</td>
|
||
<td className="px-2 py-1 border" style={{ borderColor: 'var(--app-border, #e5e7eb)' }}>
|
||
<input
|
||
className="w-20 bg-transparent outline-none"
|
||
inputMode="decimal"
|
||
value={row.quantity}
|
||
disabled={row.removed}
|
||
onChange={(e) =>
|
||
setDraftRows((prev) =>
|
||
prev.map((item) =>
|
||
item.client_id === row.client_id ? { ...item, quantity: e.target.value } : item
|
||
)
|
||
)
|
||
}
|
||
/>
|
||
</td>
|
||
<td className="px-2 py-1 border" style={{ borderColor: 'var(--app-border, #e5e7eb)' }}>
|
||
<input
|
||
className="w-24 bg-transparent outline-none"
|
||
inputMode="decimal"
|
||
value={row.sale_price}
|
||
disabled={row.removed}
|
||
onChange={(e) =>
|
||
setDraftRows((prev) =>
|
||
prev.map((item) =>
|
||
item.client_id === row.client_id ? { ...item, sale_price: e.target.value } : item
|
||
)
|
||
)
|
||
}
|
||
/>
|
||
</td>
|
||
<td className="px-2 py-1 border text-center" style={{ borderColor: 'var(--app-border, #e5e7eb)' }}>
|
||
<button
|
||
type="button"
|
||
className="text-xs text-red-700"
|
||
onClick={() =>
|
||
setDraftRows((prev) =>
|
||
prev.map((item) =>
|
||
item.client_id === row.client_id ? { ...item, removed: !item.removed } : item
|
||
)
|
||
)
|
||
}
|
||
>
|
||
{row.removed ? t('assistant.draft.restoreRow') : t('assistant.draft.removeRow')}
|
||
</button>
|
||
</td>
|
||
</tr>
|
||
))}
|
||
</tbody>
|
||
</table>
|
||
</div>
|
||
<button
|
||
type="button"
|
||
className="text-sm"
|
||
onClick={() =>
|
||
setDraftRows((prev) => [
|
||
...prev,
|
||
{
|
||
client_id: `tmp-${Date.now()}`,
|
||
sku_code: '',
|
||
item_name: '',
|
||
category_code: '',
|
||
quantity: '1',
|
||
unit: '斤',
|
||
sale_price: '0',
|
||
},
|
||
])
|
||
}
|
||
>
|
||
{t('assistant.draft.addRow')}
|
||
</button>
|
||
</div>
|
||
) : writeVoucher.diff?.length ? (
|
||
<ul className="text-sm space-y-1.5 rounded-lg border p-3" style={{ borderColor: 'var(--app-border, #e5e7eb)' }}>
|
||
{writeVoucher.diff.map((row, idx) => (
|
||
<li key={`${row.field}-${idx}`}>
|
||
<span className="opacity-70">{row.field}:</span>
|
||
{row.before != null && row.before !== '' ? `${asText(row.before)} → ` : ''}
|
||
{asText(row.after)}
|
||
</li>
|
||
))}
|
||
</ul>
|
||
) : null}
|
||
{writeVoucher.impact ? (
|
||
<div className="text-xs text-amber-700">
|
||
{t('assistant.preview.impact')}:{writeVoucher.impact}
|
||
</div>
|
||
) : null}
|
||
{isDeleteVoucher ? <div className="text-xs text-red-700">{t('assistant.preview.deleteRisk')}</div> : null}
|
||
{voucherError ? <div className="text-xs text-red-700">{voucherError}</div> : null}
|
||
<div className="text-xs opacity-70">{t('assistant.preview.needConfirm')}</div>
|
||
<div className="flex gap-2 pt-1">
|
||
<button
|
||
type="button"
|
||
className="flex-1 rounded-lg py-2.5 text-sm border"
|
||
style={{ borderColor: 'var(--app-border, #e5e7eb)' }}
|
||
onClick={() => void cancelPreview()}
|
||
>
|
||
{t('common.cancel')}
|
||
</button>
|
||
<button
|
||
type="button"
|
||
className="flex-1 rounded-lg py-2.5 text-sm font-medium text-white disabled:opacity-60"
|
||
style={{ backgroundColor: isDeleteVoucher ? '#b91c1c' : 'var(--app-theme-accent, #3b82f6)' }}
|
||
disabled={loading || !writeVoucher.capability}
|
||
onClick={() => {
|
||
const id = writeVoucher.capability;
|
||
if (!id) return;
|
||
void confirmWrite(id);
|
||
}}
|
||
>
|
||
{t('assistant.preview.confirm')}
|
||
</button>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
) : null}
|
||
</>
|
||
);
|
||
};
|