add AIAgent
This commit is contained in:
@@ -0,0 +1,183 @@
|
|||||||
|
/** 门店智能助手聊天请求。 */
|
||||||
|
export interface GaoAiChatRequest {
|
||||||
|
message: string;
|
||||||
|
conversationId?: string;
|
||||||
|
/** GLOBAL_MANAGER 兼任店长时使用当前选中门店。 */
|
||||||
|
storeId?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 智能助手 SSE 事件。 */
|
||||||
|
export interface GaoAiStreamEvent {
|
||||||
|
event: string;
|
||||||
|
data: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 智能助手 HTTP 错误。 */
|
||||||
|
export class GaoAiHttpError extends Error {
|
||||||
|
readonly status: number;
|
||||||
|
readonly code?: string;
|
||||||
|
|
||||||
|
constructor(status: number, message: string, code?: string) {
|
||||||
|
super(message);
|
||||||
|
this.name = "GaoAiHttpError";
|
||||||
|
this.status = status;
|
||||||
|
this.code = code;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 智能助手流式响应错误。 */
|
||||||
|
export class GaoAiStreamError extends Error {
|
||||||
|
readonly code?: string;
|
||||||
|
|
||||||
|
constructor(message: string, code?: string) {
|
||||||
|
super(message);
|
||||||
|
this.name = "GaoAiStreamError";
|
||||||
|
this.code = code;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const chatPath = "/gao/ai/chat";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 发起门店智能助手聊天请求。
|
||||||
|
*
|
||||||
|
* @param request 聊天请求
|
||||||
|
* @param token 当前登录令牌
|
||||||
|
* @param signal 请求取消信号
|
||||||
|
*/
|
||||||
|
export async function chat(request: GaoAiChatRequest, token: string, signal: AbortSignal): Promise<Response> {
|
||||||
|
const apiBaseURL = import.meta.env.VITE_API_BASE_URL as string | undefined;
|
||||||
|
const url = new URL(chatPath, apiBaseURL || window.location.origin);
|
||||||
|
const headers: Record<string, string> = {
|
||||||
|
Accept: "text/event-stream",
|
||||||
|
"Content-Type": "application/json"
|
||||||
|
};
|
||||||
|
if (token) {
|
||||||
|
// 系统现有接口使用 Token;Authorization 兼容智能助手实施协议。
|
||||||
|
headers.Authorization = `Bearer ${token}`;
|
||||||
|
headers.Token = token;
|
||||||
|
}
|
||||||
|
|
||||||
|
return await fetch(url, {
|
||||||
|
method: "POST",
|
||||||
|
headers,
|
||||||
|
body: JSON.stringify(request),
|
||||||
|
credentials: "include",
|
||||||
|
signal
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 读取并解析 SSE 流。
|
||||||
|
*
|
||||||
|
* @param response 聊天响应
|
||||||
|
* @param onEvent 事件处理函数
|
||||||
|
*/
|
||||||
|
export async function readSseStream(
|
||||||
|
response: Response,
|
||||||
|
onEvent: (event: GaoAiStreamEvent) => Promise<void>
|
||||||
|
): Promise<void> {
|
||||||
|
if (!response.body) {
|
||||||
|
throw new GaoAiStreamError("智能助手没有返回可读取的数据流", "EMPTY_STREAM");
|
||||||
|
}
|
||||||
|
|
||||||
|
const reader = response.body.getReader();
|
||||||
|
const decoder = new TextDecoder();
|
||||||
|
let buffer = "";
|
||||||
|
|
||||||
|
try {
|
||||||
|
while (true) {
|
||||||
|
const { done, value } = await reader.read();
|
||||||
|
if (done) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
buffer += decoder.decode(value, { stream: true });
|
||||||
|
buffer = await consumeSseBuffer(buffer, onEvent, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
buffer += decoder.decode();
|
||||||
|
await consumeSseBuffer(buffer, onEvent, true);
|
||||||
|
} finally {
|
||||||
|
reader.releaseLock();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function consumeSseBuffer(
|
||||||
|
buffer: string,
|
||||||
|
onEvent: (event: GaoAiStreamEvent) => Promise<void>,
|
||||||
|
isFinal: boolean
|
||||||
|
): Promise<string> {
|
||||||
|
const normalizedBuffer = buffer.replaceAll("\r\n", "\n").replaceAll("\r", "\n");
|
||||||
|
const blockList = normalizedBuffer.split("\n\n");
|
||||||
|
const remain = isFinal ? "" : blockList.pop() || "";
|
||||||
|
for (const block of blockList) {
|
||||||
|
const event = parseSseBlock(block);
|
||||||
|
if (event) {
|
||||||
|
await onEvent(event);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (isFinal && remain.trim()) {
|
||||||
|
const event = parseSseBlock(remain);
|
||||||
|
if (event) {
|
||||||
|
await onEvent(event);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return remain;
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseSseBlock(block: string): GaoAiStreamEvent | undefined {
|
||||||
|
let event = "message";
|
||||||
|
const dataLineList: string[] = [];
|
||||||
|
for (const line of block.split("\n")) {
|
||||||
|
if (line.startsWith("event:")) {
|
||||||
|
event = line.slice(6).trim() || "message";
|
||||||
|
} else if (line.startsWith("data:")) {
|
||||||
|
const data = line.slice(5);
|
||||||
|
dataLineList.push(data.startsWith(" ") ? data.slice(1) : data);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!dataLineList.length) {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
return { event, data: dataLineList.join("\n") };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 将非 2xx 响应转换为不携带原始响应正文的错误。 */
|
||||||
|
export async function ensureChatResponse(response: Response): Promise<void> {
|
||||||
|
if (response.ok) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let code: string | undefined;
|
||||||
|
let message = "智能助手请求失败,请稍后重试";
|
||||||
|
try {
|
||||||
|
const payload = await response.json() as {
|
||||||
|
code?: unknown;
|
||||||
|
message?: unknown;
|
||||||
|
error?: unknown;
|
||||||
|
};
|
||||||
|
if (typeof payload.code === "string") {
|
||||||
|
code = payload.code;
|
||||||
|
}
|
||||||
|
if (typeof payload.message === "string" && payload.message.trim()) {
|
||||||
|
message = payload.message.trim();
|
||||||
|
} else if (typeof payload.error === "string" && payload.error.trim()) {
|
||||||
|
message = payload.error.trim();
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// 非 JSON 错误响应使用上面的安全默认文案。
|
||||||
|
}
|
||||||
|
throw new GaoAiHttpError(response.status, message, code);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 解析 SSE 数据,解析失败时返回原始文本。 */
|
||||||
|
export function parseSseData(data: string): unknown {
|
||||||
|
if (data === "[DONE]") {
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
return JSON.parse(data) as unknown;
|
||||||
|
} catch {
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,398 @@
|
|||||||
|
import { computed, onUnmounted, shallowRef, toValue, watch, type MaybeRefOrGetter } from "vue";
|
||||||
|
import { useUserStore } from "timi-web-api/store";
|
||||||
|
import {
|
||||||
|
chat,
|
||||||
|
ensureChatResponse,
|
||||||
|
GaoAiHttpError,
|
||||||
|
GaoAiStreamError,
|
||||||
|
parseSseData,
|
||||||
|
readSseStream,
|
||||||
|
type GaoAiStreamEvent
|
||||||
|
} from "@/api/GaoAiAPI";
|
||||||
|
|
||||||
|
export type AiMessageRole = "user" | "assistant";
|
||||||
|
|
||||||
|
export interface AiCitation {
|
||||||
|
source?: string;
|
||||||
|
dataDomain?: string;
|
||||||
|
timeRange?: string;
|
||||||
|
caliber?: string;
|
||||||
|
generatedAt?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AiChatMessage {
|
||||||
|
id: number;
|
||||||
|
role: AiMessageRole;
|
||||||
|
content: string;
|
||||||
|
citationList: AiCitation[];
|
||||||
|
createdAt: number;
|
||||||
|
statusText?: string;
|
||||||
|
duration?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface UseAiChatOptions {
|
||||||
|
sessionKey: MaybeRefOrGetter<string>;
|
||||||
|
storeId?: MaybeRefOrGetter<string | undefined>;
|
||||||
|
scrollToBottom?: () => Promise<void>;
|
||||||
|
}
|
||||||
|
|
||||||
|
const conversationExpiredText = "AI 会话不存在或已过期";
|
||||||
|
|
||||||
|
/** 管理门店智能助手的会话、流式消息和取消操作。 */
|
||||||
|
export function useAiChat(options: UseAiChatOptions) {
|
||||||
|
const userStore = useUserStore();
|
||||||
|
const messages = shallowRef<AiChatMessage[]>([]);
|
||||||
|
const conversationId = shallowRef("");
|
||||||
|
const isGenerating = shallowRef(false);
|
||||||
|
const activeToolStatus = shallowRef("");
|
||||||
|
const lastError = shallowRef("");
|
||||||
|
const lastQuestion = shallowRef("");
|
||||||
|
const canRetry = computed(() => !!lastError.value && !!lastQuestion.value && !isGenerating.value);
|
||||||
|
let activeController: AbortController | undefined;
|
||||||
|
let messageSequence = 0;
|
||||||
|
|
||||||
|
async function sendMessage(message: string): Promise<void> {
|
||||||
|
const normalizedMessage = message.trim();
|
||||||
|
if (!normalizedMessage || isGenerating.value) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const userMessage: AiChatMessage = {
|
||||||
|
id: nextMessageId(),
|
||||||
|
role: "user",
|
||||||
|
content: normalizedMessage,
|
||||||
|
citationList: [],
|
||||||
|
createdAt: Date.now()
|
||||||
|
};
|
||||||
|
const assistantMessage: AiChatMessage = {
|
||||||
|
id: nextMessageId(),
|
||||||
|
role: "assistant",
|
||||||
|
content: "",
|
||||||
|
citationList: [],
|
||||||
|
createdAt: Date.now()
|
||||||
|
};
|
||||||
|
messages.value = [...messages.value, userMessage, assistantMessage];
|
||||||
|
lastQuestion.value = normalizedMessage;
|
||||||
|
lastError.value = "";
|
||||||
|
isGenerating.value = true;
|
||||||
|
activeToolStatus.value = "";
|
||||||
|
const controller = new AbortController();
|
||||||
|
activeController = controller;
|
||||||
|
let hasRetriedExpiredConversation = false;
|
||||||
|
|
||||||
|
try {
|
||||||
|
while (true) {
|
||||||
|
resetAssistantMessage(assistantMessage.id);
|
||||||
|
try {
|
||||||
|
await readChatStream(normalizedMessage, assistantMessage.id, controller);
|
||||||
|
break;
|
||||||
|
} catch (error) {
|
||||||
|
if (
|
||||||
|
!hasRetriedExpiredConversation
|
||||||
|
&& !!conversationId.value
|
||||||
|
&& isExpiredConversationError(error)
|
||||||
|
) {
|
||||||
|
hasRetriedExpiredConversation = true;
|
||||||
|
conversationId.value = "";
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
handleChatError(error, assistantMessage.id, controller.signal.aborted);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
if (activeController === controller) {
|
||||||
|
activeController = undefined;
|
||||||
|
}
|
||||||
|
isGenerating.value = false;
|
||||||
|
activeToolStatus.value = "";
|
||||||
|
await scrollToBottom();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function stopGeneration(): void {
|
||||||
|
if (!isGenerating.value) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
activeController?.abort();
|
||||||
|
activeToolStatus.value = "";
|
||||||
|
const assistantMessage = [...messages.value].reverse().find(item => item.role === "assistant");
|
||||||
|
if (assistantMessage) {
|
||||||
|
updateMessage(assistantMessage.id, { statusText: "已停止生成,可重新提问" });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function resetConversation(): void {
|
||||||
|
activeController?.abort();
|
||||||
|
activeController = undefined;
|
||||||
|
messages.value = [];
|
||||||
|
conversationId.value = "";
|
||||||
|
isGenerating.value = false;
|
||||||
|
activeToolStatus.value = "";
|
||||||
|
lastError.value = "";
|
||||||
|
lastQuestion.value = "";
|
||||||
|
}
|
||||||
|
|
||||||
|
async function retryLastMessage(): Promise<void> {
|
||||||
|
if (canRetry.value) {
|
||||||
|
await sendMessage(lastQuestion.value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function readChatStream(message: string, assistantId: number, controller: AbortController): Promise<void> {
|
||||||
|
const storeId = options.storeId ? toValue(options.storeId) : undefined;
|
||||||
|
const request = {
|
||||||
|
message,
|
||||||
|
...(conversationId.value ? { conversationId: conversationId.value } : {}),
|
||||||
|
...(storeId ? { storeId } : {})
|
||||||
|
};
|
||||||
|
const response = await chat(request, userStore.token, controller.signal);
|
||||||
|
await ensureChatResponse(response);
|
||||||
|
let hasDoneEvent = false;
|
||||||
|
await readSseStream(response, async (event) => {
|
||||||
|
hasDoneEvent = await handleStreamEvent(event, assistantId, hasDoneEvent);
|
||||||
|
await options.scrollToBottom?.();
|
||||||
|
});
|
||||||
|
if (!hasDoneEvent && !controller.signal.aborted) {
|
||||||
|
throw new GaoAiStreamError("智能助手连接中断,请重试", "DIFY_STREAM_ERROR");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleStreamEvent(event: GaoAiStreamEvent, assistantId: number, hasDoneEvent: boolean): Promise<boolean> {
|
||||||
|
const payload = parseSseData(event.data);
|
||||||
|
switch (event.event) {
|
||||||
|
case "message":
|
||||||
|
appendAssistantText(assistantId, extractText(payload));
|
||||||
|
return hasDoneEvent;
|
||||||
|
case "tool_status":
|
||||||
|
activeToolStatus.value = formatToolStatus(payload);
|
||||||
|
return hasDoneEvent;
|
||||||
|
case "citation":
|
||||||
|
appendCitation(assistantId, normalizeCitation(payload));
|
||||||
|
return hasDoneEvent;
|
||||||
|
case "done":
|
||||||
|
applyDonePayload(assistantId, payload);
|
||||||
|
return true;
|
||||||
|
case "error":
|
||||||
|
throw createStreamError(payload);
|
||||||
|
default:
|
||||||
|
return hasDoneEvent;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function applyDonePayload(assistantId: number, payload: unknown): void {
|
||||||
|
if (!isRecord(payload)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const nextConversationId = getString(payload.conversationId);
|
||||||
|
if (nextConversationId) {
|
||||||
|
conversationId.value = nextConversationId;
|
||||||
|
}
|
||||||
|
const duration = getNumber(payload.duration);
|
||||||
|
updateMessage(assistantId, {
|
||||||
|
createdAt: Date.now(),
|
||||||
|
duration: duration === undefined ? undefined : duration
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function appendAssistantText(assistantId: number, text: string): void {
|
||||||
|
if (!text) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const message = messages.value.find(item => item.id === assistantId);
|
||||||
|
if (!message) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
updateMessage(assistantId, { content: message.content + text, statusText: undefined });
|
||||||
|
}
|
||||||
|
|
||||||
|
function appendCitation(assistantId: number, citation?: AiCitation): void {
|
||||||
|
if (!citation) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const message = messages.value.find(item => item.id === assistantId);
|
||||||
|
if (!message) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
updateMessage(assistantId, { citationList: [...message.citationList, citation] });
|
||||||
|
}
|
||||||
|
|
||||||
|
function updateMessage(id: number, patch: Partial<AiChatMessage>): void {
|
||||||
|
messages.value = messages.value.map(item => item.id === id ? { ...item, ...patch } : item);
|
||||||
|
}
|
||||||
|
|
||||||
|
function resetAssistantMessage(id: number): void {
|
||||||
|
updateMessage(id, {
|
||||||
|
content: "",
|
||||||
|
citationList: [],
|
||||||
|
statusText: undefined,
|
||||||
|
duration: undefined,
|
||||||
|
createdAt: Date.now()
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleChatError(error: unknown, assistantId: number, isAborted: boolean): void {
|
||||||
|
if (isAborted) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const message = getChatErrorMessage(error);
|
||||||
|
lastError.value = message;
|
||||||
|
updateMessage(assistantId, { statusText: message });
|
||||||
|
}
|
||||||
|
|
||||||
|
function clearMessages(): void {
|
||||||
|
messages.value = [];
|
||||||
|
}
|
||||||
|
|
||||||
|
function nextMessageId(): number {
|
||||||
|
messageSequence += 1;
|
||||||
|
return messageSequence;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function scrollToBottom(): Promise<void> {
|
||||||
|
await options.scrollToBottom?.();
|
||||||
|
}
|
||||||
|
|
||||||
|
watch(() => toValue(options.sessionKey), () => {
|
||||||
|
resetConversation();
|
||||||
|
}, { flush: "sync" });
|
||||||
|
|
||||||
|
onUnmounted(() => {
|
||||||
|
activeController?.abort();
|
||||||
|
clearMessages();
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
messages,
|
||||||
|
isGenerating,
|
||||||
|
activeToolStatus,
|
||||||
|
lastError,
|
||||||
|
canRetry,
|
||||||
|
sendMessage,
|
||||||
|
stopGeneration,
|
||||||
|
resetConversation,
|
||||||
|
retryLastMessage
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function isExpiredConversationError(error: unknown): boolean {
|
||||||
|
if (error instanceof GaoAiHttpError || error instanceof GaoAiStreamError) {
|
||||||
|
return error.message.includes(conversationExpiredText)
|
||||||
|
|| error.code?.toLowerCase().includes("session") === true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
function extractText(payload: unknown): string {
|
||||||
|
if (typeof payload === "string") {
|
||||||
|
return payload === "[DONE]" ? "" : payload;
|
||||||
|
}
|
||||||
|
if (!isRecord(payload)) {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
return getString(payload.answer) || getString(payload.text) || getString(payload.content) || "";
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatToolStatus(payload: unknown): string {
|
||||||
|
if (!isRecord(payload)) {
|
||||||
|
return "正在查询实时业务数据…";
|
||||||
|
}
|
||||||
|
const status = getString(payload.status);
|
||||||
|
return status === "finished" ? "实时业务数据查询完成" : "正在查询实时业务数据…";
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeCitation(payload: unknown): AiCitation | undefined {
|
||||||
|
if (typeof payload === "string") {
|
||||||
|
return payload ? { source: payload } : undefined;
|
||||||
|
}
|
||||||
|
if (!isRecord(payload)) {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
const citation: AiCitation = {
|
||||||
|
source: getString(payload.source),
|
||||||
|
dataDomain: getString(payload.dataDomain) || getString(payload.domain),
|
||||||
|
timeRange: getString(payload.timeRange) || formatScope(payload.scope),
|
||||||
|
caliber: getString(payload.caliber) || getString(payload.metric),
|
||||||
|
generatedAt: getDisplayText(payload.generatedAt) || getDisplayText(payload.generated_at)
|
||||||
|
};
|
||||||
|
return Object.values(citation).some(Boolean) ? citation : undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
function createStreamError(payload: unknown): GaoAiStreamError {
|
||||||
|
if (!isRecord(payload)) {
|
||||||
|
return new GaoAiStreamError("智能助手查询失败,请稍后重试", "DIFY_ERROR");
|
||||||
|
}
|
||||||
|
return new GaoAiStreamError(
|
||||||
|
getString(payload.message) || "智能助手查询失败,请稍后重试",
|
||||||
|
getString(payload.code)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function getChatErrorMessage(error: unknown): string {
|
||||||
|
if (error instanceof GaoAiHttpError) {
|
||||||
|
if (error.status === 401) {
|
||||||
|
return error.message.includes("会话") ? error.message : "登录已过期,请重新登录";
|
||||||
|
}
|
||||||
|
if (error.status === 403) {
|
||||||
|
return "当前账号无权使用门店智能助手";
|
||||||
|
}
|
||||||
|
if (error.status === 429) {
|
||||||
|
return "请求过于频繁,请稍后再试";
|
||||||
|
}
|
||||||
|
return error.message;
|
||||||
|
}
|
||||||
|
if (error instanceof GaoAiStreamError) {
|
||||||
|
if (error.code === "DIFY_TIMEOUT") {
|
||||||
|
return "数据查询超时,请缩小时间范围后重试";
|
||||||
|
}
|
||||||
|
return error.message;
|
||||||
|
}
|
||||||
|
if (error instanceof DOMException && error.name === "AbortError") {
|
||||||
|
return "已停止生成,可重新提问";
|
||||||
|
}
|
||||||
|
if (error instanceof TypeError) {
|
||||||
|
return "连接中断,可重新提问";
|
||||||
|
}
|
||||||
|
return "智能助手暂时不可用,请稍后重试";
|
||||||
|
}
|
||||||
|
|
||||||
|
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||||
|
return typeof value === "object" && value !== null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function getString(value: unknown): string | undefined {
|
||||||
|
return typeof value === "string" && value.trim() ? value.trim() : undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
function getDisplayText(value: unknown): string | undefined {
|
||||||
|
const text = getString(value);
|
||||||
|
if (text) {
|
||||||
|
return text;
|
||||||
|
}
|
||||||
|
const timestamp = getNumber(value);
|
||||||
|
if (timestamp === undefined) {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
const milliseconds = timestamp < 100000000000 ? timestamp * 1000 : timestamp;
|
||||||
|
return new Date(milliseconds).toLocaleString("zh-CN", { hour12: false });
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatScope(value: unknown): string | undefined {
|
||||||
|
const text = getString(value);
|
||||||
|
if (text) {
|
||||||
|
return text;
|
||||||
|
}
|
||||||
|
if (!isRecord(value)) {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
const beginAt = getDisplayText(value.beginAt) || getDisplayText(value.begin);
|
||||||
|
const endAt = getDisplayText(value.endAt) || getDisplayText(value.end);
|
||||||
|
if (beginAt && endAt) {
|
||||||
|
return `${beginAt} 至 ${endAt}`;
|
||||||
|
}
|
||||||
|
return beginAt || endAt;
|
||||||
|
}
|
||||||
|
|
||||||
|
function getNumber(value: unknown): number | undefined {
|
||||||
|
return typeof value === "number" && Number.isFinite(value) ? value : undefined;
|
||||||
|
}
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { useUserStore } from "timi-web-api/store";
|
||||||
|
import AiChatPanel from "@/pages/ai/components/AiChatPanel.vue";
|
||||||
|
import { useCurrentStoreStore } from "@/store/currentStoreStore";
|
||||||
|
import { gaoRoleCodes } from "@/utils/permission";
|
||||||
|
|
||||||
|
defineOptions({
|
||||||
|
name: "AiChatPage"
|
||||||
|
});
|
||||||
|
|
||||||
|
const userStore = useUserStore();
|
||||||
|
const currentStoreStore = useCurrentStoreStore();
|
||||||
|
const sessionKey = computed(() => `${userStore.loginUser.user?.id || userStore.loginUser.id || ""}:${currentStoreStore.currentStoreId}`);
|
||||||
|
const canUseAi = computed(() => userStore.hasRoles(gaoRoleCodes.storeManager));
|
||||||
|
const isGlobalManager = computed(() => userStore.hasRoles(gaoRoleCodes.globalManager));
|
||||||
|
const aiStoreId = computed(() => canUseAi.value && isGlobalManager.value ? currentStoreStore.currentStoreId : undefined);
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div v-if="canUseAi" class="ai-chat-page">
|
||||||
|
<ai-chat-panel
|
||||||
|
:store-name="currentStoreStore.currentStoreName"
|
||||||
|
:session-key="sessionKey"
|
||||||
|
:store-id="aiStoreId"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<t-empty v-else description="当前账号无权使用门店智能助手" />
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style scoped lang="less">
|
||||||
|
.ai-chat-page {
|
||||||
|
height: 100%;
|
||||||
|
overflow: hidden;
|
||||||
|
min-height: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
:global(html.theme-dark) {
|
||||||
|
.ai-chat-page {
|
||||||
|
background: #10161f;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
/** 门店智能助手快捷问题。 */
|
||||||
|
export const aiQuickQuestionList = [
|
||||||
|
"今天门店经营怎么样?",
|
||||||
|
"本月销售额、订单数和应收款是多少?",
|
||||||
|
"哪些产品库存需要关注?",
|
||||||
|
"本月有哪些需要重点跟进的客户?",
|
||||||
|
"本月客户复购情况如何?"
|
||||||
|
] as const;
|
||||||
@@ -0,0 +1,131 @@
|
|||||||
|
<template>
|
||||||
|
<div class="composer">
|
||||||
|
<div v-if="lastError" class="error-bar">
|
||||||
|
<span class="error-text" v-text="lastError" />
|
||||||
|
<t-button v-if="canRetry" variant="text" size="small" content="重试" @click="emit('retry')" />
|
||||||
|
</div>
|
||||||
|
<t-form class="input-wrap glass-white" @submit.prevent="submitMessage">
|
||||||
|
<t-input
|
||||||
|
v-model="draft"
|
||||||
|
class="input"
|
||||||
|
borderless
|
||||||
|
:disabled="isGenerating"
|
||||||
|
:maxlength="256"
|
||||||
|
placeholder="问问小糕怎么个事(●'◡'●)…"
|
||||||
|
/>
|
||||||
|
<t-button
|
||||||
|
v-if="isGenerating"
|
||||||
|
class="send"
|
||||||
|
type="button"
|
||||||
|
size="small"
|
||||||
|
theme="danger"
|
||||||
|
content="停止"
|
||||||
|
@click="emit('stop')"
|
||||||
|
/>
|
||||||
|
<t-button
|
||||||
|
v-else
|
||||||
|
class="send"
|
||||||
|
type="submit"
|
||||||
|
size="small"
|
||||||
|
theme="primary"
|
||||||
|
content="发送"
|
||||||
|
/>
|
||||||
|
</t-form>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
<script setup lang="ts">
|
||||||
|
|
||||||
|
defineOptions({
|
||||||
|
name: "AiChatComposer"
|
||||||
|
});
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
isGenerating: boolean;
|
||||||
|
lastError: string;
|
||||||
|
canRetry: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
defineProps<Props>();
|
||||||
|
const draft = defineModel<string>({ required: true });
|
||||||
|
const emit = defineEmits<{
|
||||||
|
send: [message: string];
|
||||||
|
stop: [];
|
||||||
|
retry: [];
|
||||||
|
}>();
|
||||||
|
|
||||||
|
function submitMessage(): void {
|
||||||
|
const message = draft.value.trim();
|
||||||
|
if (!message) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
draft.value = "";
|
||||||
|
emit("send", message);
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
<style scoped lang="less">
|
||||||
|
.composer {
|
||||||
|
width: 100%;
|
||||||
|
|
||||||
|
.error-bar {
|
||||||
|
gap: .375rem;
|
||||||
|
display: flex;
|
||||||
|
padding: .5rem .75rem;
|
||||||
|
border-radius: .75rem;
|
||||||
|
color: #b42318;
|
||||||
|
font-size: .75rem;
|
||||||
|
background: #fef3f2;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
|
||||||
|
.error-text {
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.t-button {
|
||||||
|
color: #b42318;
|
||||||
|
flex: none;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.input-wrap {
|
||||||
|
--td-input-bg-color: transparent;
|
||||||
|
--td-button-border-radius: 1rem;
|
||||||
|
|
||||||
|
gap: .5rem;
|
||||||
|
border: 1px solid var(--td-component-border);
|
||||||
|
display: flex;
|
||||||
|
padding: .25rem .25rem .25rem .75rem;
|
||||||
|
margin-top: .5rem;
|
||||||
|
box-shadow: 0 .5rem 1.5rem rgba(15, 23, 42, .12);
|
||||||
|
align-items: center;
|
||||||
|
border-radius: 1rem;
|
||||||
|
|
||||||
|
.input {
|
||||||
|
min-width: 0;
|
||||||
|
flex: 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
.send {
|
||||||
|
width: 4rem;
|
||||||
|
flex: none;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes rotate {
|
||||||
|
to {
|
||||||
|
transform: rotate(360deg);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
:global(html.theme-dark) {
|
||||||
|
.error-bar {
|
||||||
|
color: #fda29b;
|
||||||
|
background: rgba(180, 35, 24, .18);
|
||||||
|
|
||||||
|
.t-button {
|
||||||
|
color: #fda29b;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,314 @@
|
|||||||
|
<template>
|
||||||
|
<div ref="messageList" class="message-list" role="log" aria-live="polite">
|
||||||
|
<div v-if="!props.messages.length" class="welcome">
|
||||||
|
<div class="welcome-icon"><t-icon name="robot-2" size="2rem" /></div>
|
||||||
|
<h3>今天想了解什么?</h3>
|
||||||
|
<p>我会根据当前门店的实时业务数据回答经营问题。</p>
|
||||||
|
<div class="quick-list">
|
||||||
|
<t-button
|
||||||
|
v-for="question in props.quickQuestionList"
|
||||||
|
:key="question"
|
||||||
|
class="quick-question"
|
||||||
|
variant="outline"
|
||||||
|
size="small"
|
||||||
|
@click="emit('selectQuestion', question)"
|
||||||
|
>
|
||||||
|
<span v-text="question" />
|
||||||
|
</t-button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<article
|
||||||
|
v-for="message in props.messages"
|
||||||
|
:key="message.id"
|
||||||
|
class="message-row"
|
||||||
|
:class="message.role"
|
||||||
|
>
|
||||||
|
<div class="avatar">
|
||||||
|
<t-icon :name="message.role === 'assistant' ? 'robot-2' : 'user'" />
|
||||||
|
</div>
|
||||||
|
<div class="message-main">
|
||||||
|
<div class="role-name" v-text="message.role === 'assistant' ? 'AI 小糕' : '店长'" />
|
||||||
|
<div class="bubble" :class="message.role">
|
||||||
|
<div v-if="message.content && message.role === 'assistant'" class="content markdown-content">
|
||||||
|
<markdown-view :content="message.content" />
|
||||||
|
</div>
|
||||||
|
<div v-else-if="message.content" class="content" v-text="message.content" />
|
||||||
|
<div v-else-if="message.role === 'assistant' && props.isGenerating" class="typing">
|
||||||
|
<span /><span /><span />
|
||||||
|
</div>
|
||||||
|
<div v-if="message.role === 'assistant' && message.citationList.length" class="citation-list">
|
||||||
|
<div
|
||||||
|
v-for="(citation, index) in message.citationList"
|
||||||
|
:key="`${message.id}-${index}`"
|
||||||
|
class="citation"
|
||||||
|
>
|
||||||
|
<span class="citation-label">数据来源</span>
|
||||||
|
<span v-text="getCitationText(citation)" />
|
||||||
|
<span v-if="citation.generatedAt" class="citation-time" v-text="`生成时间:${citation.generatedAt}`" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div v-if="message.role === 'assistant' && (message.statusText || (!props.isGenerating && message.content))" class="message-status" v-text="getMessageStatus(message)" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</article>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
<script setup lang="ts">
|
||||||
|
import { MarkdownView } from "timi-web";
|
||||||
|
import type { AiChatMessage } from "@/composables/useAiChat";
|
||||||
|
|
||||||
|
defineOptions({
|
||||||
|
name: "AiChatMessageList"
|
||||||
|
});
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
messages: AiChatMessage[];
|
||||||
|
isGenerating: boolean;
|
||||||
|
quickQuestionList: readonly string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
const props = defineProps<Props>();
|
||||||
|
const emit = defineEmits<{
|
||||||
|
selectQuestion: [question: string];
|
||||||
|
}>();
|
||||||
|
|
||||||
|
const messageListRef = useTemplateRef<HTMLElement>("messageList");
|
||||||
|
|
||||||
|
async function scrollToBottom(): Promise<void> {
|
||||||
|
await nextTick();
|
||||||
|
const element = messageListRef.value;
|
||||||
|
if (element) {
|
||||||
|
element.scrollTop = element.scrollHeight;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function getMessageStatus(message: AiChatMessage): string {
|
||||||
|
if (message.statusText) {
|
||||||
|
return message.statusText;
|
||||||
|
}
|
||||||
|
const timeText = `生成时间:${formatDateTime(message.createdAt)}`;
|
||||||
|
if (message.duration !== undefined) {
|
||||||
|
return `${timeText} · 查询耗时:${formatDuration(message.duration)}`;
|
||||||
|
}
|
||||||
|
return timeText;
|
||||||
|
}
|
||||||
|
|
||||||
|
function getCitationText(citation: AiChatMessage["citationList"][number]): string {
|
||||||
|
const textList = [
|
||||||
|
citation.dataDomain ? `数据域:${citation.dataDomain}` : "",
|
||||||
|
citation.timeRange ? `统计范围:${citation.timeRange}` : "",
|
||||||
|
citation.caliber ? `统计口径:${citation.caliber}` : "",
|
||||||
|
citation.source ? `来源:${citation.source}` : ""
|
||||||
|
].filter(Boolean);
|
||||||
|
return textList.join(" · ");
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatDateTime(timestamp: number): string {
|
||||||
|
return new Date(timestamp).toLocaleString("zh-CN", { hour12: false });
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatDuration(duration: number): string {
|
||||||
|
if (duration < 1000) {
|
||||||
|
return `${duration} 毫秒`;
|
||||||
|
}
|
||||||
|
return `${(duration / 1000).toFixed(1)} 秒`;
|
||||||
|
}
|
||||||
|
|
||||||
|
defineExpose({
|
||||||
|
scrollToBottom
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
<style scoped lang="less">
|
||||||
|
.message-list {
|
||||||
|
gap: 1rem;
|
||||||
|
flex: 1;
|
||||||
|
display: flex;
|
||||||
|
padding: .5rem 1rem calc(12rem + env(safe-area-inset-bottom, 0px));
|
||||||
|
min-height: 0;
|
||||||
|
overflow-y: auto;
|
||||||
|
flex-direction: column;
|
||||||
|
|
||||||
|
.welcome {
|
||||||
|
margin: auto 0;
|
||||||
|
text-align: center;
|
||||||
|
|
||||||
|
.welcome-icon {
|
||||||
|
color: #0f766e;
|
||||||
|
width: 4rem;
|
||||||
|
height: 4rem;
|
||||||
|
margin: 0 auto 1rem;
|
||||||
|
border-radius: 1.25rem;
|
||||||
|
display: flex;
|
||||||
|
background: #ccfbf1;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
h3 {
|
||||||
|
margin: 0;
|
||||||
|
font-size: 1.125rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
p {
|
||||||
|
color: var(--td-text-color-secondary);
|
||||||
|
margin: .5rem auto 1rem;
|
||||||
|
font-size: .8125rem;
|
||||||
|
line-height: 1.5;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.quick-list {
|
||||||
|
gap: .5rem;
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
justify-content: center;
|
||||||
|
|
||||||
|
.quick-question {
|
||||||
|
max-width: 100%;
|
||||||
|
white-space: normal;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.message-row {
|
||||||
|
gap: .5rem;
|
||||||
|
display: flex;
|
||||||
|
align-items: flex-start;
|
||||||
|
|
||||||
|
&.user {
|
||||||
|
flex-direction: row-reverse;
|
||||||
|
}
|
||||||
|
|
||||||
|
.avatar {
|
||||||
|
flex: none;
|
||||||
|
color: #0f766e;
|
||||||
|
width: 2rem;
|
||||||
|
height: 2rem;
|
||||||
|
display: flex;
|
||||||
|
background: #ccfbf1;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
&.user .avatar {
|
||||||
|
color: #2563eb;
|
||||||
|
background: #dbeafe;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message-main {
|
||||||
|
max-width: calc(100% - 2.5rem);
|
||||||
|
}
|
||||||
|
|
||||||
|
&.user .message-main {
|
||||||
|
text-align: right;
|
||||||
|
}
|
||||||
|
|
||||||
|
.role-name {
|
||||||
|
color: var(--td-text-color-secondary);
|
||||||
|
margin: 0 .25rem .25rem;
|
||||||
|
font-size: .6875rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.bubble {
|
||||||
|
color: var(--td-text-color-primary);
|
||||||
|
padding: .75rem;
|
||||||
|
border-radius: .25rem 1rem 1rem 1rem;
|
||||||
|
background: var(--ai-bubble);
|
||||||
|
text-align: left;
|
||||||
|
box-shadow: 0 .25rem 1rem rgba(15, 23, 42, .05);
|
||||||
|
|
||||||
|
&.user {
|
||||||
|
color: white;
|
||||||
|
border-radius: 1rem .25rem 1rem 1rem;
|
||||||
|
background: #0f766e;
|
||||||
|
}
|
||||||
|
|
||||||
|
.content {
|
||||||
|
font-size: .875rem;
|
||||||
|
line-height: 1.65;
|
||||||
|
white-space: pre-wrap;
|
||||||
|
word-break: break-word;
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown-content {
|
||||||
|
white-space: normal;
|
||||||
|
|
||||||
|
:deep(.tui-markdown-view) {
|
||||||
|
width: auto;
|
||||||
|
font-size: .875rem;
|
||||||
|
line-height: 1.65;
|
||||||
|
word-break: break-word;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.typing {
|
||||||
|
gap: .25rem;
|
||||||
|
display: flex;
|
||||||
|
padding: .25rem .125rem;
|
||||||
|
align-items: center;
|
||||||
|
|
||||||
|
span {
|
||||||
|
width: .375rem;
|
||||||
|
height: .375rem;
|
||||||
|
border-radius: 50%;
|
||||||
|
background: #0f766e;
|
||||||
|
animation: typing 1.2s infinite ease-in-out;
|
||||||
|
|
||||||
|
&:nth-child(2) {
|
||||||
|
animation-delay: .16s;
|
||||||
|
}
|
||||||
|
|
||||||
|
&:nth-child(3) {
|
||||||
|
animation-delay: .32s;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.citation-list {
|
||||||
|
gap: .375rem;
|
||||||
|
margin-top: .75rem;
|
||||||
|
padding-top: .625rem;
|
||||||
|
display: flex;
|
||||||
|
border-top: 1px solid var(--td-component-border);
|
||||||
|
flex-direction: column;
|
||||||
|
|
||||||
|
.citation {
|
||||||
|
color: var(--td-text-color-secondary);
|
||||||
|
display: flex;
|
||||||
|
font-size: .6875rem;
|
||||||
|
line-height: 1.4;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.citation-label {
|
||||||
|
color: #0f766e;
|
||||||
|
margin-right: .25rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.citation-time {
|
||||||
|
width: 100%;
|
||||||
|
margin-top: .125rem;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.message-status {
|
||||||
|
color: var(--td-text-color-secondary);
|
||||||
|
margin-top: .5rem;
|
||||||
|
font-size: .6875rem;
|
||||||
|
line-height: 1.4;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes typing {
|
||||||
|
0%, 60%, 100% {
|
||||||
|
opacity: .35;
|
||||||
|
transform: translateY(0);
|
||||||
|
}
|
||||||
|
30% {
|
||||||
|
opacity: 1;
|
||||||
|
transform: translateY(-.1875rem);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,124 @@
|
|||||||
|
<template>
|
||||||
|
<section class="ai-chat-panel" aria-label="门店经营助手">
|
||||||
|
<ai-chat-message-list
|
||||||
|
ref="messageList"
|
||||||
|
:messages="messages"
|
||||||
|
:is-generating="isGenerating"
|
||||||
|
:quick-question-list="aiQuickQuestionList"
|
||||||
|
@select-question="selectQuestion"
|
||||||
|
/>
|
||||||
|
<div class="bottom-area">
|
||||||
|
<div v-if="activeToolStatus" class="tool-status">
|
||||||
|
<t-icon name="loading" size="1rem" />
|
||||||
|
<span v-text="activeToolStatus" />
|
||||||
|
</div>
|
||||||
|
<ai-chat-composer
|
||||||
|
v-model="draft"
|
||||||
|
:is-generating="isGenerating"
|
||||||
|
:last-error="lastError"
|
||||||
|
:can-retry="canRetry"
|
||||||
|
@send="submitMessage"
|
||||||
|
@stop="stopGeneration"
|
||||||
|
@retry="retryLastMessage"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
</template>
|
||||||
|
<script setup lang="ts">
|
||||||
|
import { useAiChat } from "@/composables/useAiChat";
|
||||||
|
import AiChatComposer from "@/pages/ai/components/AiChatComposer.vue";
|
||||||
|
import AiChatMessageList from "@/pages/ai/components/AiChatMessageList.vue";
|
||||||
|
import { aiQuickQuestionList } from "@/pages/ai/aiChatQuestions";
|
||||||
|
|
||||||
|
defineOptions({
|
||||||
|
name: "AiChatPanel"
|
||||||
|
});
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
storeName: string;
|
||||||
|
sessionKey: string;
|
||||||
|
storeId?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
const props = defineProps<Props>();
|
||||||
|
type MessageListExpose = {
|
||||||
|
scrollToBottom: () => Promise<void>;
|
||||||
|
};
|
||||||
|
|
||||||
|
const messageListRef = useTemplateRef<MessageListExpose>("messageList");
|
||||||
|
const draft = shallowRef("");
|
||||||
|
const { messages, isGenerating, activeToolStatus, lastError, canRetry, sendMessage, stopGeneration, retryLastMessage } = useAiChat({
|
||||||
|
sessionKey: () => props.sessionKey,
|
||||||
|
storeId: () => props.storeId,
|
||||||
|
scrollToBottom
|
||||||
|
});
|
||||||
|
|
||||||
|
async function submitMessage(message: string): Promise<void> {
|
||||||
|
await sendMessage(message);
|
||||||
|
}
|
||||||
|
|
||||||
|
function selectQuestion(question: string): void {
|
||||||
|
draft.value = question;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function scrollToBottom(): Promise<void> {
|
||||||
|
await messageListRef.value?.scrollToBottom();
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
<style scoped lang="less">
|
||||||
|
.ai-chat-panel {
|
||||||
|
height: 100%;
|
||||||
|
display: flex;
|
||||||
|
position: relative;
|
||||||
|
overflow: hidden;
|
||||||
|
min-height: 0;
|
||||||
|
background: var(--ai-background);
|
||||||
|
padding-top: var(--app-nav-height);
|
||||||
|
flex-direction: column;
|
||||||
|
|
||||||
|
.bottom-area {
|
||||||
|
inset: auto 1rem calc(1rem + env(safe-area-inset-bottom, 0px));
|
||||||
|
width: auto;
|
||||||
|
margin: 0 auto;
|
||||||
|
z-index: 2;
|
||||||
|
position: absolute;
|
||||||
|
max-width: 40rem;
|
||||||
|
|
||||||
|
.tool-status {
|
||||||
|
gap: .375rem;
|
||||||
|
margin-bottom: .5rem;
|
||||||
|
color: #0f766e;
|
||||||
|
padding: .5rem .75rem;
|
||||||
|
border-radius: .75rem;
|
||||||
|
display: flex;
|
||||||
|
font-size: .75rem;
|
||||||
|
background: var(--ai-soft);
|
||||||
|
align-items: center;
|
||||||
|
|
||||||
|
.t-icon {
|
||||||
|
animation: rotate 1s linear infinite;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes rotate {
|
||||||
|
to {
|
||||||
|
transform: rotate(360deg);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
:global(:root) {
|
||||||
|
--ai-background: rgba(255, 255, 255, .98);
|
||||||
|
--ai-bubble: #f5f6f8;
|
||||||
|
--ai-input: white;
|
||||||
|
--ai-soft: #f0fdfa;
|
||||||
|
}
|
||||||
|
|
||||||
|
:global(html.theme-dark) {
|
||||||
|
--ai-background: rgba(15, 23, 42, .98);
|
||||||
|
--ai-bubble: #1e293b;
|
||||||
|
--ai-input: #111827;
|
||||||
|
--ai-soft: rgba(20, 184, 166, .12);
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -39,6 +39,18 @@
|
|||||||
<t-icon name="help-circle"/>
|
<t-icon name="help-circle"/>
|
||||||
</template>
|
</template>
|
||||||
</t-button>
|
</t-button>
|
||||||
|
<t-button
|
||||||
|
v-if="canUseAi"
|
||||||
|
class="ai"
|
||||||
|
theme="primary"
|
||||||
|
variant="text"
|
||||||
|
content="AI 小糕"
|
||||||
|
@click="openAiChat"
|
||||||
|
>
|
||||||
|
<template #icon>
|
||||||
|
<t-icon name="robot-2" />
|
||||||
|
</template>
|
||||||
|
</t-button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
@@ -46,7 +58,7 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { NotifyAPI, useUserStore } from "timi-web-api";
|
import { NotifyAPI, useUserStore } from "timi-web-api";
|
||||||
import { useNavBarStore } from "@/store/navBarStore";
|
import { useNavBarStore } from "@/store/navBarStore";
|
||||||
import { corePermissionCodes, permissionCodes } from "@/utils/permission";
|
import { corePermissionCodes, gaoRoleCodes, permissionCodes } from "@/utils/permission";
|
||||||
|
|
||||||
defineOptions({
|
defineOptions({
|
||||||
name: "HomeTab"
|
name: "HomeTab"
|
||||||
@@ -136,6 +148,11 @@ const visibleEntryGroupList = computed(() => entryGroupList
|
|||||||
const visibleEntryCount = computed(() => visibleEntryGroupList.value
|
const visibleEntryCount = computed(() => visibleEntryGroupList.value
|
||||||
.reduce((count, group) => count + group.entryList.length, 0));
|
.reduce((count, group) => count + group.entryList.length, 0));
|
||||||
const canReadNotify = computed(() => userStore.hasPermissions(corePermissionCodes.notify.read));
|
const canReadNotify = computed(() => userStore.hasPermissions(corePermissionCodes.notify.read));
|
||||||
|
const canUseAi = computed(() => userStore.hasRoles(gaoRoleCodes.storeManager));
|
||||||
|
|
||||||
|
async function openAiChat(): Promise<void> {
|
||||||
|
await router.push("/ai/chat");
|
||||||
|
}
|
||||||
|
|
||||||
async function loadUnreadNotifyCount(): Promise<void> {
|
async function loadUnreadNotifyCount(): Promise<void> {
|
||||||
try {
|
try {
|
||||||
@@ -240,12 +257,16 @@ onUnmounted(() => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
.help-wrap {
|
.help-wrap {
|
||||||
|
--td-button-border-radius: 1rem;
|
||||||
|
|
||||||
|
gap: 1rem;
|
||||||
width: fit-content;
|
width: fit-content;
|
||||||
margin: 0 auto;
|
margin: 1rem auto 0 auto;
|
||||||
|
display: flex;
|
||||||
.help {
|
align-items: center;
|
||||||
--td-button-border-radius: 1rem;
|
|
||||||
|
|
||||||
|
.help,
|
||||||
|
.ai {
|
||||||
width: 8rem;
|
width: 8rem;
|
||||||
background: white;
|
background: white;
|
||||||
box-shadow: var(--td-shadow-3);
|
box-shadow: var(--td-shadow-3);
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import { createRouter, createWebHistory, type RouteLocationNormalized } from "vue-router";
|
import { createRouter, createWebHistory, type RouteLocationNormalized } from "vue-router";
|
||||||
import RootLayout from "@/layout/RootLayout.vue";
|
import RootLayout from "@/layout/RootLayout.vue";
|
||||||
|
import aiRoutes from "@/router/routes/aiRoutes";
|
||||||
import chartRoutes from "@/router/routes/chartRoutes";
|
import chartRoutes from "@/router/routes/chartRoutes";
|
||||||
import customerRoutes from "@/router/routes/customerRoutes";
|
import customerRoutes from "@/router/routes/customerRoutes";
|
||||||
import { managementAccountRoutes, managementSettingRoutes, storeRoutes } from "@/router/routes/managementRoutes";
|
import { managementAccountRoutes, managementSettingRoutes, storeRoutes } from "@/router/routes/managementRoutes";
|
||||||
@@ -92,6 +93,7 @@ const router = createRouter({
|
|||||||
},
|
},
|
||||||
children: [
|
children: [
|
||||||
...tabRoutes,
|
...tabRoutes,
|
||||||
|
...aiRoutes,
|
||||||
...detailRoutes
|
...detailRoutes
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
@@ -130,6 +132,9 @@ router.beforeEach(async (to) => {
|
|||||||
async function resolveStoreAccessRedirect(to: RouteLocationNormalized): Promise<string | undefined> {
|
async function resolveStoreAccessRedirect(to: RouteLocationNormalized): Promise<string | undefined> {
|
||||||
const userStore = useUserStore();
|
const userStore = useUserStore();
|
||||||
const routeName = String(to.name || "");
|
const routeName = String(to.name || "");
|
||||||
|
if (routeName === "AiChat" && !userStore.hasRoles(gaoRoleCodes.storeManager)) {
|
||||||
|
return "/management";
|
||||||
|
}
|
||||||
const storeDiaryRouteNameList = ["StoreDiaryList", "StoreDiaryCreate", "StoreDiaryDetail", "StoreDiaryEdit"];
|
const storeDiaryRouteNameList = ["StoreDiaryList", "StoreDiaryCreate", "StoreDiaryDetail", "StoreDiaryEdit"];
|
||||||
if (storeDiaryRouteNameList.includes(routeName)) {
|
if (storeDiaryRouteNameList.includes(routeName)) {
|
||||||
if (!userStore.hasRoles(gaoRoleCodes.storeManager)) {
|
if (!userStore.hasRoles(gaoRoleCodes.storeManager)) {
|
||||||
|
|||||||
@@ -0,0 +1,20 @@
|
|||||||
|
import type { RouteRecordRaw } from "vue-router";
|
||||||
|
|
||||||
|
const aiRoutes: RouteRecordRaw[] = [
|
||||||
|
{
|
||||||
|
path: "/ai/chat",
|
||||||
|
name: "AiChat",
|
||||||
|
component: () => import("@/pages/ai/AiChatPage.vue"),
|
||||||
|
meta: {
|
||||||
|
depth: 3,
|
||||||
|
navBarVisible: true,
|
||||||
|
navBarCanBack: true,
|
||||||
|
navBarTitle: "AI 小糕",
|
||||||
|
tabBarVisible: false,
|
||||||
|
bodyBackground: "#F5F5F8",
|
||||||
|
darkBodyBackground: "#10161f"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
];
|
||||||
|
|
||||||
|
export default aiRoutes;
|
||||||
@@ -85,6 +85,21 @@ export function convertPackageQuantity(quantity: number | string, fromBaseQuanti
|
|||||||
return formatDecimal(numerator / denominator, 3, 3);
|
return formatDecimal(numerator / denominator, 3, 3);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 将基础单位数量换算为业务单位展示数量,结果最多保留三位小数。 */
|
||||||
|
export function convertBaseQuantityToPackageQuantity(baseQuantity: number | string, baseQuantityPerUnit: number | string): string | undefined {
|
||||||
|
const quantityParts = toDecimalParts(baseQuantity, 3);
|
||||||
|
const unitParts = toDecimalParts(baseQuantityPerUnit, 6);
|
||||||
|
if (!quantityParts || !unitParts || unitParts.value === 0n) {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
const numerator = quantityParts.value * 10n ** BigInt(unitParts.scale + 3);
|
||||||
|
const denominator = 10n ** BigInt(quantityParts.scale) * unitParts.value;
|
||||||
|
const quotient = numerator / denominator;
|
||||||
|
const remainder = numerator % denominator;
|
||||||
|
const rounded = denominator < remainder * 2n ? quotient + 1n : quotient;
|
||||||
|
return formatDecimal(rounded, 3, 3);
|
||||||
|
}
|
||||||
|
|
||||||
/** 精确相加两个最多三位小数的数量。 */
|
/** 精确相加两个最多三位小数的数量。 */
|
||||||
export function addPackageQuantity(left: number | string, right: number | string): string | undefined {
|
export function addPackageQuantity(left: number | string, right: number | string): string | undefined {
|
||||||
const leftParts = toQuantityParts(left);
|
const leftParts = toQuantityParts(left);
|
||||||
|
|||||||
Reference in New Issue
Block a user