feat: 智能助手增加引用功能

This commit is contained in:
2026-09-19 23:43:57 +08:00
parent 67c661fd46
commit 02e7c4b881
9 changed files with 389 additions and 235 deletions
@@ -275,7 +275,7 @@ public class ShopServiceImpl extends ServiceImpl<ShopMapper, ShopPO> implements
// 有系统文件 id 则覆盖;否则用渠道外链 logo_url(与商品 mainImage 口径一致)
if (shop.getLogoImageId() != null) {
String accessUrl = sysFileService.getFileAccessUrl(shop.getLogoImageId());
String accessUrl = sysFileService.resolveAccessUrl(shop.getLogoImageId());
if (accessUrl != null && !accessUrl.isBlank()) {
shopVO.setLogo(accessUrl);
}
@@ -124,7 +124,7 @@ public class CompanyServiceImpl extends ServiceImpl<CompanyMapper, CompanyPO> im
// logo:有 fileId 时同步冗余 URL
if (createCompanyDTO.getLogoImageId() != null) {
company.setLogoImageId(createCompanyDTO.getLogoImageId());
company.setLogo(sysFileService.getFileAccessUrl(createCompanyDTO.getLogoImageId()));
company.setLogo(sysFileService.resolveAccessUrl(createCompanyDTO.getLogoImageId()));
}
// 设置默认值
@@ -224,7 +224,7 @@ public class CompanyServiceImpl extends ServiceImpl<CompanyMapper, CompanyPO> im
// logo:有 fileId 时同步冗余 URL
if (updateCompanyDTO.getLogoImageId() != null) {
company.setLogoImageId(updateCompanyDTO.getLogoImageId());
company.setLogo(sysFileService.getFileAccessUrl(updateCompanyDTO.getLogoImageId()));
company.setLogo(sysFileService.resolveAccessUrl(updateCompanyDTO.getLogoImageId()));
}
// 设置公司ID(必须在updateById之前设置)
@@ -425,7 +425,7 @@ public class CompanyServiceImpl extends ServiceImpl<CompanyMapper, CompanyPO> im
// 有系统文件 id 则覆盖 logo URL
if (company.getLogoImageId() != null) {
String accessUrl = sysFileService.getFileAccessUrl(company.getLogoImageId());
String accessUrl = sysFileService.resolveAccessUrl(company.getLogoImageId());
if (accessUrl != null && !accessUrl.isBlank()) {
companyVO.setLogo(accessUrl);
}
@@ -62,13 +62,21 @@ public interface SysFileService {
List<SysFileVO> batchCreateOssFiles(BatchCreateOssFileDTO dto);
/**
* 通过文件ID获取文件访问URL
* 通过文件ID获取文件访问URL。会向存储探测文件是否存在,仅用于单独取地址。
*
* @param fileId 文件ID
* @return 文件访问URL
*/
String getFileAccessUrl(Long fileId);
/**
* 按文件记录拼接访问地址,不探测存储。记录缺失或已删除时返回 null。
*
* @param fileId 文件ID
* @return 访问地址,无法拼接时为 null
*/
String resolveAccessUrl(Long fileId);
/**
* 分页获取当前公司的文件列表
*
@@ -497,6 +497,18 @@ public class SysFileServiceImpl extends ServiceImpl<SysFileMapper, SysFilePO> im
return accessUrl;
}
@Override
public String resolveAccessUrl(Long fileId) {
if (fileId == null) {
return null;
}
SysFilePO sysFile = this.getById(fileId);
if (sysFile == null || sysFile.getDeleteTime() != null) {
return null;
}
return SysFileUtils.getFileAccessUrl(sysFile.getStoragePath(), sysFile.getStorageType());
}
/**
* 转换为VO
*/
@@ -238,7 +238,7 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserPO> implements
// 处理头像图片ID
if (updateUserInfoDTO.getAvatarImageId() != null) {
user.setAvatarImageId(updateUserInfoDTO.getAvatarImageId());
user.setAvatar(sysFileService.getFileAccessUrl(updateUserInfoDTO.getAvatarImageId()));
user.setAvatar(sysFileService.resolveAccessUrl(updateUserInfoDTO.getAvatarImageId()));
}
if (StringUtils.hasText(updateUserInfoDTO.getPhone())) {
@@ -1,159 +0,0 @@
<script lang="ts" setup>
import { onBeforeUnmount, ref, watch } from 'vue';
import { Empty, Input, Spin } from 'ant-design-vue';
import { getProductPageApi } from '#/api/ec/product';
import { getProductSkuPageApi } from '#/api/ec/product/sku';
import { getShopPageApi } from '#/api/ec/shop';
import {
catalogCiteLabel,
toProductCite,
toShopCite,
toSkuCite,
type CatalogCite,
type CatalogCiteKind,
} from './catalog-cite';
/** 输入框上方的引用面板:按名称/编码搜店铺、商品、SKU。 */
const props = defineProps<{
/** 由输入框末尾 @ 同步过来的关键字,可空 */
seed: string;
}>();
const emit = defineEmits<{
pick: [item: CatalogCite];
}>();
const kinds: CatalogCiteKind[] = ['shop', 'product', 'sku'];
const kind = ref<CatalogCiteKind>('shop');
const keyword = ref(props.seed);
const loading = ref(false);
const items = ref<CatalogCite[]>([]);
let timer: ReturnType<typeof setTimeout> | undefined;
let seq = 0;
watch(
() => props.seed,
(value) => {
keyword.value = value;
},
);
watch([keyword, kind], () => scheduleSearch());
function scheduleSearch() {
if (timer) clearTimeout(timer);
timer = setTimeout(() => {
void load();
}, 250);
}
async function load() {
const current = ++seq;
loading.value = true;
const q = keyword.value.trim();
try {
const next = await fetchKind(kind.value, q);
if (current === seq) items.value = next;
} catch {
if (current === seq) items.value = [];
} finally {
if (current === seq) loading.value = false;
}
}
async function fetchKind(target: CatalogCiteKind, q: string) {
if (target === 'shop') {
const data = await getShopPageApi({
page: 1,
pageSize: 8,
filters: q ? { name: q } : {},
});
return (data.records || []).map((shop) => toShopCite(shop));
}
if (target === 'product') {
const data = await getProductPageApi({
page: 1,
pageSize: 8,
filters: q ? { keywords: q } : {},
});
return (data.records || []).map((product) => toProductCite(product));
}
const data = await getProductSkuPageApi({
page: 1,
pageSize: 8,
filters: q ? { keywords: q } : {},
});
return (data.records || []).map((sku) => toSkuCite(sku));
}
function onPick(item: CatalogCite) {
emit('pick', item);
}
scheduleSearch();
onBeforeUnmount(() => {
if (timer) clearTimeout(timer);
seq += 1;
});
</script>
<template>
<div class="rounded-lg border border-border bg-card p-2">
<div class="mb-2 flex gap-1">
<button
v-for="item in kinds"
:key="item"
type="button"
class="rounded-md px-2 py-1 text-xs"
:class="
item === kind
? 'bg-primary/10 text-primary'
: 'text-muted-foreground hover:bg-muted'
"
@click="kind = item"
>
{{ catalogCiteLabel(item) }}
</button>
</div>
<Input
v-model:value="keyword"
allow-clear
placeholder="名称或编码"
size="small"
/>
<div class="relative mt-2 max-h-52 overflow-y-auto">
<div
v-if="loading"
class="text-muted-foreground flex items-center justify-center py-6 text-xs"
>
<Spin size="small" />
</div>
<Empty
v-else-if="items.length === 0"
:image="Empty.PRESENTED_IMAGE_SIMPLE"
description="没有匹配"
/>
<template v-else>
<button
v-for="item in items"
:key="item.key"
type="button"
class="hover:bg-muted flex w-full flex-col rounded-md px-2 py-1.5 text-left"
@click="onPick(item)"
>
<span class="truncate text-sm">{{ item.title }}</span>
<span
v-if="item.subtitle"
class="text-muted-foreground truncate text-xs"
>
{{ item.subtitle }}
</span>
</button>
</template>
</div>
</div>
</template>
@@ -0,0 +1,357 @@
<script lang="ts" setup>
import { computed, nextTick, onBeforeUnmount, ref, watch } from 'vue';
import { message } from 'ant-design-vue';
import { ChatSender } from '@tdesign-vue-next/chat';
import { getProductPageApi } from '#/api/ec/product';
import { getProductSkuPageApi } from '#/api/ec/product/sku';
import { getShopPageApi } from '#/api/ec/shop';
import {
catalogCiteLabel,
stripTrailingMention,
toProductCite,
toShopCite,
toSkuCite,
trailingMentionQuery,
type CatalogCite,
type CatalogCiteKind,
} from './catalog-cite';
/** 包一层 ChatSender:@ 先选分类,选中后在输入行内嵌标签。 */
const draft = defineModel<string>({ required: true });
const cites = defineModel<CatalogCite[]>('cites', { required: true });
defineProps<{
loading?: boolean;
}>();
const emit = defineEmits<{
send: [value: string];
stop: [];
}>();
const kinds: CatalogCiteKind[] = ['shop', 'product', 'sku'];
const kind = ref<CatalogCiteKind>('shop');
const rootRef = ref<HTMLElement | null>(null);
const dismissed = ref(false);
const loadingList = ref(false);
const activeKey = ref('');
const items = ref<CatalogCite[]>([]);
let timer: ReturnType<typeof setTimeout> | undefined;
let seq = 0;
const mentionQuery = computed(() => trailingMentionQuery(draft.value));
const menuOpen = computed(
() => mentionQuery.value !== null && !dismissed.value,
);
watch(mentionQuery, (query, prev) => {
if (query !== prev) {
dismissed.value = false;
activeKey.value = '';
if (query !== null) items.value = [];
}
if (query === null) {
items.value = [];
return;
}
scheduleSearch(query);
});
watch(kind, () => {
if (mentionQuery.value === null) return;
activeKey.value = '';
items.value = [];
scheduleSearch(mentionQuery.value);
});
function scheduleSearch(query: string) {
if (timer) clearTimeout(timer);
loadingList.value = true;
timer = setTimeout(() => {
void load(query);
}, 180);
}
async function load(query: string) {
const current = ++seq;
const target = kind.value;
loadingList.value = true;
const q = query.trim();
try {
const next = await fetchKind(target, q);
if (current !== seq || target !== kind.value) return;
items.value = next;
if (!next.some((item) => item.key === activeKey.value)) {
activeKey.value = next[0]?.key || '';
}
void nextTick().then(scrollActiveIntoView);
} finally {
if (current === seq) loadingList.value = false;
}
}
async function fetchKind(target: CatalogCiteKind, q: string) {
if (target === 'shop') {
return safeList(
getShopPageApi({
page: 1,
pageSize: 8,
filters: q ? { name: q } : {},
}).then((data) => (data.records || []).map((shop) => toShopCite(shop))),
);
}
if (target === 'product') {
return safeList(
getProductPageApi({
page: 1,
pageSize: 8,
filters: q ? { keywords: q } : {},
}).then((data) =>
(data.records || []).map((product) => toProductCite(product)),
),
);
}
return safeList(
getProductSkuPageApi({
page: 1,
pageSize: 8,
filters: q ? { keywords: q } : {},
}).then((data) => (data.records || []).map((sku) => toSkuCite(sku))),
);
}
async function safeList(task: Promise<CatalogCite[]>) {
try {
return await task;
} catch {
return [];
}
}
function onKeydown(event: KeyboardEvent) {
if (!menuOpen.value || event.isComposing || event.keyCode === 229) return;
if (event.key === 'ArrowDown') {
event.preventDefault();
event.stopPropagation();
move(1);
} else if (event.key === 'ArrowUp') {
event.preventDefault();
event.stopPropagation();
move(-1);
} else if (event.key === 'Enter' && !event.shiftKey) {
event.preventDefault();
event.stopPropagation();
if (loadingList.value) return;
const hit = items.value.find((item) => item.key === activeKey.value);
if (hit) pick(hit);
} else if (event.key === 'Escape') {
event.preventDefault();
event.stopPropagation();
dismissed.value = true;
}
}
function move(delta: number) {
const list = items.value;
if (list.length === 0) return;
const index = list.findIndex((item) => item.key === activeKey.value);
const next = index < 0 ? 0 : (index + delta + list.length) % list.length;
activeKey.value = list[next]?.key || '';
void nextTick().then(scrollActiveIntoView);
}
function scrollActiveIntoView() {
const key = activeKey.value;
if (!key || !rootRef.value) return;
rootRef.value
.querySelector(`[data-cite-key="${CSS.escape(key)}"]`)
?.scrollIntoView({ block: 'nearest' });
}
function pick(item: CatalogCite) {
if (cites.value.some((cite) => cite.key === item.key)) {
message.info('已经引用过了');
draft.value = stripTrailingMention(draft.value);
focusInput();
return;
}
if (cites.value.length >= 5) {
message.warning('一条消息最多引用 5 个');
return;
}
const next = stripTrailingMention(draft.value);
cites.value = [...cites.value, item];
draft.value = next;
focusInput();
}
function removeCite(key: string) {
cites.value = cites.value.filter((cite) => cite.key !== key);
focusInput();
}
function insertMention() {
if (trailingMentionQuery(draft.value) === null) {
const text = draft.value;
const gap = text && !/\s$/.test(text) ? ' ' : '';
draft.value = `${text}${gap}@`;
}
dismissed.value = false;
focusInput();
}
function focusInput(cursor?: number) {
void nextTick(() => {
const el = rootRef.value?.querySelector('textarea');
if (!el) return;
el.focus();
if (cursor != null) el.setSelectionRange(cursor, cursor);
});
}
function onPointerDown(event: PointerEvent) {
if (!menuOpen.value) return;
const target = event.target;
if (target instanceof Node && rootRef.value?.contains(target)) return;
dismissed.value = true;
}
document.addEventListener('pointerdown', onPointerDown);
onBeforeUnmount(() => {
document.removeEventListener('pointerdown', onPointerDown);
if (timer) clearTimeout(timer);
seq += 1;
});
</script>
<template>
<div ref="rootRef" class="catalog-cite-sender relative" @keydown.capture="onKeydown">
<div
v-if="menuOpen"
class="border-border bg-card absolute bottom-full left-0 z-20 mb-2 w-80 overflow-hidden rounded-lg border shadow-lg"
>
<div class="flex gap-1 p-1.5">
<button
v-for="item in kinds"
:key="item"
type="button"
class="flex-1 rounded-md px-2 py-1.5 text-xs"
:class="
item === kind
? 'bg-primary/10 text-primary font-medium'
: 'text-muted-foreground hover:bg-muted'
"
@mousedown.prevent="kind = item"
>
{{ catalogCiteLabel(item) }}
</button>
</div>
<div class="max-h-72 overflow-y-auto py-1">
<div
v-if="loadingList && items.length === 0"
class="text-muted-foreground px-3 py-6 text-center text-xs"
>
搜索中…
</div>
<div
v-else-if="items.length === 0"
class="text-muted-foreground px-3 py-6 text-center text-xs"
>
这个分类下没有匹配
</div>
<template v-else>
<button
v-for="item in items"
:key="item.key"
type="button"
:data-cite-key="item.key"
class="flex w-full flex-col px-3 py-1.5 text-left"
:class="item.key === activeKey ? 'bg-primary/10' : 'hover:bg-muted'"
@mouseenter="activeKey = item.key"
@mousedown.prevent="pick(item)"
>
<span class="truncate text-sm">{{ item.title }}</span>
<span
v-if="item.subtitle"
class="text-muted-foreground truncate text-xs"
>
{{ item.subtitle }}
</span>
</button>
</template>
</div>
<div class="text-muted-foreground border-border border-t px-3 py-1.5 text-[11px]">
↑↓ 选择 · Enter 引用 · Esc 关闭
</div>
</div>
<ChatSender
v-model="draft"
class="agent-td-sender"
:loading="loading"
placeholder="输入问题,@ 引用店铺、商品或 SKU"
:textarea-props="{ autosize: { minRows: 2, maxRows: 6 } }"
@send="emit('send', $event)"
@stop="emit('stop')"
>
<template #input-prefix>
<div v-if="cites.length" class="cite-inline">
<span
v-for="cite in cites"
:key="cite.key"
class="bg-primary/10 text-primary inline-flex max-w-40 items-center gap-1 rounded-md px-1.5 py-0.5 text-xs"
>
<span class="shrink-0 opacity-70">{{ catalogCiteLabel(cite.kind) }}</span>
<span class="truncate">{{ cite.title }}</span>
<button
type="button"
class="opacity-60 hover:opacity-100"
aria-label="移除引用"
@mousedown.prevent
@click="removeCite(cite.key)"
>
×
</button>
</span>
</div>
</template>
<template #footer-prefix>
<button
type="button"
class="text-muted-foreground hover:text-primary rounded px-1 py-1 text-xs"
@click="insertMention"
>
@ 引用
</button>
</template>
</ChatSender>
</div>
</template>
<style scoped>
.agent-td-sender {
width: 100%;
}
.catalog-cite-sender :deep(.t-chat-sender__textarea__wrapper) {
align-items: flex-start;
}
.catalog-cite-sender :deep(.t-textarea) {
flex: 1;
width: auto;
min-width: 0;
}
.cite-inline {
display: flex;
flex-shrink: 0;
flex-wrap: nowrap;
align-items: center;
gap: 4px;
max-width: 60%;
margin-top: 2px;
margin-right: 8px;
overflow-x: auto;
}
</style>
@@ -26,7 +26,7 @@ export function trailingMentionQuery(text: string): null | string {
return matched ? matched[2] ?? '' : null;
}
/** 选中引用后去掉末尾 @词,避免把触发符发给模型。 */
/** 发送前去掉还没选中的 @查询。 */
export function stripTrailingMention(text: string) {
return text.replace(/(^|\s)@[^\s@]*$/, '$1').replace(/\s+$/, '');
}
@@ -85,7 +85,7 @@ export function toSkuCite(sku: {
};
}
/** 正文 + 引用块。只有引用时也允许发送。 */
/** 正文后面附上引用 id。标签只在输入框里显示,不占一行正文。 */
export function composeMessageWithCites(text: string, cites: CatalogCite[]) {
const body = text.trim();
if (cites.length === 0) return body;
@@ -15,7 +15,7 @@ import {
Spin,
message,
} from 'ant-design-vue';
import { ChatItem, ChatSender } from '@tdesign-vue-next/chat';
import { ChatItem } from '@tdesign-vue-next/chat';
import 'tdesign-vue-next/es/style/index.css';
import '@tdesign-vue-next/chat/es/style/index.css';
@@ -31,12 +31,10 @@ import {
updateAgentLlmSettingsApi,
} from '#/api/agent';
import CatalogCitePicker from './catalog-cite-picker.vue';
import CatalogCiteSender from './catalog-cite-sender.vue';
import {
catalogCiteLabel,
composeMessageWithCites,
stripTrailingMention,
trailingMentionQuery,
type CatalogCite,
} from './catalog-cite';
@@ -72,8 +70,6 @@ const streamingText = ref('');
const draft = ref('');
/** 本条消息附带的店铺/商品/SKU,发送时写成 [引用] 块 */
const citations = ref<CatalogCite[]>([]);
const citeOpen = ref(false);
const mentionSeed = ref('');
const settingsOpen = ref(false);
const savingSettings = ref(false);
const memories = ref<AgentVO.Memory[]>([]);
@@ -138,7 +134,6 @@ function onSessionClick(threadId: string) {
}
composingNew.value = false;
citations.value = [];
citeOpen.value = false;
activeThreadId.value = threadId;
}
@@ -208,7 +203,6 @@ function beginNewChat() {
streamingText.value = '';
draft.value = '';
citations.value = [];
citeOpen.value = false;
}
/** 第一条消息发出时才落库 */
@@ -311,7 +305,6 @@ async function send(textOverride?: string) {
streamingText.value = '';
draft.value = '';
citations.value = [];
citeOpen.value = false;
messages.value.push({
seq: (messages.value.at(-1)?.seq || 0) + 1,
role: 'user',
@@ -363,32 +356,6 @@ function applyStarterPrompt(text: string) {
draft.value = text;
}
function onCitePick(item: CatalogCite) {
if (citations.value.some((cite) => cite.key === item.key)) {
message.info('已经引用过了');
return;
}
if (citations.value.length >= 5) {
message.warning('一条消息最多引用 5 个');
return;
}
citations.value = [...citations.value, item];
draft.value = stripTrailingMention(draft.value);
mentionSeed.value = '';
citeOpen.value = false;
}
function removeCite(key: string) {
citations.value = citations.value.filter((cite) => cite.key !== key);
}
watch(draft, (value) => {
const query = trailingMentionQuery(value);
if (query === null) return;
mentionSeed.value = query;
citeOpen.value = true;
});
function onSenderStop() {
abort?.abort();
sending.value = false;
@@ -532,38 +499,10 @@ void refreshSessions();
/>
</div>
<div class="shrink-0 border-t border-border p-3">
<div class="mb-2 flex flex-wrap items-center gap-1">
<Button size="small" :disabled="sending" @click="citeOpen = !citeOpen">
引用
</Button>
<span
v-for="cite in citations"
:key="cite.key"
class="bg-primary/10 text-primary inline-flex max-w-full items-center gap-1 rounded-full px-2 py-0.5 text-xs"
>
<span class="shrink-0">{{ catalogCiteLabel(cite.kind) }}</span>
<span class="truncate">{{ cite.title }}</span>
<button
type="button"
class="text-primary/70 hover:text-primary"
@click="removeCite(cite.key)"
>
×
</button>
</span>
</div>
<CatalogCitePicker
v-if="citeOpen"
class="mb-2"
:seed="mentionSeed"
@pick="onCitePick"
/>
<ChatSender
<CatalogCiteSender
v-model="draft"
class="agent-td-sender"
v-model:cites="citations"
:loading="sending"
placeholder="输入问题,@ 引用店铺/商品/SKU,Enter 发送"
:textarea-props="{ autosize: { minRows: 2, maxRows: 6 } }"
@send="onSenderSend"
@stop="onSenderStop"
/>
@@ -651,7 +590,4 @@ void refreshSessions();
.agent-td-item :deep(.t-chat__inner.user) {
justify-content: flex-end;
}
.agent-td-sender {
width: 100%;
}
</style>