front/src/views/channel/autoTrigger/components/FormulaAiAssistDrawer.vue
zzh 29d7cbb226 feat: 渠道预报前与销售产品落库前脚本接入 AI 赋值编辑
对齐下单字段白名单,复用中文赋值 DSL 与 AI 写脚本抽屉,方便改写地址/申报/件重尺。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-24 15:10:12 +08:00

648 lines
17 KiB
Vue
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<template>
<a-drawer
:visible="visible"
:width="520"
unmount-on-close
:mask-closable="!loading"
@cancel="close"
@update:visible="onVisibleChange"
>
<template #title>
<div class="drawer-title">
<span>{{ t('channel.autoTrigger.ai.title') }}</span>
<a class="config-link" href="javascript:;" @click="goConfig">
{{ t('channel.autoTrigger.ai.configLink') }}
</a>
</div>
</template>
<div class="ai-assist-body">
<p class="intro">{{ t('channel.autoTrigger.ai.intro') }}</p>
<div class="row-fields">
<div class="field">
<label class="label required">{{ t('channel.autoTrigger.ai.provider') }}</label>
<a-select
v-model="providerKey"
:placeholder="t('channel.autoTrigger.ai.providerPlaceholder')"
:loading="providersLoading"
allow-search
@change="onProviderChange"
>
<a-option
v-for="p in enabledProviders"
:key="p.providerKey"
:value="p.providerKey"
:label="p.displayName || p.providerKey"
/>
</a-select>
</div>
<div class="field">
<label class="label required">{{ t('channel.autoTrigger.ai.model') }}</label>
<a-select
v-model="modelId"
:placeholder="t('channel.autoTrigger.ai.modelPlaceholder')"
allow-create
allow-search
>
<a-option v-for="m in modelOptions" :key="m.modelId" :value="m.modelId">
{{ m.modelId }}{{ m.role ? `(${m.role})` : '' }}
</a-option>
</a-select>
</div>
</div>
<div class="skill-row">
<a-checkbox v-model="sendSkill">
{{ t('channel.autoTrigger.ai.sendSkill') }}
</a-checkbox>
<span class="skill-hint">{{ t('channel.autoTrigger.ai.sendSkillHint') }}</span>
</div>
<div v-if="sendSkill" class="field">
<label class="label">{{ t('channel.autoTrigger.ai.skillSelect') }}</label>
<a-select
v-model="skillKey"
:loading="skillsLoading"
:placeholder="t('channel.autoTrigger.ai.skillSelectPlaceholder')"
allow-search
>
<a-option v-for="s in skills" :key="s.skillKey" :value="s.skillKey" :label="s.name">
{{ s.name }}
</a-option>
</a-select>
</div>
<div class="field">
<label class="label required">{{ t('channel.autoTrigger.ai.prompt') }}</label>
<a-textarea
v-model="prompt"
:placeholder="
t('channel.autoTrigger.ai.promptPlaceholder', { mod: modKeyLabel() })
"
:auto-size="{ minRows: 4, maxRows: 8 }"
:disabled="loading"
@keydown.ctrl.enter.exact.prevent="generate"
@keydown.meta.enter.exact.prevent="generate"
/>
<div class="quick-prompts">
<button
v-for="(q, i) in resolvedQuickPrompts"
:key="i"
type="button"
class="quick-chip"
:disabled="loading"
@click="prompt = q"
>
{{ shortQuick(q) }}
</button>
</div>
</div>
<div class="actions">
<a-button type="primary" :loading="loading" :disabled="!canSend" @click="generate">
{{ loading ? t('channel.autoTrigger.ai.generating') : t('channel.autoTrigger.ai.generate') }}
</a-button>
<a-button :disabled="loading" @click="clearResult">
{{ t('channel.autoTrigger.ai.clear') }}
</a-button>
</div>
<div v-if="errorMsg" class="error-box">{{ errorMsg }}</div>
<div v-if="parsed || rawReply" class="result-block">
<div class="section-label">{{ t('channel.autoTrigger.ai.result') }}</div>
<div v-if="parsed?.expression" class="formula-preview">
<div class="meta-line" v-if="parsed.timingLabel || parsed.operationLabel">
<a-tag v-if="parsed.timingLabel" size="small" color="arcoblue">
{{ parsed.timingLabel }}
</a-tag>
<a-tag v-if="parsed.operationLabel" size="small" color="orangered">
{{ parsed.operationLabel }}
</a-tag>
</div>
<pre class="formula-code">{{ parsed.expression }}</pre>
<p v-if="parsed.explanation" class="explain">{{ parsed.explanation }}</p>
<p v-if="parsed.sampleHint" class="sample">
{{ t('channel.autoTrigger.ai.sampleHint') }}:{{ parsed.sampleHint }}
</p>
</div>
<details v-if="rawReply" class="raw-details">
<summary>{{ t('channel.autoTrigger.ai.rawReply') }}</summary>
<pre class="raw-pre">{{ rawReply }}</pre>
</details>
</div>
</div>
<template #footer>
<div class="footer-actions">
<a-button @click="close">{{ t('common.cancel') }}</a-button>
<a-button
type="primary"
:disabled="!parsed?.expression"
@click="applyFormula"
>
{{ t('channel.autoTrigger.ai.fillFormula') }}
</a-button>
</div>
</template>
</a-drawer>
</template>
<script setup lang="ts">
import { Message } from '@arco-design/web-vue'
import { computed, ref, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { useRouter } from 'vue-router'
import { chatAi, listAiProviders, listAiSkills, type AiSkillItem } from '@/api/ai'
import { modKeyLabel } from '@/utils/device'
import {
resolveProviderModelTags,
type AiProviderItem,
} from '@/views/system/aiAssistant/providerCatalog'
import {
FORMULA_AI_DEFAULT_SKILL_KEY,
FORMULA_AI_QUICK_PROMPTS,
appendFormulaFieldCatalog,
buildFormulaAiSystemPrompt,
parseAiFormulaReply,
type ParsedAiFormula,
} from '../formulaAiSkill'
const DEFAULT_STORAGE_KEY = 'oms.autoTrigger.formulaAi'
const props = defineProps<{
visible: boolean
/** 当前公式,生成时一并作为上下文 */
currentFormula?: string
timingLabel?: string
operationLabel?: string
/** listAiSkills scene,默认 autoTriggerFormula */
skillScene?: string
defaultSkillKey?: string
storageKey?: string
/** chatAi scene 参数 */
chatScene?: string
quickPrompts?: string[]
/** 库内 skill 缺失时的本地 fallback system */
fallbackSystemPrompt?: string
shortSystemPrompt?: string
/** 用户消息末尾输出格式提示 */
outputHint?: string
/** 自定义字段目录拼接(如预报/落库脚本仅下单字段) */
appendCatalog?: (core: string) => string
}>()
const resolvedStorageKey = computed(() => props.storageKey || DEFAULT_STORAGE_KEY)
const resolvedSkillScene = computed(() => props.skillScene || 'autoTriggerFormula')
const resolvedDefaultSkillKey = computed(
() => props.defaultSkillKey || FORMULA_AI_DEFAULT_SKILL_KEY,
)
const resolvedChatScene = computed(() => props.chatScene || 'auto_trigger_formula')
const resolvedQuickPrompts = computed(() =>
props.quickPrompts?.length ? props.quickPrompts : FORMULA_AI_QUICK_PROMPTS,
)
const resolvedOutputHint = computed(
() => props.outputHint || '请按 skill 规定的格式输出(时机/操作/公式/说明)。',
)
const emit = defineEmits<{
'update:visible': [boolean]
apply: [payload: {
expression: string
timingLabel?: string
operationLabel?: string
sampleHint?: string
}]
}>()
const { t } = useI18n()
const router = useRouter()
const providersLoading = ref(false)
const providers = ref<AiProviderItem[]>([])
const providerKey = ref('')
const modelId = ref('')
const sendSkill = ref(true)
const skillKey = ref(resolvedDefaultSkillKey.value)
const skills = ref<AiSkillItem[]>([])
const skillsLoading = ref(false)
const prompt = ref('')
const loading = ref(false)
const errorMsg = ref('')
const rawReply = ref('')
const parsed = ref<ParsedAiFormula | null>(null)
const enabledProviders = computed(() =>
providers.value.filter((p) => p.enabled && Boolean(p.apiKey)),
)
const selectedProvider = computed(
() => enabledProviders.value.find((p) => p.providerKey === providerKey.value) ?? null,
)
const modelOptions = computed(() => {
const p = selectedProvider.value
if (!p) return []
return resolveProviderModelTags(p)
})
const canSend = computed(
() =>
Boolean(providerKey.value && modelId.value && prompt.value.trim()) && !loading.value,
)
function shortQuick(q: string) {
return q.length > 22 ? `${q.slice(0, 22)}…` : q
}
function onVisibleChange(v: boolean) {
emit('update:visible', v)
}
function close() {
emit('update:visible', false)
}
function goConfig() {
router.push({ path: '/system/aiAssistant' })
}
function loadPrefs() {
try {
const raw = localStorage.getItem(resolvedStorageKey.value)
if (!raw) return
const data = JSON.parse(raw) as {
providerKey?: string
modelId?: string
sendSkill?: boolean
skillKey?: string
}
if (data.providerKey) providerKey.value = data.providerKey
if (data.modelId) modelId.value = data.modelId
if (typeof data.sendSkill === 'boolean') sendSkill.value = data.sendSkill
if (data.skillKey?.trim()) skillKey.value = data.skillKey.trim()
else skillKey.value = resolvedDefaultSkillKey.value
} catch {
/* ignore */
}
}
function savePrefs() {
try {
localStorage.setItem(
resolvedStorageKey.value,
JSON.stringify({
providerKey: providerKey.value,
modelId: modelId.value,
sendSkill: sendSkill.value,
skillKey: skillKey.value,
}),
)
} catch {
/* ignore */
}
}
function onProviderChange() {
const opts = modelOptions.value
if (!opts.some((m) => m.modelId === modelId.value)) {
modelId.value = opts[0]?.modelId ?? ''
}
savePrefs()
}
async function loadProviders() {
providersLoading.value = true
try {
const items = await listAiProviders()
providers.value = (items ?? []) as AiProviderItem[]
if (!providerKey.value) {
const def =
enabledProviders.value.find((p) => p.isDefault) ?? enabledProviders.value[0]
if (def) providerKey.value = def.providerKey
}
if (providerKey.value && !enabledProviders.value.some((p) => p.providerKey === providerKey.value)) {
providerKey.value = enabledProviders.value[0]?.providerKey ?? ''
}
onProviderChange()
} catch (e: any) {
Message.error(e?.message || t('channel.autoTrigger.ai.loadProvidersFail'))
} finally {
providersLoading.value = false
}
}
async function loadSkills() {
skillsLoading.value = true
try {
skills.value = await listAiSkills({
scene: resolvedSkillScene.value,
includeContent: true,
enabledOnly: true,
})
if (
!skills.value.some((s) => s.skillKey === skillKey.value) &&
skills.value[0]
) {
skillKey.value = skills.value[0].skillKey
} else if (!skillKey.value) {
skillKey.value = resolvedDefaultSkillKey.value
}
} catch {
skills.value = []
} finally {
skillsLoading.value = false
}
}
function resolveSystemPrompt(): string {
const appendCatalog = props.appendCatalog || appendFormulaFieldCatalog
if (!sendSkill.value) {
return (
props.shortSystemPrompt ||
'你是 OMS 自动触发公式助手。只输出中文公式表达式;字符串用 字段包含(\'…\'),数值用 字段() 比较;非空用 字段有值() 或 字段包含(\'\'),为空用 字段为空()。'
)
}
const fromList = skills.value.find((s) => s.skillKey === skillKey.value)
const content = String(fromList?.content || '').trim()
if (content) return appendCatalog(content)
if (props.fallbackSystemPrompt?.trim()) return props.fallbackSystemPrompt.trim()
return buildFormulaAiSystemPrompt()
}
function clearResult() {
rawReply.value = ''
parsed.value = null
errorMsg.value = ''
}
async function generate() {
if (!canSend.value) {
Message.warning(t('channel.autoTrigger.ai.needProviderModelPrompt'))
return
}
savePrefs()
loading.value = true
errorMsg.value = ''
rawReply.value = ''
parsed.value = null
const ctxParts: string[] = []
if (props.timingLabel) ctxParts.push(`当前时机:${props.timingLabel}`)
if (props.operationLabel) ctxParts.push(`当前操作:${props.operationLabel}`)
if (props.currentFormula?.trim()) {
ctxParts.push(`当前公式(可改写):\n${props.currentFormula.trim()}`)
}
const userContent = [
ctxParts.length ? `【上下文】\n${ctxParts.join('\n')}` : '',
`【需求】\n${prompt.value.trim()}`,
resolvedOutputHint.value,
]
.filter(Boolean)
.join('\n\n')
const messages: { role: string; content: string }[] = [
{ role: 'system', content: resolveSystemPrompt() },
{ role: 'user', content: userContent },
]
try {
const res = await chatAi({
providerKey: providerKey.value,
model: modelId.value,
messages,
scene: resolvedChatScene.value,
})
const content = String(res?.content ?? '').trim()
if (!content) {
errorMsg.value = t('channel.autoTrigger.ai.emptyReply')
return
}
rawReply.value = content
const result = parseAiFormulaReply(content)
parsed.value = result
if (!result.expression) {
errorMsg.value = t('channel.autoTrigger.ai.parseFail')
} else {
Message.success(t('channel.autoTrigger.ai.generateOk'))
}
} catch (e: any) {
errorMsg.value = e?.message || t('channel.autoTrigger.ai.generateFail')
} finally {
loading.value = false
}
}
function applyFormula() {
if (!parsed.value?.expression) return
emit('apply', {
expression: parsed.value.expression,
timingLabel: parsed.value.timingLabel,
operationLabel: parsed.value.operationLabel,
sampleHint: parsed.value.sampleHint,
})
Message.success(t('channel.autoTrigger.ai.filled'))
close()
}
watch(
() => props.visible,
async (v) => {
if (!v) return
loadPrefs()
await Promise.all([loadProviders(), loadSkills()])
},
)
watch(sendSkill, savePrefs)
watch(skillKey, savePrefs)
watch(modelId, savePrefs)
</script>
<style scoped lang="less">
.drawer-title {
display: flex;
align-items: center;
gap: 12px;
width: 100%;
padding-right: 8px;
.config-link {
margin-left: auto;
font-size: 13px;
font-weight: 400;
color: var(--app-primary-color, #2d8c8c);
text-decoration: none;
&:hover {
text-decoration: underline;
}
}
}
.ai-assist-body {
display: flex;
flex-direction: column;
gap: 14px;
}
.intro {
margin: 0;
font-size: 13px;
color: var(--color-text-3);
line-height: 1.5;
}
.row-fields {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 12px;
}
.field {
display: flex;
flex-direction: column;
gap: 6px;
}
.label {
font-size: 13px;
color: var(--color-text-2);
font-weight: 500;
&.required::before {
content: '*';
color: #f53f3f;
margin-right: 4px;
}
}
.skill-row {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 8px;
.skill-hint {
font-size: 12px;
color: var(--color-text-3);
}
}
.quick-prompts {
display: flex;
flex-wrap: wrap;
gap: 8px;
margin-top: 8px;
}
.quick-chip {
height: 28px;
padding: 0 10px;
border: 1px solid var(--color-border-2);
border-radius: 4px;
background: var(--color-fill-2);
color: var(--color-text-2);
font-size: 12px;
cursor: pointer;
&:hover:not(:disabled) {
border-color: var(--app-primary-color, #2d8c8c);
color: var(--app-primary-color, #2d8c8c);
}
&:disabled {
opacity: 0.5;
cursor: not-allowed;
}
}
.actions {
display: flex;
gap: 8px;
}
.error-box {
padding: 8px 12px;
border-radius: 4px;
background: #ffece8;
color: #cb272d;
font-size: 13px;
line-height: 1.5;
}
.result-block {
border-top: 1px solid var(--color-border-2);
padding-top: 12px;
}
.section-label {
font-size: 13px;
font-weight: 500;
color: var(--color-text-2);
margin-bottom: 8px;
}
.formula-preview {
background: var(--color-fill-2);
border: 1px solid var(--color-border-2);
border-radius: 6px;
padding: 12px;
}
.meta-line {
display: flex;
gap: 8px;
margin-bottom: 8px;
}
.formula-code {
margin: 0;
white-space: pre-wrap;
word-break: break-all;
font-family: var(--app-font-mono);
font-size: 13px;
line-height: 1.55;
color: var(--color-text-1);
}
.explain,
.sample {
margin: 8px 0 0;
font-size: 12px;
color: var(--color-text-3);
line-height: 1.5;
}
.raw-details {
margin-top: 10px;
font-size: 12px;
color: var(--color-text-2);
summary {
cursor: pointer;
user-select: none;
}
}
.raw-pre {
margin: 8px 0 0;
max-height: 160px;
overflow: auto;
white-space: pre-wrap;
word-break: break-word;
font-size: 12px;
background: var(--app-card-bg);
border: 1px solid var(--color-border-2);
border-radius: 4px;
padding: 8px;
}
.footer-actions {
display: flex;
justify-content: flex-end;
gap: 8px;
}
</style>