feat: 把估价智能体和部署配置提交到主分支

门户估价对话、会员与智能体账号,以及生产 Docker 部署一直停在工作区,远端主分支还没有这些改动。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
wuzilongandCursor committed 2026-11-23 09:42:44 +08:00
1 parent 6519682885
commit 9c7c80e194
78 files changed
+16614 -345

No files matched your search

+13
View File
@@ -42,6 +42,19 @@ coverage/
*.pid
target/
# 部署离线包、生成配置和证书。示例文件可以提交。
/deploy/dist/
/deploy/.env
/deploy/IMAGE_TAG
/deploy/nginx/active.conf
/deploy/certs/*
!/deploy/certs/.gitkeep
/deploy/certbot/*
!/deploy/certbot/.gitkeep
/deploy/data/
/deploy/secrets/
/deploy/backup.log
# personal-dev:begin
/.local/agent/
# personal-dev:end
+5
View File
@@ -0,0 +1,5 @@
node_modules
.git
.env
.env.*
*.log
+4
View File
@@ -0,0 +1,4 @@
FROM nginx:1.27-alpine
RUN rm -f /etc/nginx/conf.d/default.conf
COPY dist /usr/share/nginx/html/admin
+7777
View File
File diff suppressed because it is too large. Load diff
+47
View File
@@ -18,6 +18,13 @@ import type {
LoginSecurity,
PageResult,
SensitiveWord,
SiteMember,
SiteMemberQuery,
SiteMemberUpdate,
AgentUser,
AgentUserCreate,
AgentUserQuery,
AgentUserUpdate,
SiteSettings
} from '@/types/admin'
@@ -225,6 +232,46 @@ export function fetchGetSensitiveWords(params?: {
})
}
export function fetchGetSiteMembers(params: SiteMemberQuery) {
return request
.get<unknown>({ url: '/api/admin/site-members', params: cleanQuery(params) })
.then((data) => asPage<SiteMember>(data))
}
export function fetchGetSiteMember(id: number | string) {
return request.get<SiteMember>({ url: `/api/admin/site-members/${id}` })
}
export function fetchUpdateSiteMember(id: number | string, data: SiteMemberUpdate) {
return request.put<SiteMember>({ url: `/api/admin/site-members/${id}`, data })
}
export function fetchDeleteSiteMember(id: number | string) {
return request.del({ url: `/api/admin/site-members/${id}` })
}
export function fetchGetAgentUsers(params: AgentUserQuery) {
return request
.get<unknown>({ url: '/api/admin/agent-users', params: cleanQuery(params) })
.then((data) => asPage<AgentUser>(data))
}
export function fetchGetAgentUser(id: string) {
return request.get<AgentUser>({ url: `/api/admin/agent-users/${id}` })
}
export function fetchCreateAgentUser(data: AgentUserCreate) {
return request.post<AgentUser>({ url: '/api/admin/agent-users', data })
}
export function fetchUpdateAgentUser(id: string, data: AgentUserUpdate) {
return request.put<AgentUser>({ url: `/api/admin/agent-users/${id}`, data })
}
export function fetchDeleteAgentUser(id: string) {
return request.del({ url: `/api/admin/agent-users/${id}` })
}
export function fetchCreateSensitiveWord(word: string) {
return request.post<SensitiveWord>({ url: '/api/admin/sensitive-words', data: { word } })
}
+4
View File
@@ -24,6 +24,7 @@ const PAGE_AUTH_PREFIX: Record<string, string> = {
'/system/file': 'file:',
'/system/site': 'site:',
'/system/sensitive-word': 'word:',
'/system/site-member': 'site-member:',
'/home/template': 'home:',
'/home/slides': 'home:',
'/home/articles': 'home:',
@@ -73,6 +74,9 @@ const AUTH_TITLE: Record<string, string> = {
'word:add': '新增',
'word:delete': '删除',
'word:preview': '预览',
'site-member:view': '查看',
'site-member:edit': '编辑',
'site-member:delete': '删除',
'home:edit': '保存',
'about:edit': '保存',
'party:edit': '保存',
+56
View File
@@ -183,6 +183,62 @@ export interface SiteSettings {
expert_reply_workdays?: number | null
}
export interface SiteMember {
id: number | string
email: string
status: AdminStatus
builtin?: boolean
agentEnabled?: boolean
displayName?: string | null
privacyAcceptedAt?: string | null
createdAt?: string | null
updatedAt?: string | null
}
export interface SiteMemberQuery {
current?: number
size?: number
email?: string
}
export interface SiteMemberUpdate {
email: string
status: AdminStatus
password?: string
agentEnabled?: boolean
displayName?: string
}
export interface AgentUser {
id: string
builtin: boolean
username: string
displayName?: string | null
mobileMask?: string
status: AdminStatus | string
createdAt?: string | null
updatedAt?: string | null
}
export interface AgentUserQuery {
current?: number
size?: number
username?: string
}
export interface AgentUserCreate {
username: string
displayName: string
status: AdminStatus
password: string
}
export interface AgentUserUpdate {
displayName: string
status: AdminStatus
password?: string
}
export interface SensitiveWord {
id: number
word: string
+319
View File
@@ -0,0 +1,319 @@
<!-- 智能体市场 -->
<template>
<div class="market">
<header class="market-head">
<div>
<h2>智能体市场</h2>
<p>已登录管理端时,直接使用当前用户管理中的账号。门户注册用户仍需勾选允许登录智能体。</p>
</div>
<div v-if="account" class="market-user">
<span>{{ account }}</span>
</div>
</header>
<div class="grid">
<button
v-for="item in agents"
:key="item.key"
type="button"
class="card"
@click="openAgent(item)"
>
<span class="mark" :style="{ color: item.color, backgroundColor: item.color + '18' }">
<ArtSvgIcon :icon="item.icon" class="mark-icon" />
</span>
<span class="copy">
<strong>{{ item.title }}</strong>
<span>{{ item.summary }}</span>
<em>甘肃省房地产价格评估行业协会</em>
</span>
</button>
</div>
<ElDialog v-model="loginVisible" title="登录智能体" width="420px" align-center>
<p class="login-hint">请使用门户网站注册的邮箱,或用户管理中的 admin 账号。账号需勾选「允许登录智能体」。</p>
<ElForm label-width="72px" @submit.prevent>
<ElFormItem label="账号">
<ElInput v-model="username" placeholder="邮箱或 admin" autocomplete="username" />
</ElFormItem>
<ElFormItem label="密码">
<ElInput v-model="password" type="password" show-password autocomplete="current-password" />
</ElFormItem>
</ElForm>
<p v-if="error" class="login-error">{{ error }}</p>
<template #footer>
<ElButton @click="loginVisible = false">取消</ElButton>
<ElButton type="primary" :loading="busy" @click="submitLogin">登录</ElButton>
</template>
</ElDialog>
</div>
</template>
<script setup lang="ts">
import { ElButton, ElMessageBox } from 'element-plus'
import request from '@/utils/http'
defineOptions({ name: 'AiAgentMarket' })
type AgentCard = {
key: string
title: string
summary: string
icon: string
color: string
ready: boolean
}
const TOKEN_KEY = 'gsfdc_admin_agent_token'
const PORTAL_PORT = '13000'
const agents: AgentCard[] = [
{ key: 'valuation', title: '估价智能体', summary: '对照协会知识,回答估价业务问题。', icon: 'ri:calculator-line', color: '#1677ff', ready: true },
{ key: 'policy', title: '政策法规问答', summary: '查询房地产估价相关政策法规要点。', icon: 'ri:scales-3-line', color: '#0f766e', ready: false },
{ key: 'verify', title: '估价报告核验助手', summary: '说明报告备案查询和核验入口。', icon: 'ri:file-search-line', color: '#b45309', ready: false },
{ key: 'edu', title: '继续教育学习顾问', summary: '介绍继续教育学时、计划和报名去向。', icon: 'ri:graduation-cap-line', color: '#7c3aed', ready: false },
{ key: 'members', title: '会员机构查询', summary: '帮助查找协会会员机构名录。', icon: 'ri:building-line', color: '#0369a1', ready: false },
{ key: 'complaint', title: '投诉举报指引', summary: '说明投诉受理范围和需准备的材料。', icon: 'ri:feedback-line', color: '#be123c', ready: false },
{ key: 'integrity', title: '诚信档案查询', summary: '介绍诚信公示和档案查询方式。', icon: 'ri:shield-check-line', color: '#047857', ready: false },
{ key: 'standard', title: '估价准则解读', summary: '用通俗语言说明常用估价准则。', icon: 'ri:book-open-line', color: '#1d4ed8', ready: false },
{ key: 'house', title: '住宅估价要点', summary: '整理住宅估价常见比较和注意事项。', icon: 'ri:home-4-line', color: '#c2410c', ready: false },
{ key: 'land', title: '土地估价要点', summary: '整理土地估价的用途、年限和修正思路。', icon: 'ri:landscape-line', color: '#a16207', ready: false },
{ key: 'case', title: '资产评估案例', summary: '按用途浏览协会发布的估价案例。', icon: 'ri:folder-chart-line', color: '#4338ca', ready: false },
{ key: 'fee', title: '收费标准说明', summary: '说明协会公布的收费参考口径。', icon: 'ri:money-cny-circle-line', color: '#0e7490', ready: false },
{ key: 'expert', title: '专家答疑分拣', summary: '把会员问题分到对应的专家服务。', icon: 'ri:user-star-line', color: '#9f1239', ready: false },
{ key: 'brief', title: '行业数据简报', summary: '汇总协会已发布的行业数据说明。', icon: 'ri:bar-chart-box-line', color: '#166534', ready: false },
{ key: 'annual', title: '资质年检提醒', summary: '提示会员机构年检需要核对的事项。', icon: 'ri:calendar-check-line', color: '#92400e', ready: false },
{ key: 'branch', title: '分支机构联络', summary: '查找协会分支机构的公开联系方式。', icon: 'ri:map-pin-line', color: '#155e75', ready: false },
{ key: 'train', title: '培训报名助手', summary: '介绍培训通知和报名应查看的栏目。', icon: 'ri:presentation-line', color: '#6d28d9', ready: false },
{ key: 'filing', title: '报告备案咨询', summary: '说明报告备案要提交的信息和进度查询。', icon: 'ri:file-list-2-line', color: '#1e40af', ready: false },
{ key: 'risk', title: '风险提示助手', summary: '转述协会已发布的行业风险提示。', icon: 'ri:alarm-warning-line', color: '#b91c1c', ready: false },
{ key: 'glossary', title: '估价术语词典', summary: '解释常见房地产估价术语。', icon: 'ri:book-2-line', color: '#334155', ready: false },
{ key: 'notice', title: '协会通知摘要', summary: '概括最新协会通知的要点。', icon: 'ri:notification-3-line', color: '#0f766e', ready: false }
]
const loginVisible = ref(false)
const username = ref('')
const password = ref('')
const error = ref('')
const busy = ref(false)
const account = ref('')
const pending = ref<AgentCard | null>(null)
function readToken() {
return window.localStorage.getItem(TOKEN_KEY) || ''
}
function writeToken(token: string) {
if (token) window.localStorage.setItem(TOKEN_KEY, token)
else window.localStorage.removeItem(TOKEN_KEY)
}
async function refreshAccount() {
const token = readToken()
if (!token) {
account.value = ''
return
}
const response = await fetch('/api/site/auth/agent/me', {
headers: { Authorization: `Bearer ${token}` }
})
if (!response.ok) {
writeToken('')
account.value = ''
return
}
const body = await response.json()
account.value = body.displayName || body.username || ''
}
function openLogin(item?: AgentCard) {
pending.value = item || null
error.value = ''
password.value = ''
loginVisible.value = true
}
function portalAssistant(token: string) {
const origin = `${window.location.protocol}//${window.location.hostname}:${PORTAL_PORT}`
const url = `${origin}/expert/assistant#agentToken=${encodeURIComponent(token)}`
window.open(url, '_blank', 'noopener')
}
async function adoptStaffSession() {
try {
const body = await request.post<{ accessToken?: string; displayName?: string; username?: string }>({
url: '/api/admin/auth/agent-session',
showErrorMessage: false
})
if (!body?.accessToken) return false
writeToken(body.accessToken)
account.value = body.displayName || body.username || ''
return true
} catch {
return false
}
}
async function openAgent(item: AgentCard) {
if (!readToken()) {
const adopted = await adoptStaffSession()
if (!adopted) {
openLogin(item)
return
}
}
if (!item.ready) {
await ElMessageBox.alert('建设中', item.title, { confirmButtonText: '知道了' })
return
}
portalAssistant(readToken())
}
async function submitLogin() {
error.value = ''
busy.value = true
try {
const response = await fetch('/api/site/auth/agent-login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username: username.value.trim(), password: password.value })
})
const body = await response.json().catch(() => ({}))
if (!response.ok) {
const detail = body?.detail
error.value = typeof detail === 'string' ? detail : '登录失败'
return
}
writeToken(body.accessToken || '')
await refreshAccount()
loginVisible.value = false
const next = pending.value
pending.value = null
if (next) await openAgent(next)
} catch {
error.value = '登录失败'
} finally {
busy.value = false
}
}
onMounted(async () => {
const adopted = await adoptStaffSession()
if (!adopted) await refreshAccount()
})
</script>
<style scoped>
.market {
display: flex;
flex-direction: column;
gap: 16px;
}
.market-head {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 16px;
}
.market-head h2 {
margin: 0 0 6px;
font-size: 20px;
font-weight: 650;
}
.market-head p,
.login-hint {
margin: 0;
color: #64748b;
font-size: 13px;
line-height: 1.6;
}
.market-user {
display: flex;
align-items: center;
gap: 8px;
white-space: nowrap;
}
.grid {
display: grid;
grid-template-columns: repeat(4, minmax(0, 1fr));
gap: 12px;
}
.card {
display: flex;
align-items: flex-start;
gap: 12px;
min-height: 118px;
padding: 16px;
text-align: left;
background: #fff;
border: 1px solid #e8eef8;
border-radius: 12px;
cursor: pointer;
}
.card:hover {
border-color: #bfd4ff;
}
.mark {
display: grid;
flex: none;
place-items: center;
width: 52px;
height: 52px;
border-radius: 14px;
}
.mark-icon {
width: 28px;
height: 28px;
}
.copy {
display: flex;
flex: 1;
flex-direction: column;
gap: 6px;
min-width: 0;
}
.copy strong {
font-size: 15px;
}
.copy span,
.copy em {
color: #64748b;
font-size: 12px;
font-style: normal;
line-height: 1.5;
}
.login-hint {
margin-bottom: 14px;
}
.login-error {
margin: 0;
color: #b91c1c;
font-size: 13px;
}
@media (max-width: 1200px) {
.grid {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
}
@media (max-width: 720px) {
.grid {
grid-template-columns: 1fr;
}
}
</style>
+330
View File
@@ -0,0 +1,330 @@
<!-- 智能体用户:可登录估价智能体的账号。admin 与用户管理中的 admin 是同一条记录。 -->
<template>
<div class="flex flex-col gap-3">
<ElCard>
<template #header>
<div class="flex items-center justify-between gap-3">
<span>智能体用户</span>
<ElButton v-if="hasAuth('agent-user:add')" type="primary" @click="openCreate">新增用户</ElButton>
</div>
</template>
<ListKeywordSearch v-model="keyword" placeholder="检索用户名或姓名" @search="searchUsers" />
<ArtTable
:loading="loading"
:data="data"
:columns="columns"
:pagination="pagination"
@pagination:size-change="handleSizeChange"
@pagination:current-change="handleCurrentChange"
/>
</ElCard>
<ElDialog v-model="viewVisible" title="智能体用户" width="560px" align-center>
<ElDescriptions v-if="current" :column="1" border>
<ElDescriptionsItem label="头像">
<img v-if="current.builtin" class="agent-avatar" :src="consoleAvatar" alt="头像" />
<span v-else class="agent-letter">{{ letter(current) }}</span>
</ElDescriptionsItem>
<ElDescriptionsItem label="用户名">{{ current.username }}</ElDescriptionsItem>
<ElDescriptionsItem label="姓名">{{ current.displayName || '—' }}</ElDescriptionsItem>
<ElDescriptionsItem label="手机号">{{ current.mobileMask || '—' }}</ElDescriptionsItem>
<ElDescriptionsItem label="状态">{{ statusText(current.status) }}</ElDescriptionsItem>
<ElDescriptionsItem label="来源">
{{ current.builtin ? '与用户管理中的 admin 为同一账号' : '智能体用户' }}
</ElDescriptionsItem>
<ElDescriptionsItem label="创建时间">{{ formatDateTime(current.createdAt) || '—' }}</ElDescriptionsItem>
<ElDescriptionsItem label="更新时间">{{ formatDateTime(current.updatedAt) || '—' }}</ElDescriptionsItem>
</ElDescriptions>
</ElDialog>
<ElDialog v-model="editVisible" :title="form.mode === 'add' ? '新增智能体用户' : '编辑智能体用户'" width="480px" align-center>
<p v-if="form.builtin" class="form-hint">
该账号与用户管理中的 admin 共用用户名、密码、姓名、手机号和状态。在这里修改后,用户管理中的同一账号会一起变化。
</p>
<ElForm ref="formRef" :model="form" :rules="rules" label-width="88px">
<ElFormItem label="用户名" prop="username">
<ElInput v-model="form.username" placeholder="请输入用户名" :disabled="form.mode === 'edit'" />
</ElFormItem>
<ElFormItem label="姓名" prop="displayName">
<ElInput v-model="form.displayName" placeholder="请输入姓名" />
</ElFormItem>
<ElFormItem label="状态" prop="status">
<ElSelect v-model="form.status" placeholder="请选择状态">
<ElOption v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
</ElSelect>
</ElFormItem>
<ElFormItem :label="form.mode === 'add' ? '密码' : '新密码'" prop="password">
<ElInput
v-model="form.password"
type="password"
show-password
:placeholder="form.mode === 'add' ? '请输入密码' : '留空则不修改'"
/>
</ElFormItem>
</ElForm>
<template #footer>
<ElButton @click="editVisible = false">取消</ElButton>
<ElButton type="primary" :loading="saving" @click="save">保存</ElButton>
</template>
</ElDialog>
</div>
</template>
<script setup lang="ts">
import type { FormInstance, FormRules } from 'element-plus'
import { ElButton, ElMessage, ElMessageBox, ElTag } from 'element-plus'
import consoleAvatar from '@imgs/user/avatar.webp'
import { useTable } from '@/hooks/core/useTable'
import { useAuth } from '@/hooks/core/useAuth'
import {
fetchCreateAgentUser,
fetchDeleteAgentUser,
fetchGetAgentUser,
fetchGetAgentUsers,
fetchUpdateAgentUser
} from '@/api/system-manage'
import type { AdminStatus, AgentUser } from '@/types/admin'
import { formatDateTime, isStrongPassword, PASSWORD_MESSAGE } from '@/utils/admin'
import ListKeywordSearch from '@/components/ListKeywordSearch.vue'
defineOptions({ name: 'AgentUser' })
const statusOptions: { value: AdminStatus; label: string }[] = [
{ value: 'active', label: '正常' },
{ value: 'disabled', label: '停用' },
{ value: 'cancelled', label: '已注销' }
]
const statusConfig: Record<string, { type: 'success' | 'warning' | 'info'; text: string }> = {
active: { type: 'success', text: '正常' },
disabled: { type: 'warning', text: '停用' },
cancelled: { type: 'info', text: '已注销' }
}
const statusText = (status?: string) => statusConfig[status || '']?.text || status || '—'
const letter = (row: AgentUser) => (row.displayName || row.username || '?').slice(0, 1)
const { hasAuth } = useAuth()
const keyword = ref('')
const viewVisible = ref(false)
const editVisible = ref(false)
const saving = ref(false)
const current = ref<AgentUser | null>(null)
const formRef = ref<FormInstance>()
const form = reactive({
mode: 'add' as 'add' | 'edit',
id: '',
builtin: false,
username: '',
displayName: '',
status: 'active' as AdminStatus,
password: ''
})
const rules: FormRules = {
username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
displayName: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
status: [{ required: true, message: '请选择状态', trigger: 'change' }],
password: [
{
validator: (_rule, value: string, callback) => {
if (!value) {
if (form.mode === 'add') {
callback(new Error('请输入密码'))
return
}
callback()
return
}
if (!isStrongPassword(value)) {
callback(new Error(PASSWORD_MESSAGE))
return
}
callback()
},
trigger: 'blur'
}
]
}
const {
columns,
data,
loading,
pagination,
getData,
replaceSearchParams,
handleSizeChange,
handleCurrentChange,
refreshData
} = useTable({
core: {
apiFn: fetchGetAgentUsers,
apiParams: { current: 1, size: 20 },
columnsFactory: () => [
{ type: 'index', width: 60, label: '序号' },
{
prop: 'avatar',
label: '头像',
width: 80,
formatter: (row: AgentUser) => {
if (row.builtin) {
return h('img', { src: consoleAvatar, alt: '头像', class: 'agent-avatar' })
}
return h('span', { class: 'agent-letter' }, letter(row))
}
},
{ prop: 'username', label: '用户名', minWidth: 140 },
{ prop: 'displayName', label: '姓名', minWidth: 140 },
{ prop: 'mobileMask', label: '手机号', minWidth: 140 },
{
prop: 'status',
label: '状态',
width: 100,
formatter: (row: AgentUser) => {
const config = statusConfig[row.status] || { type: 'info' as const, text: row.status }
return h(ElTag, { type: config.type }, () => config.text)
}
},
{
prop: 'createdAt',
label: '创建时间',
minWidth: 170,
formatter: (row: AgentUser) => formatDateTime(row.createdAt)
},
{
prop: 'operation',
label: '操作',
width: 200,
fixed: 'right',
formatter: (row: AgentUser) => {
const buttons = []
if (hasAuth('agent-user:view')) {
buttons.push(h(ElButton, { link: true, type: 'primary', onClick: () => openView(row) }, () => '查看'))
}
if (hasAuth('agent-user:edit')) {
buttons.push(h(ElButton, { link: true, type: 'primary', onClick: () => openEdit(row) }, () => '编辑'))
}
if (hasAuth('agent-user:delete') && !row.builtin) {
buttons.push(h(ElButton, { link: true, type: 'danger', onClick: () => remove(row) }, () => '删除'))
}
return h('div', { class: 'flex items-center gap-1' }, buttons)
}
}
]
}
})
const searchUsers = (value: string) => {
keyword.value = value
replaceSearchParams({ username: value.trim() || undefined })
getData()
}
const openView = async (row: AgentUser) => {
current.value = await fetchGetAgentUser(row.id)
viewVisible.value = true
}
const openCreate = () => {
form.mode = 'add'
form.id = ''
form.builtin = false
form.username = ''
form.displayName = ''
form.status = 'active'
form.password = ''
editVisible.value = true
nextTick(() => formRef.value?.clearValidate())
}
const openEdit = (row: AgentUser) => {
form.mode = 'edit'
form.id = row.id
form.builtin = row.builtin
form.username = row.username
form.displayName = row.displayName || ''
form.status = (row.status as AdminStatus) || 'active'
form.password = ''
editVisible.value = true
nextTick(() => formRef.value?.clearValidate())
}
const save = async () => {
if (!formRef.value) return
try {
await formRef.value.validate()
} catch {
return
}
saving.value = true
try {
if (form.mode === 'add') {
await fetchCreateAgentUser({
username: form.username.trim(),
displayName: form.displayName.trim(),
status: form.status,
password: form.password
})
} else {
await fetchUpdateAgentUser(form.id, {
displayName: form.displayName.trim(),
status: form.status,
password: form.password.trim() || undefined
})
}
ElMessage.success('已保存')
editVisible.value = false
refreshData()
} catch {
// 失败文案由接口层展示
} finally {
saving.value = false
}
}
const remove = async (row: AgentUser) => {
try {
await ElMessageBox.confirm(`确定删除「${row.username}」吗?删除后该用户不能再登录估价智能体。`, '删除', {
type: 'warning'
})
} catch {
return
}
try {
await fetchDeleteAgentUser(row.id)
ElMessage.success('已删除')
refreshData()
} catch {
// 失败文案由接口层展示
}
}
</script>
<style scoped>
.form-hint {
margin: 0 0 16px;
color: var(--el-text-color-secondary);
font-size: 13px;
line-height: 1.5;
}
:deep(.agent-avatar) {
width: 32px;
height: 32px;
border-radius: 50%;
object-fit: cover;
}
:deep(.agent-letter) {
display: inline-flex;
align-items: center;
justify-content: center;
width: 32px;
height: 32px;
border-radius: 50%;
background: var(--el-color-primary-light-8);
color: var(--el-color-primary);
font-size: 14px;
}
</style>
@@ -0,0 +1,307 @@
<!-- 门户网站注册用户 -->
<template>
<div class="flex flex-col gap-3">
<ElCard>
<template #header>
<span>门户网站注册用户</span>
</template>
<ListKeywordSearch v-model="keyword" placeholder="检索邮箱或账号" @search="searchMembers" />
<ArtTable
:loading="loading"
:data="data"
:columns="columns"
:pagination="pagination"
@pagination:size-change="handleSizeChange"
@pagination:current-change="handleCurrentChange"
/>
</ElCard>
<ElDialog v-model="viewVisible" title="注册用户" width="560px" align-center>
<ElDescriptions v-if="current" :column="1" border>
<ElDescriptionsItem :label="current.builtin ? '账号' : '邮箱'">{{ current.email }}</ElDescriptionsItem>
<ElDescriptionsItem v-if="current.builtin" label="姓名">{{ current.displayName || '—' }}</ElDescriptionsItem>
<ElDescriptionsItem label="登录智能体">{{ current.agentEnabled ? '允许' : '不允许' }}</ElDescriptionsItem>
<ElDescriptionsItem v-if="current.builtin" label="来源">与用户管理中的 admin 为同一账号</ElDescriptionsItem>
<ElDescriptionsItem label="状态">{{ statusText(current.status) }}</ElDescriptionsItem>
<ElDescriptionsItem label="同意隐私政策">{{ formatDateTime(current.privacyAcceptedAt) || '—' }}</ElDescriptionsItem>
<ElDescriptionsItem label="注册时间">{{ formatDateTime(current.createdAt) || '—' }}</ElDescriptionsItem>
<ElDescriptionsItem label="更新时间">{{ formatDateTime(current.updatedAt) || '—' }}</ElDescriptionsItem>
</ElDescriptions>
</ElDialog>
<ElDialog v-model="editVisible" title="编辑注册用户" width="480px" align-center>
<ElForm ref="formRef" :model="form" :rules="rules" label-width="88px">
<ElFormItem :label="form.builtin ? '账号' : '邮箱'" prop="email">
<ElInput v-model="form.email" :disabled="form.builtin" :placeholder="form.builtin ? '账号' : 'name@example.com'" />
</ElFormItem>
<ElFormItem v-if="form.builtin" label="姓名" prop="displayName">
<ElInput v-model="form.displayName" placeholder="姓名" />
</ElFormItem>
<ElFormItem label="状态" prop="status">
<ElSelect v-model="form.status" placeholder="请选择状态">
<ElOption v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
</ElSelect>
</ElFormItem>
<ElFormItem label="登录智能体">
<ElCheckbox v-model="form.agentEnabled">允许登录智能体</ElCheckbox>
</ElFormItem>
<ElFormItem label="新密码" prop="password">
<ElInput v-model="form.password" type="password" show-password placeholder="留空则不修改" />
</ElFormItem>
<p v-if="form.builtin" class="px-2 text-xs text-gray-500">与用户管理中的 admin 为同一账号。姓名、密码和状态会同步过去。</p>
</ElForm>
<template #footer>
<ElButton @click="editVisible = false">取消</ElButton>
<ElButton type="primary" :loading="saving" @click="save">保存</ElButton>
</template>
</ElDialog>
</div>
</template>
<script setup lang="ts">
import type { FormInstance, FormRules } from 'element-plus'
import { ElButton, ElMessage, ElMessageBox, ElTag } from 'element-plus'
import { useTable } from '@/hooks/core/useTable'
import { useAuth } from '@/hooks/core/useAuth'
import {
fetchDeleteSiteMember,
fetchGetSiteMember,
fetchGetSiteMembers,
fetchUpdateSiteMember
} from '@/api/system-manage'
import type { AdminStatus, SiteMember } from '@/types/admin'
import { formatDateTime, isStrongPassword, PASSWORD_MESSAGE } from '@/utils/admin'
import ListKeywordSearch from '@/components/ListKeywordSearch.vue'
defineOptions({ name: 'SiteMember' })
const statusOptions: { value: AdminStatus; label: string }[] = [
{ value: 'active', label: '正常' },
{ value: 'disabled', label: '停用' },
{ value: 'cancelled', label: '已注销' }
]
const statusConfig: Record<string, { type: 'success' | 'warning' | 'info'; text: string }> = {
active: { type: 'success', text: '正常' },
disabled: { type: 'warning', text: '停用' },
cancelled: { type: 'info', text: '已注销' }
}
const statusText = (status?: string) => statusConfig[status || '']?.text || status || '—'
const { hasAuth } = useAuth()
const keyword = ref('')
const viewVisible = ref(false)
const editVisible = ref(false)
const saving = ref(false)
const current = ref<SiteMember | null>(null)
const formRef = ref<FormInstance>()
const form = reactive({
id: '' as string | number,
email: '',
displayName: '',
builtin: false,
agentEnabled: false,
status: 'active' as AdminStatus,
password: ''
})
const rules: FormRules = {
email: [
{
validator: (_rule, value: string, callback) => {
const text = (value || '').trim()
if (form.builtin) {
if (!text) callback(new Error('请输入账号'))
else callback()
return
}
if (!text) {
callback(new Error('请输入邮箱'))
return
}
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(text)) {
callback(new Error('邮箱格式不正确'))
return
}
callback()
},
trigger: 'blur'
}
],
displayName: [
{
validator: (_rule, value: string, callback) => {
if (form.builtin && !(value || '').trim()) {
callback(new Error('请填写姓名'))
return
}
callback()
},
trigger: 'blur'
}
],
status: [{ required: true, message: '请选择状态', trigger: 'change' }],
password: [
{
validator: (_rule, value: string, callback) => {
if (!value) {
callback()
return
}
if (!isStrongPassword(value)) {
callback(new Error(PASSWORD_MESSAGE))
return
}
callback()
},
trigger: 'blur'
}
]
}
const {
columns,
data,
loading,
pagination,
getData,
replaceSearchParams,
handleSizeChange,
handleCurrentChange,
refreshData
} = useTable({
core: {
apiFn: fetchGetSiteMembers,
apiParams: { current: 1, size: 20 },
columnsFactory: () => [
{ type: 'index', width: 60, label: '序号' },
{ prop: 'email', label: '邮箱 / 账号', minWidth: 220 },
{
prop: 'agentEnabled',
label: '登录智能体',
width: 120,
formatter: (row: SiteMember) => (row.agentEnabled ? '允许' : '不允许')
},
{
prop: 'status',
label: '状态',
width: 100,
formatter: (row: SiteMember) => {
const config = statusConfig[row.status] || { type: 'info' as const, text: row.status }
return h(ElTag, { type: config.type }, () => config.text)
}
},
{
prop: 'privacyAcceptedAt',
label: '同意隐私政策',
minWidth: 180,
formatter: (row: SiteMember) => formatDateTime(row.privacyAcceptedAt) || '—'
},
{
prop: 'createdAt',
label: '注册时间',
minWidth: 180,
formatter: (row: SiteMember) => formatDateTime(row.createdAt) || '—'
},
{
prop: 'updatedAt',
label: '更新时间',
minWidth: 180,
formatter: (row: SiteMember) => formatDateTime(row.updatedAt) || '—'
},
{
prop: 'operation',
label: '操作',
width: 180,
fixed: 'right',
formatter: (row: SiteMember) => {
const buttons = []
if (hasAuth('site-member:view')) {
buttons.push(
h(ElButton, { link: true, type: 'primary', onClick: () => openView(row) }, () => '查看')
)
}
if (hasAuth('site-member:edit')) {
buttons.push(
h(ElButton, { link: true, type: 'primary', onClick: () => openEdit(row) }, () => '编辑')
)
}
if (hasAuth('site-member:delete') && !row.builtin) {
buttons.push(
h(ElButton, { link: true, type: 'danger', onClick: () => remove(row) }, () => '删除')
)
}
return h('div', { class: 'flex items-center gap-1' }, buttons)
}
}
]
}
})
const searchMembers = (value: string) => {
keyword.value = value
replaceSearchParams({ email: value.trim() || undefined })
getData()
}
const openView = async (row: SiteMember) => {
current.value = await fetchGetSiteMember(row.id)
viewVisible.value = true
}
const openEdit = (row: SiteMember) => {
form.id = row.id
form.email = row.email
form.displayName = row.displayName || ''
form.builtin = Boolean(row.builtin)
form.agentEnabled = Boolean(row.agentEnabled)
form.status = row.status
form.password = ''
editVisible.value = true
nextTick(() => formRef.value?.clearValidate())
}
const save = async () => {
if (!formRef.value) return
try {
await formRef.value.validate()
} catch {
return
}
saving.value = true
try {
await fetchUpdateSiteMember(form.id, {
email: form.email.trim(),
status: form.status,
password: form.password.trim() || undefined,
agentEnabled: form.agentEnabled,
displayName: form.builtin ? form.displayName.trim() : undefined
})
ElMessage.success('已保存')
editVisible.value = false
refreshData()
} catch {
// 失败文案由接口层展示
} finally {
saving.value = false
}
}
const remove = async (row: SiteMember) => {
try {
await ElMessageBox.confirm(`确定删除「${row.email}」吗?删除后该邮箱可以重新注册。`, '删除', {
type: 'warning'
})
} catch {
return
}
try {
await fetchDeleteSiteMember(row.id)
ElMessage.success('已删除')
refreshData()
} catch {
// 失败文案由接口层展示
}
}
</script>
+33
View File
@@ -0,0 +1,33 @@
# 复制为 deploy/.env 后由 init-env.sh 生成。不要把真实口令写入仓库。
# 下面的域名是现站口径,生成前可以用环境变量覆盖。
IMAGE_TAG=20261123
DATA_ROOT=./data
SITE_DOMAIN=www.gsrea.org.cn
SITE_NAMES="www.gsrea.org.cn gsrea.org.cn"
FILES_DOMAIN=files.gsrea.org.cn
SITE_ORIGIN=https://www.gsrea.org.cn
CORS_ORIGINS=https://www.gsrea.org.cn,https://gsrea.org.cn
MINIO_PUBLIC_SECURE=true
MINIO_BASE_URL=https://files.gsrea.org.cn/gsfdc-public
MYSQL_DATABASE=gsfdc
MYSQL_USER=gsfdc
MYSQL_PASSWORD=change-me
MYSQL_ROOT_PASSWORD=change-me
REDIS_PASSWORD=change-me
MINIO_ROOT_USER=gsfdc
MINIO_ROOT_PASSWORD=change-me
JWT_SECRET=change-me
FIELD_AES_KEY=change-me
# 可选。没有就留空,不要为了填表去抄开发环境。
GAODE_KEY=
GAODE_SECURITY_JS_CODE=
SMTP_HOST=
SMTP_PORT=465
SMTP_USER=
SMTP_PASSWORD=
SMTP_SENDER=
SMTP_USE_SSL=true
CERTBOT_EMAIL=
+45
View File
@@ -0,0 +1,45 @@
# 房地产协会站点部署
4 核 8G 上只跑这一套:门户、管理后台、Python 接口、MySQL、Redis、MinIO。教育平台和 Dify 不在这里面。
对外只开 80 和 443。数据库、Redis、MinIO 不映射到宿主机。
| 容器 | 内存上限 | 作用 |
| --- | --- | --- |
| mysql | 1400M | 缓冲池 256M,单站点够用 |
| server | 768M | 1 个 uvicorn 进程,避免启动时两进程同时建表 |
| portal | 640M | Nuxt |
| minio | 384M | 公开桶和私有桶 |
| redis | 192M | 最大 128M |
| web | 128M | Nginx、后台静态文件、反向代理 |
上传限制 32M,和后台默认 10M 的业务上限留出余量。日志单文件 10M,保留 3 份。每天 03:15 备份数据库,保留 14 天。
## 地址
- 门户:`https://www.gsrea.org.cn/`
- 后台:`https://www.gsrea.org.cn/admin/#/login`
- 接口:`https://www.gsrea.org.cn/api/site/health`
- 公开附件:`https://files.gsrea.org.cn/gsfdc-public/...`
域名以 `.env` 为准。后台接口用相对路径,换域名不用重新打包后台。
## 本机产物
`deploy/build-images.sh` 打出 linux/amd64 镜像,并打进 MySQL、Redis、MinIO。离线包在 `deploy/dist/gsfdc-bundle-<标签>.tar`。
## 服务器上
1. 上传离线包并解压。
2. `bash bootstrap-host.sh`。它安装 Docker、2G swap、只放行 80/443。看到未挂载的数据盘时先 `lsblk`,确认是空盘再格式化并挂到 `/data`。脚本不会自己格式化。
3. 有证书就把 `fullchain.pem` 和 `privkey.pem` 放进 `certs/`。没有证书时先用 HTTP 把站跑起来,内容导入前再切到最终的 https 附件地址。
4. 数据盘就绪时:`DATA_ROOT=/data/gsfdc ./init-env.sh`。然后 `./up.sh --yes`。
5. `./create-admin.sh`。口令在 `secrets/initial-admin.txt`。
6. `./check.sh`。
7. `bash install-backup-cron.sh`。
`.env` 里的 `FIELD_AES_KEY` 只能生成一次。换掉之后,已经加密的手机号和身份证解不开。
DNS 需要三条 A 记录:`www`、根域名、`files`,都指向这台机器。改解析前可以用临时 Host 头在服务器上自测。
证书申请在域名已经指过来之后执行 `./issue-cert.sh`。申请前在 `.env` 填写 `CERTBOT_EMAIL`。证书放到位后,把 `SITE_ORIGIN`、`CORS_ORIGINS`、`MINIO_BASE_URL` 改成 https,`MINIO_PUBLIC_SECURE` 改为 true,再 `./render-nginx.sh && docker compose up -d`。已经写进数据库的附件地址不会跟着变,所以正式内容放在 https 确定之后再导入。
+21
View File
@@ -0,0 +1,21 @@
#!/bin/bash
set -euo pipefail
cd "$(dirname "$0")"
if [[ ! -f .env ]]; then
echo "缺少 .env"
exit 1
fi
set -a
# shellcheck disable=SC1091
source .env
set +a
mkdir -p "${DATA_ROOT}/backups"
stamp="$(date +%Y%m%d-%H%M)"
target="${DATA_ROOT}/backups/gsfdc-${stamp}.sql.gz"
docker compose exec -T mysql mysqldump \
-uroot -p"${MYSQL_ROOT_PASSWORD}" \
--single-transaction \
--default-character-set=utf8mb4 \
"${MYSQL_DATABASE}" | gzip -1 > "$target"
find "${DATA_ROOT}/backups" -name 'gsfdc-*.sql.gz' -mtime +14 -delete
echo "已备份数据库 $target"
+62
View File
@@ -0,0 +1,62 @@
#!/bin/bash
# 只在 CentOS 服务器上执行。不格式化磁盘。
set -euo pipefail
if [[ "$(id -u)" -ne 0 ]]; then
echo "需要 root"
exit 1
fi
if [[ ! -f /etc/os-release ]] || ! grep -Eq 'CentOS Stream|centos' /etc/os-release; then
echo "这个脚本只在 CentOS 服务器上执行"
exit 1
fi
if ! swapon --show | grep -q .; then
if [[ ! -f /swapfile ]]; then
fallocate -l 2G /swapfile
chmod 600 /swapfile
mkswap /swapfile
fi
swapon /swapfile || true
grep -q '/swapfile' /etc/fstab || echo '/swapfile none swap sw 0 0' >> /etc/fstab
fi
cat > /etc/sysctl.d/99-gsfdc.conf <<'EOF'
vm.swappiness=10
vm.overcommit_memory=1
net.core.somaxconn=1024
EOF
sysctl --system >/dev/null || true
if ! command -v docker >/dev/null 2>&1; then
dnf -y install dnf-plugins-core
dnf config-manager --add-repo https://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo
dnf -y install docker-ce docker-ce-cli containerd.io docker-compose-plugin
fi
if [[ ! -f /etc/docker/daemon.json ]]; then
mkdir -p /etc/docker
cat > /etc/docker/daemon.json <<'EOF'
{
"registry-mirrors": ["https://docker.1ms.run", "https://docker.m.daocloud.io"],
"log-driver": "json-file",
"log-opts": {"max-size": "10m", "max-file": "3"},
"live-restore": true
}
EOF
fi
systemctl enable --now docker
if mountpoint -q /data; then
mkdir -p /data/gsfdc
echo "数据盘已挂在 /data。生成配置时使用 DATA_ROOT=/data/gsfdc"
else
echo "没有挂载 /data。先不要格式化磁盘。用 lsblk 确认数据盘后,再决定挂载点。"
echo "在此之前数据放在部署目录的 data/。"
fi
if systemctl is-active --quiet firewalld; then
firewall-cmd --permanent --add-service=http
firewall-cmd --permanent --add-service=https
firewall-cmd --reload
fi
echo "主机准备完成。接下来在部署目录执行 docker load 和 ./up.sh"
+48
View File
@@ -0,0 +1,48 @@
#!/bin/bash
# 在开发机上构建 linux/amd64 镜像。服务器是 x86,本机是 Apple 芯片时也不能打成 arm64。
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
TAG="${IMAGE_TAG:-20261123}"
export IMAGE_TAG="$TAG"
echo "$TAG" > "$ROOT/deploy/IMAGE_TAG"
echo "拉取 linux/amd64 基础镜像"
python3 "$ROOT/deploy/pull-bases.py"
echo "构建门户"
cd "$ROOT/portal"
npm ci --registry=https://registry.npmmirror.com
NODE_OPTIONS=--max-old-space-size=4096 npm run build
echo "构建管理后台"
cd "$ROOT/admin"
# 现有模板的 vue-tsc 有一批与本次部署无关的类型错误,打包用 vite 产物。
VITE_BASE_URL=/admin/ VITE_API_URL=/ VITE_DROP_CONSOLE=true NODE_OPTIONS=--max-old-space-size=4096 pnpm exec vite build
echo "把基础镜像展开成 linux/amd64 实体,避免只保存多架构索引"
materialize() {
docker buildx build --platform linux/amd64 --provenance=false --sbom=false --load -t "$1" - <<EOF
FROM $1
EOF
}
materialize mysql:8.0
materialize redis:7.4-alpine
materialize minio/minio:latest
echo "构建镜像 linux/amd64"
docker buildx build --platform linux/amd64 --provenance=false --sbom=false --load \
-t "gsfdc-server:${TAG}" -f "$ROOT/server/Dockerfile" "$ROOT/server"
docker buildx build --platform linux/amd64 --provenance=false --sbom=false --load \
-t "gsfdc-portal:${TAG}" -f "$ROOT/portal/Dockerfile" "$ROOT/portal"
docker buildx build --platform linux/amd64 --provenance=false --sbom=false --load \
-t "gsfdc-web:${TAG}" -f "$ROOT/admin/Dockerfile" "$ROOT/admin"
for name in "gsfdc-server:${TAG}" "gsfdc-portal:${TAG}" "gsfdc-web:${TAG}" mysql:8.0 redis:7.4-alpine minio/minio:latest; do
arch="$(docker image inspect "$name" --format '{{.Architecture}}')"
if [[ "$arch" != "amd64" ]]; then
echo "$name 架构是 $arch,不能拿到 x86 服务器上跑"
exit 1
fi
done
"$ROOT/deploy/package-images.sh"
View File
Whitespace-only changes.
View File
Whitespace-only changes.
+33
View File
@@ -0,0 +1,33 @@
#!/bin/bash
set -euo pipefail
cd "$(dirname "$0")"
if [[ ! -f .env ]]; then
echo "缺少 .env"
exit 1
fi
set -a
# shellcheck disable=SC1091
source .env
set +a
code=0
echo -n "门户 "
if curl -fsS -o /dev/null -w "%{http_code}\n" -H "Host: ${SITE_DOMAIN}" http://127.0.0.1/; then
true
else
code=1
fi
echo -n "后台 "
if curl -fsS -o /dev/null -w "%{http_code}\n" -H "Host: ${SITE_DOMAIN}" http://127.0.0.1/admin/; then
true
else
code=1
fi
echo -n "接口 "
if curl -fsS -H "Host: ${SITE_DOMAIN}" http://127.0.0.1/api/site/health; then
echo
else
code=1
fi
docker compose ps
exit "$code"
+32
View File
@@ -0,0 +1,32 @@
#!/bin/bash
set -euo pipefail
cd "$(dirname "$0")"
if [[ ! -f .env ]]; then
echo "缺少 .env"
exit 1
fi
user="${1:-admin}"
pass="Aa$(openssl rand -hex 12)"
install -d -m 700 secrets
umask 077
printf 'username=%s\npassword=%s\n' "$user" "$pass" > secrets/initial-admin.txt
chmod 600 secrets/initial-admin.txt
ready=0
for _ in 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20; do
if docker compose exec -T server python -c "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8000/api/site/health', timeout=3)" >/dev/null 2>&1; then
ready=1
break
fi
sleep 3
done
if [[ "$ready" != 1 ]]; then
echo "服务还没就绪。初始口令已写在 secrets/initial-admin.txt,稍后重跑会换一套口令。"
exit 1
fi
docker compose run --rm --no-deps --entrypoint python \
-e BOOTSTRAP_ADMIN_USERNAME="$user" \
-e BOOTSTRAP_ADMIN_PASSWORD="$pass" \
server -m app.commands.create_superuser
echo "初始管理员已写入 secrets/initial-admin.txt"
+215
View File
@@ -0,0 +1,215 @@
name: gsfdc
x-logging: &logging
driver: json-file
options:
max-size: "10m"
max-file: "3"
services:
mysql:
image: mysql:8.0
container_name: gsfdc-mysql
restart: unless-stopped
init: true
logging: *logging
environment:
MYSQL_DATABASE: ${MYSQL_DATABASE}
MYSQL_USER: ${MYSQL_USER}
MYSQL_PASSWORD: ${MYSQL_PASSWORD}
MYSQL_ROOT_PASSWORD: ${MYSQL_ROOT_PASSWORD}
TZ: Asia/Shanghai
command:
- --character-set-server=utf8mb4
- --collation-server=utf8mb4_unicode_ci
volumes:
- ${DATA_ROOT}/mysql:/var/lib/mysql
- ./mysql/my.cnf:/etc/mysql/conf.d/gsfdc.cnf:ro
shm_size: 256m
healthcheck:
test: ["CMD-SHELL", "mysqladmin ping -h 127.0.0.1 -uroot -p\"$$MYSQL_ROOT_PASSWORD\" --silent"]
interval: 10s
timeout: 5s
retries: 30
start_period: 40s
deploy:
resources:
limits:
memory: 1400M
networks:
- gsfdc
redis:
image: redis:7.4-alpine
container_name: gsfdc-redis
restart: unless-stopped
init: true
logging: *logging
command:
- redis-server
- --appendonly
- "yes"
- --maxmemory
- 128mb
- --maxmemory-policy
- allkeys-lru
- --requirepass
- ${REDIS_PASSWORD}
environment:
TZ: Asia/Shanghai
volumes:
- ${DATA_ROOT}/redis:/data
healthcheck:
test: ["CMD-SHELL", "REDISCLI_AUTH=\"$$REDIS_PASSWORD\" redis-cli ping | grep -q PONG"]
interval: 10s
timeout: 3s
retries: 20
start_period: 10s
deploy:
resources:
limits:
memory: 192M
networks:
- gsfdc
minio:
image: minio/minio:latest
container_name: gsfdc-minio
restart: unless-stopped
init: true
logging: *logging
command: ["server", "/data", "--console-address", ":9001"]
environment:
MINIO_ROOT_USER: ${MINIO_ROOT_USER}
MINIO_ROOT_PASSWORD: ${MINIO_ROOT_PASSWORD}
TZ: Asia/Shanghai
volumes:
- ${DATA_ROOT}/minio:/data
deploy:
resources:
limits:
memory: 384M
networks:
- gsfdc
server:
image: gsfdc-server:${IMAGE_TAG}
container_name: gsfdc-server
restart: unless-stopped
init: true
logging: *logging
env_file:
- .env
environment:
DATABASE_URL: mysql+pymysql://${MYSQL_USER}:${MYSQL_PASSWORD}@mysql:3306/${MYSQL_DATABASE}?charset=utf8mb4
MYSQL_HOST: mysql
MYSQL_PORT: "3306"
MYSQL_USER: ${MYSQL_USER}
MYSQL_PASSWORD: ${MYSQL_PASSWORD}
MYSQL_DATABASE: ${MYSQL_DATABASE}
REDIS_HOST: redis
REDIS_PORT: "6379"
REDIS_PASSWORD: ${REDIS_PASSWORD}
MINIO_ENDPOINT: minio:9000
MINIO_SECURE: "false"
MINIO_ACCESS_KEY: ${MINIO_ROOT_USER}
MINIO_SECRET_KEY: ${MINIO_ROOT_PASSWORD}
MINIO_BUCKET_PUBLIC: gsfdc-public
MINIO_BUCKET_PRIVATE: gsfdc-private
MINIO_PUBLIC_ENDPOINT: ${FILES_DOMAIN}
MINIO_PUBLIC_SECURE: ${MINIO_PUBLIC_SECURE}
MINIO_BASE_URL: ${MINIO_BASE_URL}
TRUST_PROXY: "true"
EXPOSE_DOCS: "false"
API_PAYLOAD_ENCRYPT: "false"
CORS_ORIGINS: ${CORS_ORIGINS}
JWT_SECRET: ${JWT_SECRET}
FIELD_AES_KEY: ${FIELD_AES_KEY}
UVICORN_WORKERS: "1"
TZ: Asia/Shanghai
depends_on:
mysql:
condition: service_healthy
redis:
condition: service_healthy
minio:
condition: service_started
healthcheck:
test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8000/api/site/health', timeout=3)"]
interval: 15s
timeout: 5s
retries: 20
start_period: 50s
deploy:
resources:
limits:
memory: 768M
networks:
- gsfdc
portal:
image: gsfdc-portal:${IMAGE_TAG}
container_name: gsfdc-portal
restart: unless-stopped
init: true
logging: *logging
environment:
HOST: 0.0.0.0
PORT: "3000"
NITRO_HOST: 0.0.0.0
NITRO_PORT: "3000"
NODE_ENV: production
NODE_OPTIONS: --max-old-space-size=384
NUXT_API_BASE: http://server:8000/api/site
NUXT_PUBLIC_API_BASE: /api/site
TZ: Asia/Shanghai
depends_on:
server:
condition: service_started
healthcheck:
test: ["CMD", "node", "-e", "fetch('http://127.0.0.1:3000/').then((r)=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))"]
interval: 15s
timeout: 5s
retries: 12
start_period: 25s
deploy:
resources:
limits:
memory: 640M
networks:
- gsfdc
web:
image: gsfdc-web:${IMAGE_TAG}
container_name: gsfdc-web
restart: unless-stopped
init: true
logging: *logging
ports:
- "80:80"
- "443:443"
volumes:
- ./nginx/active.conf:/etc/nginx/conf.d/default.conf:ro
- ./certs:/etc/nginx/certs:ro
- ./certbot:/var/www/certbot:ro
depends_on:
portal:
condition: service_started
server:
condition: service_started
healthcheck:
test: ["CMD", "wget", "-q", "-O", "/dev/null", "http://127.0.0.1/admin/"]
interval: 15s
timeout: 5s
retries: 12
start_period: 10s
deploy:
resources:
limits:
memory: 128M
networks:
- gsfdc
networks:
gsfdc:
name: gsfdc
+77
View File
@@ -0,0 +1,77 @@
#!/bin/bash
# 只在还没有 .env 时生成。已有文件不覆盖,避免把字段加密密钥换掉。
set -euo pipefail
cd "$(dirname "$0")"
if [[ -f .env ]]; then
echo ".env 已存在,保持不变"
exit 0
fi
umask 077
python3 - <<'PY'
import base64
import os
import secrets
from pathlib import Path
root = Path(".")
tag = os.environ.get("IMAGE_TAG", "").strip()
tag_file = root / "IMAGE_TAG"
if not tag and tag_file.exists():
tag = tag_file.read_text(encoding="utf-8").strip()
if not tag:
tag = "20261123"
site = os.environ.get("SITE_DOMAIN", "www.gsrea.org.cn").strip()
apex = site[4:] if site.startswith("www.") else site
names = os.environ.get("SITE_NAMES", f"{site} {apex}").strip()
files = os.environ.get("FILES_DOMAIN", f"files.{apex}").strip()
data_root = os.environ.get("DATA_ROOT", "./data").strip() or "./data"
cert_ready = (root / "certs" / "fullchain.pem").is_file() or (
root / "certs" / "live" / site / "fullchain.pem"
).is_file()
scheme = "https" if cert_ready else "http"
origin = f"{scheme}://{site}"
cors = f"{scheme}://{site}"
if apex != site:
cors = f"{cors},{scheme}://{apex}"
def q(value: str) -> str:
return '"' + value.replace("\\", "\\\\").replace('"', '\\"') + '"'
lines = [
f"IMAGE_TAG={q(tag)}",
f"DATA_ROOT={q(data_root)}",
f"SITE_DOMAIN={q(site)}",
f"SITE_NAMES={q(names)}",
f"FILES_DOMAIN={q(files)}",
f"SITE_ORIGIN={q(origin)}",
f"CORS_ORIGINS={q(cors)}",
f"MINIO_PUBLIC_SECURE={q('true' if cert_ready else 'false')}",
f"MINIO_BASE_URL={q(f'{scheme}://{files}/gsfdc-public')}",
"MYSQL_DATABASE=gsfdc",
"MYSQL_USER=gsfdc",
f"MYSQL_PASSWORD={q(secrets.token_hex(24))}",
f"MYSQL_ROOT_PASSWORD={q(secrets.token_hex(24))}",
f"REDIS_PASSWORD={q(secrets.token_hex(24))}",
"MINIO_ROOT_USER=gsfdc",
f"MINIO_ROOT_PASSWORD={q(secrets.token_hex(24))}",
f"JWT_SECRET={q(secrets.token_hex(32))}",
f"FIELD_AES_KEY={q(base64.b64encode(secrets.token_bytes(32)).decode('ascii'))}",
"GAODE_KEY=",
"GAODE_SECURITY_JS_CODE=",
"SMTP_HOST=",
"SMTP_PORT=465",
"SMTP_USER=",
"SMTP_PASSWORD=",
"SMTP_SENDER=",
"SMTP_USE_SSL=true",
"CERTBOT_EMAIL=",
]
path = root / ".env"
path.write_text("\n".join(lines) + "\n", encoding="utf-8")
os.chmod(path, 0o600)
print(f"已生成 .env ,权限 600。站点 {origin} ,附件 {scheme}://{files}/")
print("字段加密密钥只在这个文件里。不要重新生成,否则已加密的手机号和身份证无法解密。")
PY
+12
View File
@@ -0,0 +1,12 @@
#!/bin/bash
set -euo pipefail
if [[ "$(id -u)" -ne 0 ]]; then
echo "需要 root"
exit 1
fi
dir="$(cd "$(dirname "$0")" && pwd)"
cat > /etc/cron.d/gsfdc-backup <<EOF
15 3 * * * root ${dir}/backup.sh >> ${dir}/backup.log 2>&1
EOF
chmod 644 /etc/cron.d/gsfdc-backup
echo "已安装每天 03:15 的数据库备份"
+29
View File
@@ -0,0 +1,29 @@
#!/bin/bash
# 域名已经解析到这台机器、80 端口可从公网访问之后再执行。
set -euo pipefail
cd "$(dirname "$0")"
if [[ ! -f .env ]]; then
echo "缺少 .env"
exit 1
fi
set -a
# shellcheck disable=SC1091
source .env
set +a
if [[ -z "${CERTBOT_EMAIL:-}" ]]; then
echo "先在 .env 里填写 CERTBOT_EMAIL"
exit 1
fi
mkdir -p certs certbot
domains=(-d "$SITE_DOMAIN" -d "$FILES_DOMAIN")
apex="${SITE_DOMAIN#www.}"
if [[ "$apex" != "$SITE_DOMAIN" ]]; then
domains+=(-d "$apex")
fi
docker run --rm \
-v "$PWD/certs:/etc/letsencrypt" \
-v "$PWD/certbot:/var/www/certbot" \
certbot/certbot certonly --webroot -w /var/www/certbot \
--email "$CERTBOT_EMAIL" --agree-tos --no-eff-email \
"${domains[@]}"
echo "证书已写入 certs/live/${SITE_DOMAIN}/ 。接着修改 .env 里的站点地址为 https,再执行 ./render-nginx.sh && docker compose up -d"
+11
View File
@@ -0,0 +1,11 @@
[mysqld]
character-set-server = utf8mb4
collation-server = utf8mb4_unicode_ci
innodb_buffer_pool_size = 256M
innodb_log_buffer_size = 16M
max_connections = 80
performance_schema = OFF
table_open_cache = 400
skip-name-resolve
slow_query_log = ON
long_query_time = 2
+79
View File
@@ -0,0 +1,79 @@
server_tokens off;
client_max_body_size 32m;
gzip on;
gzip_comp_level 5;
gzip_min_length 1024;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml image/svg+xml;
resolver 127.0.0.11 valid=10s ipv6=off;
server {
listen 80;
server_name ${SITE_NAMES};
add_header X-Content-Type-Options nosniff always;
add_header Referrer-Policy strict-origin-when-cross-origin always;
add_header X-Frame-Options SAMEORIGIN always;
location ^~ /.well-known/acme-challenge/ {
root /var/www/certbot;
default_type "text/plain";
}
location ~ ^/(docs|redoc|openapi\.json)$ {
return 404;
}
location /api/ {
set $api_backend server;
proxy_pass http://$api_backend:8000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_read_timeout 120s;
proxy_send_timeout 120s;
}
location = /admin {
return 301 /admin/;
}
location /admin/ {
alias /usr/share/nginx/html/admin/;
index index.html;
}
location / {
set $portal_backend portal;
proxy_pass http://$portal_backend:3000;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Connection "";
}
}
server {
listen 80;
server_name ${FILES_DOMAIN};
location ^~ /.well-known/acme-challenge/ {
root /var/www/certbot;
default_type "text/plain";
}
location / {
limit_except GET HEAD {
deny all;
}
set $minio_backend minio;
proxy_pass http://$minio_backend:9000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_buffering off;
}
}
+91
View File
@@ -0,0 +1,91 @@
server_tokens off;
client_max_body_size 32m;
gzip on;
gzip_comp_level 5;
gzip_min_length 1024;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml image/svg+xml;
resolver 127.0.0.11 valid=10s ipv6=off;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 1d;
ssl_protocols TLSv1.2 TLSv1.3;
server {
listen 80;
server_name ${SITE_NAMES} ${FILES_DOMAIN};
location ^~ /.well-known/acme-challenge/ {
root /var/www/certbot;
default_type "text/plain";
}
location / {
return 301 https://$host$request_uri;
}
}
server {
listen 443 ssl;
server_name ${SITE_NAMES};
ssl_certificate ${CERT_FULL};
ssl_certificate_key ${CERT_KEY};
add_header Strict-Transport-Security "max-age=15552000" always;
add_header X-Content-Type-Options nosniff always;
add_header Referrer-Policy strict-origin-when-cross-origin always;
add_header X-Frame-Options SAMEORIGIN always;
location ~ ^/(docs|redoc|openapi\.json)$ {
return 404;
}
location /api/ {
set $api_backend server;
proxy_pass http://$api_backend:8000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_read_timeout 120s;
proxy_send_timeout 120s;
}
location = /admin {
return 301 /admin/;
}
location /admin/ {
alias /usr/share/nginx/html/admin/;
index index.html;
}
location / {
set $portal_backend portal;
proxy_pass http://$portal_backend:3000;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Connection "";
}
}
server {
listen 443 ssl;
server_name ${FILES_DOMAIN};
ssl_certificate ${CERT_FULL};
ssl_certificate_key ${CERT_KEY};
location / {
limit_except GET HEAD {
deny all;
}
set $minio_backend minio;
proxy_pass http://$minio_backend:9000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_buffering off;
}
}
+32
View File
@@ -0,0 +1,32 @@
#!/bin/bash
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
TAG="${IMAGE_TAG:-20261123}"
if [[ -f "$ROOT/deploy/IMAGE_TAG" ]]; then
TAG="$(tr -d '[:space:]' < "$ROOT/deploy/IMAGE_TAG")"
fi
OUT="$ROOT/deploy/dist"
STAGE="$OUT/gsfdc-bundle"
rm -rf "$STAGE"
mkdir -p "$STAGE/nginx" "$STAGE/mysql" "$STAGE/certs" "$STAGE/certbot"
cp "$ROOT/deploy/docker-compose.yml" "$ROOT/deploy/.env.example" "$STAGE/"
cp "$ROOT/deploy/IMAGE_TAG" "$STAGE/" 2>/dev/null || echo "$TAG" > "$STAGE/IMAGE_TAG"
cp "$ROOT/deploy/"*.sh "$STAGE/"
cp "$ROOT/deploy/nginx/"*.template "$STAGE/nginx/"
cp "$ROOT/deploy/mysql/my.cnf" "$STAGE/mysql/"
cp "$ROOT/deploy/README.md" "$STAGE/" 2>/dev/null || true
echo "打包镜像(含 MySQL、Redis、MinIO)"
docker save \
"gsfdc-server:${TAG}" \
"gsfdc-portal:${TAG}" \
"gsfdc-web:${TAG}" \
mysql:8.0 \
redis:7.4-alpine \
minio/minio:latest \
| gzip -1 > "$STAGE/images.tar.gz"
tar -C "$OUT" -cf "$OUT/gsfdc-bundle-${TAG}.tar" gsfdc-bundle
ls -lh "$STAGE/images.tar.gz" "$OUT/gsfdc-bundle-${TAG}.tar"
echo "离线包 $OUT/gsfdc-bundle-${TAG}.tar"
+131
View File
@@ -0,0 +1,131 @@
#!/usr/bin/env python3
"""通过 Docker Engine API 拉取 linux/amd64 基础镜像。
本机访问 Docker Hub 会超时。docker pull 在非交互终端里可能一直没有输出,
所以直接把请求发给引擎,再打上构建用的官方名字。
"""
import json
import socket
import sys
import urllib.parse
SOCK = "/Users/zlwu/.docker/run/docker.sock"
IMAGES = [
("docker.1ms.run/library/nginx", "1.27-alpine", "nginx:1.27-alpine"),
("docker.1ms.run/library/mysql", "8.0", "mysql:8.0"),
("docker.1ms.run/library/redis", "7.4-alpine", "redis:7.4-alpine"),
("docker.1ms.run/library/python", "3.12-slim-bookworm", "python:3.12-slim-bookworm"),
("docker.1ms.run/library/node", "22-bookworm-slim", "node:22-bookworm-slim"),
("docker.1panel.live/minio/minio", "latest", "minio/minio:latest"),
]
def request(method: str, path: str, body: bytes = b"") -> bytes:
header = (
f"{method} {path} HTTP/1.1\r\n"
"Host: localhost\r\n"
"Connection: close\r\n"
f"Content-Length: {len(body)}\r\n"
"\r\n"
).encode()
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
sock.settimeout(900)
sock.connect(SOCK)
sock.sendall(header + body)
chunks = []
while True:
try:
data = sock.recv(65536)
except socket.timeout:
raise SystemExit(f"引擎没有在时限内完成 {path}")
if not data:
break
chunks.append(data)
sock.close()
raw = b"".join(chunks)
head, _, payload = raw.partition(b"\r\n\r\n")
status = head.split(b" ", 2)[1]
if status != b"200" and status != b"201":
raise SystemExit(f"{path} -> {status.decode()} {payload[:400]!r}")
return payload
def stream(method: str, path: str) -> None:
header = (
f"{method} {path} HTTP/1.1\r\n"
"Host: localhost\r\n"
"Connection: close\r\n"
"Content-Length: 0\r\n"
"\r\n"
).encode()
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
sock.settimeout(900)
sock.connect(SOCK)
sock.sendall(header)
buffer = b""
header_done = False
error = None
last = ""
while True:
try:
data = sock.recv(65536)
except socket.timeout:
sock.close()
raise SystemExit(f"引擎没有在时限内完成 {path}")
if not data:
break
buffer += data
if not header_done:
if b"\r\n\r\n" not in buffer:
continue
head, buffer = buffer.split(b"\r\n\r\n", 1)
status = head.split(b" ", 2)[1]
if status not in (b"200", b"201"):
sock.close()
raise SystemExit(f"{path} -> {status.decode()} {buffer[:400]!r}")
header_done = True
while b"\n" in buffer:
line, buffer = buffer.split(b"\n", 1)
line = line.strip()
if not line.startswith(b"{"):
continue
try:
item = json.loads(line)
except json.JSONDecodeError:
continue
if "error" in item:
error = item["error"]
status_text = item.get("status") or ""
if status_text and status_text != last:
last = status_text
print(f" {status_text}", flush=True)
sock.close()
if error:
raise SystemExit(error)
def pull(source: str, tag: str, official: str) -> None:
query = urllib.parse.urlencode(
{"fromImage": source, "tag": tag, "platform": "linux/amd64"}
)
print(f"拉取 {source}:{tag}", flush=True)
stream("POST", f"/v1.47/images/create?{query}")
source_ref = f"{source}:{tag}"
repo, official_tag = official.split(":", 1)
tag_query = urllib.parse.urlencode({"repo": repo, "tag": official_tag})
encoded = urllib.parse.quote(source_ref, safe="")
request("POST", f"/v1.47/images/{encoded}/tag?{tag_query}")
print(f"已标记 {official}", flush=True)
def main() -> None:
for source, tag, official in IMAGES:
pull(source, tag, official)
print("BASE_IMAGES_OK", flush=True)
if __name__ == "__main__":
try:
main()
except BrokenPipeError:
sys.exit(1)
+52
View File
@@ -0,0 +1,52 @@
#!/bin/bash
set -euo pipefail
cd "$(dirname "$0")"
if [[ ! -f .env ]]; then
echo "缺少 .env,先执行 ./init-env.sh"
exit 1
fi
set -a
# shellcheck disable=SC1091
source .env
set +a
python3 - <<'PY'
import os
from pathlib import Path
root = Path(".")
site = os.environ["SITE_DOMAIN"].strip()
files = os.environ["FILES_DOMAIN"].strip()
names = os.environ.get("SITE_NAMES", site).strip()
flat = root / "certs" / "fullchain.pem"
flat_key = root / "certs" / "privkey.pem"
live = root / "certs" / "live" / site / "fullchain.pem"
live_key = root / "certs" / "live" / site / "privkey.pem"
https = (flat.is_file() and flat_key.is_file()) or (live.is_file() and live_key.is_file())
if flat.is_file() and flat_key.is_file():
cert_full = "/etc/nginx/certs/fullchain.pem"
cert_key = "/etc/nginx/certs/privkey.pem"
elif live.is_file() and live_key.is_file():
cert_full = f"/etc/nginx/certs/live/{site}/fullchain.pem"
cert_key = f"/etc/nginx/certs/live/{site}/privkey.pem"
else:
cert_full = ""
cert_key = ""
src = root / "nginx" / ("https.conf.template" if https else "http.conf.template")
text = src.read_text(encoding="utf-8")
values = {
"SITE_NAMES": names,
"FILES_DOMAIN": files,
"CERT_FULL": cert_full,
"CERT_KEY": cert_key,
}
for key, value in values.items():
text = text.replace("${" + key + "}", value)
if "${" in text:
raise SystemExit("nginx 模板仍有未替换的占位符")
out = root / "nginx" / "active.conf"
out.write_text(text, encoding="utf-8")
print(("https" if https else "http") + " 配置已写入 nginx/active.conf")
PY
Executable
+15
View File
@@ -0,0 +1,15 @@
#!/bin/bash
set -euo pipefail
cd "$(dirname "$0")"
created=0
if [[ ! -f .env ]]; then
./init-env.sh
created=1
fi
./render-nginx.sh
if [[ "$created" == 1 && "${1:-}" != "--yes" ]]; then
echo "请先核对 .env 里的域名。确认后执行 ./up.sh --yes"
exit 0
fi
docker compose --env-file .env up -d
docker compose ps
@@ -0,0 +1,65 @@
# 智能估价设计
状态:三步均已接到门户。视觉以已确认 HTML 原型为准。成稿按已启用的 Word 或 PPT 模版生成,文末保留「本成稿为辅助文稿,不构成正式评估意见。」Word 模版下载 docx,PPT 模版下载 pptx。
## 已确认的界面
原型:`.scratch/expert-service/dianshi-prototype.html`。
- 名称:**智能估价**。品牌标志用协会 logo(`docs/参考/现站/基础数据/logo/logo.jpg`)。
- 浅色科技蓝:页面底约 `#eef5ff`,面板近白,主按钮纯色 `#3b82f6`,不用渐变按钮。
- 左侧:新会话、会话列表(按最近活跃倒序)、`···` 菜单(重命名、删除)、底部当前用户名与退出登录。
- 右侧:对话区占满剩余高度,输入区贴底。
- 新会话由助手先说话,气泡内展示已启用的推荐问题;用户发送或点选后,该会话不再重复推荐按钮。
- 输入区:附件、文本、按模版生成、发送。
- 说明行左侧为支持的文件类型与风险提示,右侧为「内网知识库 · 默认开启」和「联网检索」开关。开关按会话记住,开启后保持到用户手动关闭。
- 回答可折叠「思考过程」。
- 用户头像为双人线稿,颜色 `#4a90e2`。助手头像为协会 logo。
## 已确认的范围
- 推荐问题的管理按钮在聊天页,仅管理员可见。模版管理同页,留到第三步。
- 第一步:登录后续聊、Dify 知识库流式问答、开场推荐、重命名与删除。
- 管理员:门户会员邮箱与一名启用中的工作人员用户名相同,或邮箱写在 `VALUATION_ADMIN_EMAILS`。
## 权限
| 动作 | 未登录 | 登录会员 | 管理员 |
|---|---|---|---|
| 打开页面 | 可看入口,须登录后聊天 | 可 | 可 |
| 会话增删改查、问答 | 否 | 仅自己的 | 仅自己的 |
| 改推荐问题、上传/启停/删除模版 | 否 | 否 | 是 |
| 选择已启用模版生成 | 否 | 是 | 是 |
管理员判定沿用现有工作人员账号(`admin/` 登录态),不在门户会员表里另造一套管理员。
## 数据
- `valuation_sessions`:会员 id、标题、Dify conversation id、更新时间。
- `valuation_messages`:会话 id、角色、正文、思考过程、附件引用。门户落库,刷新后仍在。
- `valuation_suggestions`:文案、排序、是否启用。
- `valuation_templates`:名称、私有桶文件、是否启用。
- 附件走现有私有桶,绑定会话与上传人。
删除会话:删本侧会话、消息和附件关联;能删则同步删 Dify 会话。不可恢复。
## Dify
- 浏览器只调 `/api/site/valuation/*`。
- 服务端使用已配置的估价应用 API Key,流式转发。
- 默认检索模式不启用联网工具;打开「联网检索」时才允许,且只作用于当前会话。服务端从当前网络可打开的搜索页取最多 8 条标题、摘要和来源网址,写入联网摘录。连接失败时明确告诉模型没有取回网页。
- 思考过程映射 Dify 的 reasoning / agent thought;没有则不渲染空壳。
## 附件白名单
pdf、docx、txt、md、xlsx、xls、csv、jpg、jpeg、png、webp。文档类附件提取正文后写入提问,单份最多 32000 字;图片交给模型识别图片中的文字。回答底部按本轮实际情况列出出处:用了附件就标「附件」,知识库检索到文档就标「知识库」。两者都有时分列,不互相覆盖。
单文件不超过站点 `upload_max_bytes`。单次随消息提交的附件不超过 5 个。不接受 gif、svg、doc、音视频、ppt、压缩包。
## 模版成稿
用户在对话里提出生成文档时,先选择一份已启用模版;系统按本次要求检索知识库,再按模版章节或幻灯片顺序生成。模版接受 docx 与 pptx。不选模版时,根据本次要求决定生成 Word、PPT、Excel、CSV、Markdown 或纯文本。不把此前会话闲聊写入正文。文案必须写明不构成正式评估报告。模版文件仅管理员上传。下载文件是按提纲新生成的,不保留原模版的版式、图片和动画。
## 风险
每条模型回答都保留:「本回答仅供参考,不构成正式评估意见。」成稿保留:「本成稿为辅助文稿,不构成正式评估意见。」
@@ -0,0 +1,35 @@
# 智能估价
状态:约定的三步已实现,验收四项已核对。界面原型已确认。管理按钮留在聊天页,仅管理员可见。
## Why
门户「专家服务 / 智能估价」目前只是未接入模型的对话样式。本机 Dify 已有估价知识库与「估价智能体」。需要按已确认原型,做成可登录续聊、可配置、可按模版出辅助文稿的工作台。
## What Changes
- 门户 `/expert/assistant` 换成已确认的浅色「智能估价」工作台:左侧会话、开场推荐问题、流式回答、可折叠思考过程、附件、联网开关、按模版生成。
- 会话、消息、推荐问题、报告模版由 `server/` 持久化,并代理 Dify,密钥不进浏览器。
- 推荐问题与报告模版仅管理员可改;其他登录用户只能使用。
- 成稿称为辅助文稿,不构成正式评估报告,不实现完整智能估价平台。
## Non-goals
- 不代替有资质机构出具正式评估报告或备案结论。
- 不在 `edu/` 实现。
- 不把 Dify 控制台嵌进门户。
- 访客不持久化会话(须登录)。
## Capabilities
- `valuation-chat`: 多会话问答、开场推荐、思考过程、删除与重命名。
- `valuation-files`: 按白名单上传附件并针对附件提问。
- `valuation-templates`: 管理员维护模版;用户选择模版生成辅助文稿。
- `valuation-retrieval`: 默认仅内网知识库,可另开联网补充。
## Impact
- `portal/`:专家服务智能估价页。
- `server/`:会员接口与管理员接口、表结构。
- `admin/`:仅当确认「管理放后台」时改;若确认「管理留在聊天页」则不改管理端页面。
- 依赖本机 Dify(`http://127.0.0.1:13080`)及已建估价应用。
@@ -0,0 +1,39 @@
# valuation-chat
## Requirements
### Requirement: 登录后的多会话
系统 MUST 只为已登录会员保存会话。每个会话 MUST 只属于创建它的会员。会员 MUST 能新建、打开、重命名和删除自己的会话。删除后 MUST 不可恢复。
#### Scenario: 续聊
- **WHEN** 会员再次打开智能估价
- **THEN** 系统展示该会员以往会话,并可以打开其中一条继续提问
#### Scenario: 越权
- **WHEN** 会员请求另一个会员的会话
- **THEN** 系统拒绝,且不返回该会话内容
### Requirement: 开场与推荐问题
新建或尚无用户消息的会话 MUST 先展示助手开场,并展示已启用的推荐问题。用户发送或点选推荐问题后,该会话 MUST NOT 再显示推荐按钮。
#### Scenario: 点选推荐问题
- **WHEN** 会员点击一条推荐问题
- **THEN** 系统把它当作该会员发出的问题,并向 Dify 请求回答
### Requirement: 推荐问题仅管理员可改
系统 MUST 允许管理员新增、修改、排序、启用或删除推荐问题。非管理员 MUST NOT 修改推荐问题。门户 MUST 只展示已启用项。
#### Scenario: 会员尝试修改
- **WHEN** 登录会员调用推荐问题管理接口
- **THEN** 系统返回 403,且推荐问题保持不变
### Requirement: 按模版生成辅助文稿
系统 MUST 提供至少一份可启用的报告模版。管理员 MUST 能上传 docx 模版、启用、停用和删除。非管理员 MUST NOT 修改模版。登录会员 MUST 能选择一份已启用模版,结合当前会话生成辅助文稿。成稿 MUST 写明不构成正式评估意见,并可以下载为 docx。
#### Scenario: 会员上传模版
- **WHEN** 非管理员上传模版
- **THEN** 系统返回 403
#### Scenario: 停用后不可生成
- **WHEN** 会员选择一份已停用模版生成
- **THEN** 系统拒绝,且不保存成稿
+34
View File
@@ -0,0 +1,34 @@
# 任务
第一步:门户聊天页 + 后端会话与推荐问题。不改 `admin/` 页面。
## 1. 规格
- [x] 记录已确认原型与产品边界(本目录 proposal / design)
- [x] 用户确认:管理留在聊天页;第一步只做会话问答
## 2. 第一步
- [x] 会话与消息表、推荐问题表
- [x] 会员接口:列表、新建、重命名、删除、拉历史、流式提问
- [x] 聊天页内的推荐问题管理接口(仅管理员)
- [x] 门户工作台接上上述接口,登录后续聊
- [x] 默认推荐三条(日播时尚 / 华润三九 / 浙江建投),管理员可改
- [x] 本机对 Dify 估价智能体打通一条流式回答;会话接口单测 5 项通过
## 3. 第二步
- [x] 附件上传与「基于附件」提问
- [x] 联网补充开关
## 4. 第三步
- [x] 模版上传、启停、删除(仅管理员)
- [x] 用户选择模版生成辅助文稿
## 5. 验收
- [x] 会员 A 看不到会员 B 的会话(接口测试:他人会话 404)
- [x] 非管理员调用管理接口返回 403(推荐问题与模版上传)
- [x] 删除当前会话后回到最近一条或新会话开场(登录后页面点过:只剩一条时开新会话,还有另一条时留在那一条并显示开场)
- [x] 刷新页面后会话与消息仍在(登录后刷新,原会话标题与开场还在)
+6
View File
@@ -0,0 +1,6 @@
node_modules
.nuxt
.git
.env
.env.*
*.log
+14
View File
@@ -0,0 +1,14 @@
FROM node:22-bookworm-slim
ENV HOST=0.0.0.0 \
PORT=3000 \
NITRO_HOST=0.0.0.0 \
NITRO_PORT=3000 \
NODE_ENV=production
WORKDIR /app
COPY .output ./.output
RUN chown -R node:node /app
USER node
EXPOSE 3000
CMD ["node", ".output/server/index.mjs"]
+114
View File
@@ -0,0 +1,114 @@
<template>
<div ref="root" class="option-select">
<button
type="button"
class="trigger"
:aria-expanded="open"
aria-haspopup="listbox"
@click="open = !open"
>
<span>{{ current }}</span>
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" aria-hidden="true">
<path d="m6 9 6 6 6-6" />
</svg>
</button>
<ul v-if="open" class="menu" role="listbox">
<li v-for="item in options" :key="item.value">
<button
type="button"
role="option"
:aria-selected="item.value === modelValue"
:class="{ on: item.value === modelValue }"
@click="choose(item.value)"
>
{{ item.label }}
</button>
</li>
</ul>
</div>
</template>
<script setup lang="ts">
type Option = { value: number; label: string }
const props = defineProps<{
modelValue: number | null
options: Option[]
}>()
const emit = defineEmits<{ "update:modelValue": [value: number] }>()
const open = ref(false)
const root = ref<HTMLElement | null>(null)
const current = computed(() => props.options.find((item) => item.value === props.modelValue)?.label || "请选择")
function choose(value: number) {
emit("update:modelValue", value)
open.value = false
}
function onPointerDown(event: PointerEvent) {
if (!root.value?.contains(event.target as Node)) open.value = false
}
onMounted(() => document.addEventListener("pointerdown", onPointerDown))
onBeforeUnmount(() => document.removeEventListener("pointerdown", onPointerDown))
</script>
<style scoped>
.option-select { position: relative; }
.trigger {
width: 100%;
height: 40px;
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
padding: 0 12px;
border: 1px solid #d6e4ff;
border-radius: 10px;
background: #fff;
color: #1e3a5f;
font: inherit;
font-size: 14px;
cursor: pointer;
text-align: left;
}
.trigger span {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.trigger svg { width: 16px; height: 16px; flex: none; color: #6b86a8; }
.menu {
position: absolute;
z-index: 2;
top: calc(100% + 4px);
left: 0;
right: 0;
margin: 0;
padding: 6px;
list-style: none;
max-height: 220px;
overflow: auto;
border: 1px solid #d7e3f4;
border-radius: 10px;
background: #fff;
box-shadow: 0 10px 28px rgba(30, 58, 95, 0.14);
}
.menu button {
width: 100%;
border: 0;
border-radius: 8px;
background: transparent;
color: #1e3a5f;
font: inherit;
font-size: 14px;
text-align: left;
padding: 8px 10px;
cursor: pointer;
}
.menu button:hover,
.menu button.on { background: #e8f1ff; color: #1d4ed8; }
</style>
+103
View File
@@ -0,0 +1,103 @@
const TOKEN_KEY = "gsfdc_agent_token"
type AgentProfile = {
username: string
displayName: string
canManage?: boolean
}
export function useAgentAuth() {
const token = useState<string | null>("agent-token", () => null)
const username = useState<string | null>("agent-username", () => null)
const displayName = useState<string | null>("agent-display-name", () => null)
const ready = useState("agent-auth-ready", () => false)
const { get } = useSiteApi()
function readStored() {
if (!import.meta.client) return null
return window.localStorage.getItem(TOKEN_KEY)
}
function persist(next: string | null) {
if (!import.meta.client) return
if (next) window.localStorage.setItem(TOKEN_KEY, next)
else window.localStorage.removeItem(TOKEN_KEY)
}
async function refreshProfile() {
if (!token.value) {
username.value = null
displayName.value = null
return null
}
try {
const me = await get<AgentProfile>("/auth/agent/me", token.value)
username.value = me.username
displayName.value = me.displayName || me.username
return me
} catch (exc: any) {
const status = Number(exc?.statusCode || exc?.response?.status || 0)
if (status === 401 || status === 403) {
token.value = null
username.value = null
displayName.value = null
persist(null)
}
return null
}
}
function takeHashToken() {
if (!import.meta.client) return ""
const hash = new URLSearchParams(window.location.hash.replace(/^#/, ""))
const handed = hash.get("agentToken") || ""
if (!handed) return ""
hash.delete("agentToken")
const next = hash.toString()
const url = `${window.location.pathname}${window.location.search}${next ? `#${next}` : ""}`
window.history.replaceState(null, "", url)
return handed
}
async function ensure() {
if (!import.meta.client) return
const handed = takeHashToken()
if (handed) {
await setSession(handed)
return
}
if (ready.value) return
const stored = readStored()
token.value = stored
if (stored) await refreshProfile()
ready.value = true
}
async function setSession(accessToken: string) {
token.value = accessToken
persist(accessToken)
ready.value = true
await refreshProfile()
}
function clearSession() {
token.value = null
username.value = null
displayName.value = null
persist(null)
}
const isAuthed = computed(() => Boolean(token.value))
return {
token,
username,
displayName,
ready,
isAuthed,
ensure,
setSession,
clearSession,
refreshProfile,
}
}
+1 -1
View File
@@ -1,5 +1,5 @@
export const EXPERT_SECTIONS = [
{ key: "assistant", label: "智能估价", path: "/expert/assistant" },
{ key: "assistant", label: "智能估价智能体", path: "/expert/assistant" },
{ key: "guides", label: "专项估价服务", path: "/expert/guides" },
{ key: "qa", label: "专家答疑", path: "/expert/qa" },
] as const
+19 -4
View File
@@ -1,17 +1,24 @@
type FetchOpts = {
method?: "GET" | "POST" | "PUT" | "DELETE"
method?: "GET" | "POST" | "PUT" | "PATCH" | "DELETE"
body?: any
token?: string | null
formData?: FormData
}
export function useSiteApi() {
export function siteApiBase() {
const config = useRuntimeConfig()
const internal = import.meta.server ? String(config.apiBase || "").trim() : ""
const chosen = internal || String(config.public.apiBase || "")
return chosen.replace(/\/$/, "")
}
export function useSiteApi() {
const base = siteApiBase()
async function request<T>(path: string, opts: FetchOpts = {}) {
const headers: Record<string, string> = {}
if (opts.token) headers.Authorization = `Bearer ${opts.token}`
return $fetch<T>(`${config.public.apiBase}${path}`, {
return $fetch<T>(`${base}${path}`, {
method: opts.method || (opts.body || opts.formData ? "POST" : "GET"),
body: opts.formData || opts.body,
headers,
@@ -30,5 +37,13 @@ export function useSiteApi() {
return request<T>(path, { method: "POST", formData, token })
}
return { get, post, upload }
function patch<T>(path: string, body?: any, token?: string | null) {
return request<T>(path, { method: "PATCH", body, token })
}
function del<T>(path: string, token?: string | null) {
return request<T>(path, { method: "DELETE", token })
}
return { get, post, upload, patch, del }
}
+1 -1
View File
@@ -28,7 +28,7 @@ const { home, logoUrl, ensureChrome } = useSiteChrome()
const activeKey = computed(() => {
const path = route.path
if (path.startsWith("/expert/assistant")) return "assistant"
if (path.startsWith("/expert/assistant") || path.startsWith("/expert/agent-login")) return "assistant"
if (path.startsWith("/expert/qa") || path.startsWith("/expert/login") || path.startsWith("/expert/register") || path.startsWith("/expert/reset")) {
return "qa"
}
+80
View File
@@ -0,0 +1,80 @@
<template>
<div class="auth-page">
<div class="auth-box">
<h2 class="page-title">智能估价登录</h2>
<label>邮箱或账号</label>
<input v-model="username" type="text" placeholder="邮箱或账号" autocomplete="username">
<label>密码</label>
<input v-model="password" type="password" placeholder="输入密码" autocomplete="current-password">
<div class="actions">
<button type="button" class="btn" :disabled="busy" @click="submit">登录</button>
</div>
<p v-if="error" class="error">{{ error }}</p>
</div>
</div>
</template>
<script setup lang="ts">
const route = useRoute()
const router = useRouter()
const { post } = useSiteApi()
const { setSession, ensure, isAuthed } = useAgentAuth()
const username = ref("")
const password = ref("")
const busy = ref(false)
const error = ref("")
const redirect = computed(() => String(route.query.redirect || "/expert/assistant"))
await ensure()
if (isAuthed.value) {
await navigateTo(redirect.value, { replace: true })
}
async function submit() {
error.value = ""
busy.value = true
try {
const body = await post<{ accessToken: string }>("/auth/agent-login", {
username: username.value.trim(),
password: password.value,
})
await setSession(body.accessToken)
await router.replace(redirect.value)
} catch (exc: any) {
error.value = exc?.data?.detail || exc?.message || "登录失败"
} finally {
busy.value = false
}
}
</script>
<style scoped>
.auth-page {
flex: 1;
display: flex;
align-items: center;
justify-content: center;
width: 100%;
min-height: 640px;
height: min(760px, calc(100vh - 210px));
padding: 32px 24px;
box-sizing: border-box;
}
.auth-box { width: min(420px, 100%); }
.page-title { margin: 0 0 12px; font-size: 22px; font-weight: 650; letter-spacing: 0.08em; }
label { display: block; margin: 0 0 6px; font-size: 13px; color: var(--muted, #5b6b85); }
input {
width: 100%; margin: 0 0 14px; padding: 10px 12px;
border: 1px solid var(--line, #d6e4ff); border-radius: 8px;
background: var(--surface, #fff); color: var(--text, #0b1f3a); font: inherit;
}
.actions { display: flex; flex-wrap: wrap; gap: 10px; align-items: center; }
.btn {
appearance: none; border: 0; border-radius: 8px; padding: 0 16px; height: 36px;
display: inline-flex; align-items: center; justify-content: center; line-height: 1;
font: inherit; background: var(--c, #1677ff); color: #fff; cursor: pointer;
}
.btn:disabled { opacity: 0.45; cursor: not-allowed; }
.error { margin: 12px 0 0; color: #b91c1c; font-size: 13px; }
</style>
File diff suppressed because it is too large. Load diff
+165
View File
@@ -0,0 +1,165 @@
const ESCAPE: Record<string, string> = {
"&": "&amp;",
"<": "&lt;",
">": "&gt;",
'"': "&quot;",
}
function escapeHtml(value: string): string {
return value.replace(/[&<>"]/g, (char) => ESCAPE[char] || char)
}
function renderInline(value: string): string {
const codes: string[] = []
let text = escapeHtml(value).replace(/`([^`\n]+)`/g, (_match, code: string) => {
const token = `\u0000${codes.length}\u0000`
codes.push(code)
return token
})
text = text.replace(
/\[([^\]\n]+)\]\((https?:\/\/[^\s)]+)\)/g,
'<a href="$2" target="_blank" rel="noopener noreferrer">$1</a>',
)
text = text.replace(/\*\*([^*\n]+)\*\*/g, "<strong>$1</strong>")
text = text.replace(/__([^_\n]+)__/g, "<strong>$1</strong>")
text = text
.split(/(<[^>]+>)/)
.map((part) => (part.startsWith("<") ? part : linkBareUrls(part)))
.join("")
return text.replace(/\u0000(\d+)\u0000/g, (_match, index: string) => `<code>${codes[Number(index)]}</code>`)
}
function linkBareUrls(value: string): string {
return value.replace(/https?:\/\/[^\s<]+/g, (url) => {
const clean = url.replace(/[.,;:!?)]+$/, "")
const tail = url.slice(clean.length)
return `<a href="${clean}" target="_blank" rel="noopener noreferrer">${clean}</a>${tail}`
})
}
function splitCells(line: string): string[] {
let text = line.trim()
if (text.startsWith("|")) text = text.slice(1)
if (text.endsWith("|")) text = text.slice(0, -1)
const cells: string[] = []
let current = ""
for (let index = 0; index < text.length; index += 1) {
const char = text[index]
if (char === "\\" && text[index + 1] === "|") {
current += "|"
index += 1
continue
}
if (char === "|") {
cells.push(current.trim())
current = ""
continue
}
current += char
}
cells.push(current.trim())
return cells
}
function isSeparatorRow(line: string): boolean {
if (!line.includes("|")) return false
const cells = splitCells(line)
return cells.length > 1 && cells.every((cell) => /^:?-+:?$/.test(cell))
}
function isTableStart(lines: string[], index: number): boolean {
const line = lines[index]?.trim() || ""
const next = lines[index + 1]?.trim() || ""
return line.includes("|") && isSeparatorRow(next)
}
function renderTable(header: string[], rows: string[][]): string {
const width = Math.max(header.length, ...rows.map((row) => row.length), 1)
const cells = (row: string[], tag: "th" | "td") => {
const padded = row.concat(Array(Math.max(0, width - row.length)).fill(""))
return padded.slice(0, width).map((cell) => `<${tag}>${renderInline(cell)}</${tag}>`).join("")
}
const body = rows.map((row) => `<tr>${cells(row, "td")}</tr>`).join("")
return `<div class="table-wrap"><table><thead><tr>${cells(header, "th")}</tr></thead><tbody>${body}</tbody></table></div>`
}
function isList(line: string): "ul" | "ol" | "" {
if (/^[-*]\s+\S/.test(line)) return "ul"
if (/^\d+\.\s+\S/.test(line)) return "ol"
return ""
}
export function renderAnswerMarkdown(source: string): string {
const lines = source.replace(/\r\n/g, "\n").split("\n")
const blocks: string[] = []
let index = 0
while (index < lines.length) {
const raw = lines[index]
const line = raw.trim()
if (!line) {
index += 1
continue
}
if (line.startsWith("```")) {
const body: string[] = []
index += 1
while (index < lines.length && !lines[index].trim().startsWith("```")) {
body.push(escapeHtml(lines[index]))
index += 1
}
if (index < lines.length) index += 1
blocks.push(`<pre><code>${body.join("\n")}</code></pre>`)
continue
}
const heading = /^(#{1,4})\s+(.+)$/.exec(line)
if (heading) {
const level = heading[1].length
blocks.push(`<h${level}>${renderInline(heading[2])}</h${level}>`)
index += 1
continue
}
if (isTableStart(lines, index)) {
const header = splitCells(lines[index])
index += 2
const rows: string[][] = []
while (index < lines.length && lines[index].trim().includes("|") && !isSeparatorRow(lines[index].trim())) {
rows.push(splitCells(lines[index]))
index += 1
}
blocks.push(renderTable(header, rows))
continue
}
const listKind = isList(line)
if (listKind) {
const items: string[] = []
let start = 1
while (index < lines.length) {
const current = lines[index].trim()
if (!current) {
index += 1
const upcoming = lines[index]?.trim() || ""
if (isList(upcoming) !== listKind) break
continue
}
if (isList(current) !== listKind) break
if (listKind === "ol" && items.length === 0) start = Number(/^(\d+)\./.exec(current)?.[1] || "1")
const body = current.replace(listKind === "ol" ? /^\d+\.\s+/ : /^[-*]\s+/, "")
items.push(`<li>${renderInline(body)}</li>`)
index += 1
}
const startAttr = listKind === "ol" && start !== 1 ? ` start="${start}"` : ""
blocks.push(`<${listKind}${startAttr}>${items.join("")}</${listKind}>`)
continue
}
const paragraph = [renderInline(line)]
index += 1
while (index < lines.length) {
const current = lines[index].trim()
if (!current || current.startsWith("```") || /^(#{1,4})\s+/.test(current) || isList(current) || isTableStart(lines, index)) break
paragraph.push(renderInline(current))
index += 1
}
blocks.push(`<p>${paragraph.join("<br>")}</p>`)
}
return blocks.join("")
}
+1
View File
@@ -5,6 +5,7 @@ export default defineNuxtConfig({
css: ["~/assets/themes.css"],
components: [{ path: "~/components", pathPrefix: false }],
runtimeConfig: {
apiBase: "",
public: {
apiBase: "http://127.0.0.1:18000/api/site",
payloadEncrypt: false,
Binary file not shown.

After

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.4 KiB

+9
View File
@@ -0,0 +1,9 @@
.venv
**/__pycache__
**/*.pyc
.pytest_cache
tests
scripts
.env
.git
*.md
+11
View File
@@ -25,6 +25,13 @@ MINIO_SECRET_KEY=
MINIO_BUCKET_PUBLIC=gsfdc-public
MINIO_BUCKET_PRIVATE=gsfdc-private
MINIO_SECURE=false
# 私有附件签名链接使用的对外主机,不含路径。本地留空。
MINIO_PUBLIC_ENDPOINT=
MINIO_PUBLIC_SECURE=true
# 生产放在 Nginx 后时设为 true,本地保持 false。
TRUST_PROXY=false
# 生产关闭接口文档。
EXPOSE_DOCS=true
# MINIO_BASE_URL:公开图片/附件对外访问基址(含公开桶路径)。
# 门户与管理端接口返回的 imageUrl、附件 url 都基于此项拼接,不跟站点主域名走。
# 本地可直连 MinIO;生产填独立资源域名,例如 https://static.example.com(反代到公开桶)。
@@ -54,3 +61,7 @@ DIFY_PUBLIC_URL=http://127.0.0.1:13080
DIFY_SSO_SECRET=
DIFY_SSO_EMAIL_DOMAIN=gsrea.local
DIFY_SSO_TTL_SEC=90
# 估价智能体的 Dify 应用 API Key,只放服务端。多个管理员邮箱用逗号分隔。
DIFY_API_BASE=http://127.0.0.1:13080/v1
DIFY_VALUATION_API_KEY=
VALUATION_ADMIN_EMAILS=
+24
View File
@@ -0,0 +1,24 @@
FROM python:3.12-slim-bookworm
ENV PYTHONDONTWRITEBYTECODE=1 \
PYTHONUNBUFFERED=1 \
PIP_DISABLE_PIP_VERSION_CHECK=1
WORKDIR /app
RUN apt-get update \
&& apt-get install -y --no-install-recommends ca-certificates adduser \
&& rm -rf /var/lib/apt/lists/* \
&& adduser --disabled-password --gecos "" --uid 10001 app
COPY requirements.txt .
RUN pip install --no-cache-dir -i https://mirrors.aliyun.com/pypi/simple/ -r requirements.txt \
|| pip install --no-cache-dir -r requirements.txt
COPY docker-entrypoint.sh /entrypoint.sh
COPY app ./app
RUN chmod 755 /entrypoint.sh && chown -R app:app /app
USER app
EXPOSE 8000
ENTRYPOINT ["/entrypoint.sh"]
+99
View File
@@ -0,0 +1,99 @@
from fastapi import APIRouter, Depends, HTTPException, Query, status
from pydantic import BaseModel
from sqlalchemy.orm import Session
from app.core.deps import require_staff
from app.db import get_db
from app.models.agent_user import (
create_agent_user,
delete_agent_record,
get_agent_record,
query_agent_users,
update_agent_record,
)
from app.services.password import hash_password, validate_password
router = APIRouter(dependencies=[Depends(require_staff)])
class AgentUserCreate(BaseModel):
username: str
displayName: str
password: str
status: str = "active"
class AgentUserUpdate(BaseModel):
displayName: str
status: str
password: str | None = None
def _password_hash(password: str | None, *, required: bool) -> str | None:
text_value = (password or "").strip()
if not text_value:
if required:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="请填写密码")
return None
validate_password(text_value)
return hash_password(text_value)
@router.get("/agent-users")
def list_agent_users(
current: int = Query(1),
size: int = Query(20),
username: str | None = None,
db: Session = Depends(get_db),
) -> dict:
return query_agent_users(db, current=current, size=size, username=username)
@router.post("/agent-users", status_code=status.HTTP_201_CREATED)
def add_agent_user(body: AgentUserCreate, db: Session = Depends(get_db)) -> dict:
password_hash = _password_hash(body.password, required=True)
try:
return create_agent_user(
db,
username=body.username,
password_hash=password_hash or "",
display_name=body.displayName,
status=body.status,
)
except ValueError as exc:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc)) from exc
@router.get("/agent-users/{user_key}")
def read_agent_user(user_key: str, db: Session = Depends(get_db)) -> dict:
try:
return get_agent_record(db, user_key)
except LookupError as exc:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)) from exc
@router.put("/agent-users/{user_key}")
def write_agent_user(user_key: str, body: AgentUserUpdate, db: Session = Depends(get_db)) -> dict:
try:
return update_agent_record(
db,
user_key,
display_name=body.displayName,
status=body.status,
password_hash=_password_hash(body.password, required=False),
)
except LookupError as exc:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)) from exc
except ValueError as exc:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc)) from exc
@router.delete("/agent-users/{user_key}")
def remove_agent_user(user_key: str, db: Session = Depends(get_db)) -> dict:
try:
delete_agent_record(db, user_key)
except LookupError as exc:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)) from exc
except ValueError as exc:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc)) from exc
return {"ok": True}
+19
View File
@@ -3,7 +3,9 @@ from pydantic import BaseModel
from sqlalchemy.orm import Session
from app.core.deps import require_staff
from app.core.security import create_access_token
from app.db import get_db
from app.models.rbac import AdminUser
from app.services import rbac as rbac_service
public_router = APIRouter()
@@ -103,6 +105,23 @@ def login(body: LoginIn, request: Request, db: Session = Depends(get_db)) -> dic
return rbac_service.authenticate(db, body.username, body.password, body.captchaId, body.captchaCode)
@router.post("/auth/agent-session")
def issue_agent_session(actor_id: int = Depends(_actor_id), db: Session = Depends(get_db)) -> dict:
"""管理端已登录的用户管理账号,打开智能体市场时直接使用该账号。"""
from fastapi import HTTPException
user = db.get(AdminUser, actor_id)
if user is None or user.status != "active":
raise HTTPException(status_code=401, detail="登录已失效")
token = create_access_token(f"s:{user.id}", "agent")
return {
"accessToken": token,
"tokenType": "agent",
"username": user.username,
"displayName": user.display_name or user.username,
}
@router.post("/auth/password")
def change_password(
body: OwnPasswordIn,
+168
View File
@@ -0,0 +1,168 @@
from fastapi import APIRouter, Depends, HTTPException, Query, status
from pydantic import BaseModel
from sqlalchemy.orm import Session
from app.core.deps import require_staff
from app.db import get_db
from app.models.agent_user import (
linked_admin_user,
serialize_staff_agent,
set_admin_agent_enabled,
admin_agent_enabled,
)
from app.models.member import delete_member, query_members, serialize_member, update_member
from app.models.member import get_member_by_id
from app.models.rbac import AdminUser
from app.services.email_code import is_valid_email, normalize_email
from app.services.password import hash_password, validate_password
router = APIRouter(dependencies=[Depends(require_staff)])
class SiteMemberUpdate(BaseModel):
email: str
status: str
password: str | None = None
agentEnabled: bool | None = None
displayName: str | None = None
def _missing() -> None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="用户不存在")
def _builtin_key(user_id: int) -> str:
return f"staff-{user_id}"
def _builtin_record(db: Session) -> dict | None:
admin = linked_admin_user(db)
if admin is None:
return None
record = serialize_staff_agent(admin)
record["email"] = admin.username
record["builtin"] = True
record["agentEnabled"] = admin_agent_enabled(db)
record["displayName"] = admin.display_name
record["privacyAcceptedAt"] = None
return record
def _matches_builtin(record: dict, keyword: str) -> bool:
if not keyword:
return True
folded = keyword.casefold()
return folded in str(record.get("email") or "").casefold() or folded in str(record.get("displayName") or "").casefold()
@router.get("/site-members")
def list_site_members(
current: int = Query(1),
size: int = Query(20),
email: str | None = None,
db: Session = Depends(get_db),
) -> dict:
keyword = (email or "").strip()
builtin = _builtin_record(db)
include_builtin = builtin is not None and _matches_builtin(builtin, keyword)
if not include_builtin:
return query_members(db, current=current, size=size, email=email)
page_size = size if size > 0 else 20
if current <= 1:
page = query_members(db, current=1, size=page_size, email=email, offset=0, limit=max(page_size - 1, 0))
records = [builtin, *page["records"]]
else:
page = query_members(
db,
current=current,
size=page_size,
email=email,
offset=(current - 1) * page_size - 1,
limit=page_size,
)
records = page["records"]
return {**page, "records": records, "current": current, "size": page_size, "total": int(page["total"]) + 1}
@router.get("/site-members/{member_key}")
def read_site_member(member_key: str, db: Session = Depends(get_db)) -> dict:
if member_key.startswith("staff-"):
builtin = _builtin_record(db)
if builtin is None or builtin["id"] != member_key:
_missing()
return builtin
row = get_member_by_id(db, int(member_key))
if row is None:
_missing()
return serialize_member(row)
@router.put("/site-members/{member_key}")
def write_site_member(member_key: str, body: SiteMemberUpdate, db: Session = Depends(get_db)) -> dict:
if member_key.startswith("staff-"):
return _write_builtin(member_key, body, db)
email = normalize_email(body.email)
if not is_valid_email(email):
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="邮箱格式不正确")
password = (body.password or "").strip()
password_hash = None
if password:
validate_password(password)
password_hash = hash_password(password)
try:
row = update_member(
db,
int(member_key),
email=email,
status=(body.status or "").strip(),
password_hash=password_hash,
agent_enabled=body.agentEnabled,
)
except LookupError as exc:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)) from exc
except ValueError as exc:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc)) from exc
return serialize_member(row)
def _write_builtin(member_key: str, body: SiteMemberUpdate, db: Session) -> dict:
from datetime import datetime, timezone
builtin = _builtin_record(db)
if builtin is None or builtin["id"] != member_key:
_missing()
admin = linked_admin_user(db)
if not isinstance(admin, AdminUser):
_missing()
display_name = (body.displayName or admin.display_name or "").strip()
if not display_name:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="请填写姓名")
status_value = (body.status or "").strip()
if status_value not in {"active", "disabled", "cancelled"}:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="状态不正确")
password = (body.password or "").strip()
if password:
validate_password(password)
admin.password_hash = hash_password(password)
admin.display_name = display_name
admin.status = status_value
admin.updated_at = datetime.now(timezone.utc)
if body.agentEnabled is not None:
set_admin_agent_enabled(db, body.agentEnabled)
db.commit()
db.refresh(admin)
saved = _builtin_record(db)
if saved is None:
_missing()
return saved
@router.delete("/site-members/{member_key}")
def remove_site_member(member_key: str, db: Session = Depends(get_db)) -> dict:
if member_key.startswith("staff-"):
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="该账号与用户管理中的 admin 是同一账号,不能在这里删除")
try:
delete_member(db, int(member_key))
except LookupError as exc:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)) from exc
return {"ok": True}
+4
View File
@@ -15,6 +15,7 @@ from app.api.admin.dify_sso import router as admin_dify_sso_router
from app.api.admin.routes import router as admin_router
from app.api.admin.security import public_router as security_public_router
from app.api.admin.security import router as security_router
from app.api.admin.site_members import router as admin_site_members_router
from app.api.site.about import router as site_about_router
from app.api.site.discipline import router as site_discipline_router
from app.api.site.edu import router as site_edu_router
@@ -25,6 +26,7 @@ from app.api.site.home import router as site_home_router
from app.api.site.public import router as site_public_router
from app.api.site.reports import router as site_reports_router
from app.api.site.settings import router as site_settings_router
from app.api.site.valuation import router as site_valuation_router
api_router = APIRouter()
api_router.include_router(site_public_router, prefix="/api/site")
@@ -37,6 +39,7 @@ api_router.include_router(site_edu_router, prefix="/api/site")
api_router.include_router(site_legal_router, prefix="/api/site")
api_router.include_router(site_auth_router, prefix="/api/site")
api_router.include_router(member_router, prefix="/api/site/member")
api_router.include_router(site_valuation_router, prefix="/api/site/member/valuation")
api_router.include_router(rbac_public_router, prefix="/api/admin")
api_router.include_router(security_public_router, prefix="/api/admin")
api_router.include_router(rbac_router, prefix="/api/admin")
@@ -51,4 +54,5 @@ api_router.include_router(admin_legal_router, prefix="/api/admin")
api_router.include_router(admin_expert_router, prefix="/api/admin")
api_router.include_router(admin_uploaded_cases_router, prefix="/api/admin")
api_router.include_router(admin_dify_sso_router, prefix="/api/admin")
api_router.include_router(admin_site_members_router, prefix="/api/admin")
api_router.include_router(admin_router, prefix="/api/admin")
+57
View File
@@ -4,9 +4,12 @@ from fastapi import APIRouter, Depends, HTTPException, status
from pydantic import BaseModel
from sqlalchemy.orm import Session
from app.core.deps import require_agent
from app.core.security import create_access_token
from app.db import get_db
from app.models.agent_user import find_login_account, load_agent_actor
from app.models.member import create_member, get_member_by_email, set_member_password
from app.services.login_guard import clear_failures, is_currently_locked, record_failure
from app.services.email_code import (
consume_email_code,
is_valid_email,
@@ -36,6 +39,11 @@ class LoginRequest(BaseModel):
code: str | None = None
class AgentLoginRequest(BaseModel):
username: str
password: str
class ResetPasswordRequest(BaseModel):
email: str
code: str
@@ -108,6 +116,55 @@ def login(body: LoginRequest, db: Session = Depends(get_db)) -> dict:
return {"accessToken": token, "tokenType": "member", "email": member.email}
AGENT_LOGIN_FAILURE = "用户名或密码错误"
def _reject_agent_login(db: Session, user, *, record: bool) -> None:
if record and user is not None:
record_failure(db, user)
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=AGENT_LOGIN_FAILURE)
@router.post("/auth/agent-login")
def agent_login(body: AgentLoginRequest, db: Session = Depends(get_db)) -> dict:
found = find_login_account(db, body.username)
if found is None:
_reject_agent_login(db, None, record=False)
kind, user, allowed = found
if is_currently_locked(user):
_reject_agent_login(db, user, record=False)
if not verify_password(body.password, user.password_hash):
_reject_agent_login(db, user, record=True)
if user.status != "active":
_reject_agent_login(db, user, record=True)
if not allowed:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="该账号未开通智能体登录")
clear_failures(db, user)
subject = f"s:{user.id}" if kind == "staff" else f"m:{user.id}"
username = user.username if kind == "staff" else user.email
display_name = user.display_name if kind == "staff" else user.email.split("@", 1)[0]
token = create_access_token(subject, "agent")
return {
"accessToken": token,
"tokenType": "agent",
"username": username,
"displayName": display_name or username,
}
@router.get("/auth/agent/me")
def agent_me(principal: dict = Depends(require_agent), db: Session = Depends(get_db)) -> dict:
try:
actor = load_agent_actor(db, str(principal.get("sub") or ""))
except LookupError as exc:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="登录已失效") from exc
return {
"username": actor.username,
"displayName": actor.display_name,
"canManage": actor.can_manage,
}
@router.post("/auth/reset-password")
def reset_password(body: ResetPasswordRequest, db: Session = Depends(get_db)) -> dict:
email = normalize_email(body.email)
+640
View File
@@ -0,0 +1,640 @@
import json
from urllib.parse import quote
from fastapi import APIRouter, Depends, File, Form, HTTPException, UploadFile, status
from fastapi.responses import Response, StreamingResponse
from pydantic import BaseModel, Field
from sqlalchemy.orm import Session
from app.core.deps import require_agent
from app.db import get_db
from app.models.agent_user import AgentActor, load_agent_actor
from app.models.content import read_upload_limit
from app.models.valuation import ValuationFile, ValuationMessage, _now
from app.services.dify_chat import DifyChatError, DifyNotConfigured, cited_documents, iter_dify_chat, upload_dify_file
from app.services.storage import make_object_key, read_object, remove_stored_object, safe_filename, upload_object
from app.services.valuation import (
add_suggestion,
add_user_message,
create_session,
delete_session,
delete_suggestion,
get_owned_session,
list_messages,
list_sessions,
list_suggestions,
add_template,
delete_template,
get_template,
list_templates,
template_format,
owned_files,
bind_files,
rename_session,
save_assistant_message,
set_template_enabled,
update_suggestion,
)
from app.services.valuation_context import (
ALLOWED_EXTENSIONS,
MAX_FILES,
RISK_LINE,
DRAFT_FORMATS,
build_draft_file,
draft_title,
compose_query,
peel_free_format,
draft_prompt,
ensure_answer_note,
extract_excerpt,
file_kind,
search_web,
with_risk_line,
)
router = APIRouter(dependencies=[Depends(require_agent)])
class SessionRename(BaseModel):
title: str = Field(min_length=1, max_length=40)
class ChatRequest(BaseModel):
query: str = Field(default="", max_length=2000)
fileIds: list[int] = Field(default_factory=list, max_length=MAX_FILES)
web: bool = False
class DraftRequest(BaseModel):
templateId: int | None = None
query: str = Field(default="", max_length=2000)
fileIds: list[int] = Field(default_factory=list, max_length=MAX_FILES)
web: bool = False
class TemplatePatch(BaseModel):
enabled: bool
class SuggestionWrite(BaseModel):
text: str = Field(min_length=1, max_length=200)
enabled: bool | None = None
def _actor(db: Session, principal: dict) -> AgentActor:
try:
return load_agent_actor(db, str(principal.get("sub") or ""))
except LookupError as exc:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="登录已失效") from exc
def _require_manager(db: Session, principal: dict, detail: str = "仅管理员可修改推荐问题") -> AgentActor:
actor = _actor(db, principal)
if not actor.can_manage:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=detail)
return actor
def _sse(payload: dict) -> str:
return f"data: {json.dumps(payload, ensure_ascii=False)}\n\n"
@router.get("/bootstrap")
def bootstrap(principal: dict = Depends(require_agent), db: Session = Depends(get_db)) -> dict:
actor = _actor(db, principal)
return {
"username": actor.username,
"displayName": actor.display_name,
"canManage": actor.can_manage,
"suggestions": list_suggestions(db, enabled_only=True),
"templates": list_templates(db, enabled_only=True),
}
@router.get("/sessions")
def sessions(principal: dict = Depends(require_agent), db: Session = Depends(get_db)) -> dict:
actor = _actor(db, principal)
return {"items": list_sessions(db, actor.key)}
@router.post("/sessions", status_code=status.HTTP_201_CREATED)
def new_session(principal: dict = Depends(require_agent), db: Session = Depends(get_db)) -> dict:
actor = _actor(db, principal)
return create_session(db, actor.key)
@router.patch("/sessions/{session_id}")
def patch_session(
session_id: int,
body: SessionRename,
principal: dict = Depends(require_agent),
db: Session = Depends(get_db),
) -> dict:
actor = _actor(db, principal)
updated = rename_session(db, actor.key, session_id, body.title)
if updated is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="会话不存在")
return updated
@router.delete("/sessions/{session_id}", status_code=status.HTTP_204_NO_CONTENT)
def remove_session(
session_id: int,
principal: dict = Depends(require_agent),
db: Session = Depends(get_db),
) -> None:
actor = _actor(db, principal)
if not delete_session(db, actor.key, session_id):
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="会话不存在")
@router.get("/sessions/{session_id}/messages")
def messages(
session_id: int,
principal: dict = Depends(require_agent),
db: Session = Depends(get_db),
) -> dict:
actor = _actor(db, principal)
items = list_messages(db, actor.key, session_id)
if items is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="会话不存在")
return {"items": items}
def _read_limited(upload: UploadFile, limit: int) -> bytes:
chunks = bytearray()
while True:
piece = upload.file.read(65536)
if not piece:
break
if len(chunks) + len(piece) > limit:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="文件超过大小上限")
chunks.extend(piece)
return bytes(chunks)
@router.post("/files", status_code=status.HTTP_201_CREATED)
def upload_chat_file(
file: UploadFile = File(...),
principal: dict = Depends(require_agent),
db: Session = Depends(get_db),
) -> dict:
actor = _actor(db, principal)
filename = safe_filename(file.filename or "")
extension = filename.rsplit(".", 1)[-1].lower() if "." in filename else ""
if extension not in ALLOWED_EXTENSIONS:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="不支持该文件类型")
limit = read_upload_limit(db) or 10 * 1024 * 1024
data = _read_limited(file, limit)
if not data:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="文件是空的")
content_type = (file.content_type or "application/octet-stream").split(";", 1)[0].strip()[:128]
object_key = make_object_key(filename)
upload_object("private", object_key, data, content_type)
row = ValuationFile(
member_id=0,
owner_key=actor.key,
filename=filename,
extension=extension,
content_type=content_type,
size=len(data),
object_key=object_key,
created_at=_now(),
)
db.add(row)
db.commit()
db.refresh(row)
return {"id": row.id, "name": row.filename, "size": row.size}
@router.post("/sessions/{session_id}/messages")
def ask(
session_id: int,
body: ChatRequest,
principal: dict = Depends(require_agent),
db: Session = Depends(get_db),
):
actor = _actor(db, principal)
session = get_owned_session(db, actor.key, session_id)
if session is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="会话不存在")
query = body.query.strip()
files = owned_files(db, actor.key, body.fileIds)
if files is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="附件不存在")
if not query and not files:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="请输入问题或上传附件")
file_names = [item.filename for item in files]
snippets = search_web(query) if body.web and query else []
add_user_message(db, session, query or "请结合附件说明要点。", attachments=file_names, web=body.web)
bind_files(db, files, session.id)
conversation_id = session.dify_conversation_id
owner = actor.key
owned_id = session.id
user_key = owner
dify_files = []
excerpts: list[tuple[str, str]] = []
try:
for item in files:
content = read_object("private", item.object_key)
excerpts.append((item.filename, extract_excerpt(item.extension, content)))
uploaded_id = upload_dify_file(
filename=item.filename,
content=content,
content_type=item.content_type,
user=user_key,
)
dify_files.append(
{
"type": file_kind(item.extension),
"transfer_method": "local_file",
"upload_file_id": uploaded_id,
}
)
except (DifyNotConfigured, DifyChatError) as exc:
raise HTTPException(status_code=status.HTTP_502_BAD_GATEWAY, detail=str(exc)) from exc
prompt = compose_query(
query,
file_names=file_names,
web=body.web,
web_snippets=snippets,
file_excerpts=excerpts,
)
def generate():
answer: list[str] = []
thought = ""
sources: list[dict[str, str]] = []
retrieved: list[str] = []
next_conversation = conversation_id
error = ""
try:
for event in iter_dify_chat(
query=prompt,
conversation_id=conversation_id,
user=user_key,
files=dify_files,
):
if event["type"] == "delta":
answer.append(event["text"])
elif event["type"] == "replace":
answer = [event["text"]]
elif event["type"] == "thought":
thought = event["text"]
elif event["type"] == "sources":
retrieved = [str(name) for name in event.get("documents") or [] if str(name).strip()]
sources = cited_documents(file_names, retrieved)
if not sources:
continue
event = {"type": "sources", "documents": sources}
elif event["type"] == "done":
next_conversation = event.get("conversationId") or next_conversation
yield _sse(event)
except (DifyNotConfigured, DifyChatError) as exc:
error = str(exc)
yield _sse({"type": "error", "message": error})
if file_names and not any(item["kind"] == "attachment" for item in sources):
sources = cited_documents(file_names, retrieved)
if sources:
yield _sse({"type": "sources", "documents": sources})
visible = "".join(answer).strip()
fallback = f"暂时无法回答。{error}" if error else "知识库未返回内容。"
noted = ensure_answer_note(visible or fallback)
if not visible:
yield _sse({"type": "delta", "text": noted})
elif noted.startswith(visible):
suffix = noted[len(visible) :]
if suffix:
yield _sse({"type": "delta", "text": suffix})
elif noted != visible:
yield _sse({"type": "replace", "text": noted})
text = noted
try:
owned = get_owned_session(db, owner, owned_id)
if owned is not None:
save_assistant_message(
db,
owned,
content=text,
thought=thought,
conversation_id=next_conversation,
sources=sources,
)
except Exception:
db.rollback()
yield _sse({"type": "error", "message": "回答已生成,但没能保存,请稍后重试"})
return StreamingResponse(generate(), media_type="text/event-stream")
@router.get("/suggestions")
def admin_suggestions(principal: dict = Depends(require_agent), db: Session = Depends(get_db)) -> dict:
_require_manager(db, principal)
return {"items": list_suggestions(db, enabled_only=False)}
@router.post("/suggestions", status_code=status.HTTP_201_CREATED)
def create_suggestion(
body: SuggestionWrite,
principal: dict = Depends(require_agent),
db: Session = Depends(get_db),
) -> dict:
_require_manager(db, principal)
return add_suggestion(db, body.text)
@router.patch("/suggestions/{suggestion_id}")
def patch_suggestion(
suggestion_id: int,
body: SuggestionWrite,
principal: dict = Depends(require_agent),
db: Session = Depends(get_db),
) -> dict:
_require_manager(db, principal)
updated = update_suggestion(db, suggestion_id, text=body.text, enabled=body.enabled)
if updated is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="推荐问题不存在")
return updated
@router.delete("/suggestions/{suggestion_id}", status_code=status.HTTP_204_NO_CONTENT)
def remove_suggestion(
suggestion_id: int,
principal: dict = Depends(require_agent),
db: Session = Depends(get_db),
) -> None:
_require_manager(db, principal)
if not delete_suggestion(db, suggestion_id):
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="推荐问题不存在")
def _file_excerpts(files, user_key: str) -> tuple[list[tuple[str, str]], list[dict]]:
excerpts: list[tuple[str, str]] = []
dify_files = []
for item in files:
content = read_object("private", item.object_key)
excerpts.append((item.filename, extract_excerpt(item.extension, content)))
uploaded_id = upload_dify_file(
filename=item.filename,
content=content,
content_type=item.content_type,
user=user_key,
)
dify_files.append(
{
"type": file_kind(item.extension),
"transfer_method": "local_file",
"upload_file_id": uploaded_id,
}
)
return excerpts, dify_files
@router.get("/templates/manage")
def manage_templates(principal: dict = Depends(require_agent), db: Session = Depends(get_db)) -> dict:
_require_manager(db, principal, "仅管理员可修改模版")
return {"items": list_templates(db, enabled_only=False)}
@router.post("/templates", status_code=status.HTTP_201_CREATED)
def upload_template(
name: str = Form(...),
file: UploadFile = File(...),
principal: dict = Depends(require_agent),
db: Session = Depends(get_db),
) -> dict:
_require_manager(db, principal, "仅管理员可修改模版")
clean_name = name.strip()
if not clean_name:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="请填写模版名称")
filename = safe_filename(file.filename or "")
extension = filename.rsplit(".", 1)[-1].lower() if "." in filename else ""
content_types = {
"docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
"pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation",
}
if extension not in content_types:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="模版只接受 docx 或 pptx")
data = _read_limited(file, read_upload_limit(db) or 10 * 1024 * 1024)
outline = extract_excerpt(extension, data, limit=8000)
if len(outline) < 4:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="模版里没有可用正文")
object_key = make_object_key(filename)
upload_object("private", object_key, data, content_types[extension])
return add_template(db, name=clean_name, filename=filename, object_key=object_key, outline=outline)
@router.patch("/templates/{template_id}")
def patch_template(
template_id: int,
body: TemplatePatch,
principal: dict = Depends(require_agent),
db: Session = Depends(get_db),
) -> dict:
_require_manager(db, principal, "仅管理员可修改模版")
updated = set_template_enabled(db, template_id, body.enabled)
if updated is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="模版不存在")
return updated
@router.delete("/templates/{template_id}", status_code=status.HTTP_204_NO_CONTENT)
def remove_template(
template_id: int,
principal: dict = Depends(require_agent),
db: Session = Depends(get_db),
) -> None:
_require_manager(db, principal, "仅管理员可修改模版")
row = delete_template(db, template_id)
if row is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="模版不存在")
if row.object_key:
try:
remove_stored_object("private", row.object_key)
except Exception:
pass
@router.post("/sessions/{session_id}/drafts")
def draft(
session_id: int,
body: DraftRequest,
principal: dict = Depends(require_agent),
db: Session = Depends(get_db),
):
actor = _actor(db, principal)
session = get_owned_session(db, actor.key, session_id)
if session is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="会话不存在")
template = get_template(db, body.templateId, enabled_only=True) if body.templateId else None
if body.templateId and template is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="模版不存在或未启用")
files = owned_files(db, actor.key, body.fileIds)
if files is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="附件不存在")
query = body.query.strip()
request_text = query or "请根据知识库检索结果生成文档。"
user_key = actor.key
try:
excerpts, dify_files = _file_excerpts(files, user_key)
except (DifyNotConfigured, DifyChatError) as exc:
raise HTTPException(status_code=status.HTTP_502_BAD_GATEWAY, detail=str(exc)) from exc
snippets = search_web(query) if body.web and query else []
draft_format = template_format(template.filename) if template else ""
draft_name = draft_title(template.name if template else "", query)
prompt = draft_prompt(
template_name=template.name if template else "",
outline=template.outline if template else "",
question=query,
file_excerpts=excerpts,
web=body.web,
web_snippets=snippets,
template_format=draft_format,
)
fresh = session.title == "新会话"
add_user_message(
db,
session,
request_text,
attachments=[item.filename for item in files],
web=body.web,
)
bind_files(db, files, session.id)
if fresh:
session.title = request_text[:22]
db.commit()
conversation_id = session.dify_conversation_id or ""
owner = actor.key
owned_id = session.id
template_name = template.name if template else ""
def generate():
answer: list[str] = []
if template_name and draft_format == "pptx":
thought = f"1. 按本次要求检索知识库\n2. 载入 PPT 模版「{template_name}」\n3. 按幻灯片顺序生成,并保留风险提示"
elif template_name:
thought = f"1. 按本次要求检索知识库\n2. 载入模版「{template_name}」\n3. 按模版章节生成,并保留风险提示"
else:
thought = "1. 按本次要求检索知识库\n2. 未指定模版,按本次要求决定成品类型\n3. 保留风险提示"
sources: list[dict[str, str]] = []
retrieved: list[str] = []
error = ""
resolved = draft_format
held = ""
yield _sse({"type": "thought", "text": thought})
def reveal(piece: str, *, replace: bool) -> str | None:
nonlocal resolved, held
if resolved:
return piece
held = piece if replace else held + piece
chosen, visible = peel_free_format(held, finished=False, question=query)
if not chosen:
return None
resolved = chosen
held = ""
return visible
try:
for event in iter_dify_chat(
query=prompt,
conversation_id="",
user=user_key,
files=dify_files,
):
if event["type"] == "delta":
visible = reveal(event["text"], replace=False)
if visible:
answer.append(visible)
event = {"type": "delta", "text": visible}
else:
continue
elif event["type"] == "replace":
visible = reveal(event["text"], replace=True)
if visible is None:
answer = []
continue
answer = [visible]
event = {"type": "replace", "text": visible}
elif event["type"] == "thought":
thought = f"{thought}\n{event['text']}"
event = {"type": "thought", "text": thought}
elif event["type"] == "sources":
retrieved = [str(name) for name in event.get("documents") or [] if str(name).strip()]
sources = cited_documents([item.filename for item in files], retrieved)
if not sources:
continue
event = {"type": "sources", "documents": sources}
elif event["type"] == "done":
event = {"type": "done"}
yield _sse(event)
except (DifyNotConfigured, DifyChatError) as exc:
error = str(exc)
yield _sse({"type": "error", "message": error})
if not resolved:
chosen, visible = peel_free_format(held, finished=True, question=query)
resolved = chosen or "docx"
if visible:
answer.append(visible)
yield _sse({"type": "delta", "text": visible})
resolved = resolved or "docx"
draft_names = [item.filename for item in files]
if draft_names and not any(item["kind"] == "attachment" for item in sources):
sources = cited_documents(draft_names, retrieved)
if sources:
yield _sse({"type": "sources", "documents": sources})
text = with_risk_line("".join(answer).strip() or (f"暂时无法成稿。{error}" if error else "知识库未返回内容。"))
if RISK_LINE not in "".join(answer):
yield _sse({"type": "delta", "text": f"\n\n{RISK_LINE}"})
try:
owned = get_owned_session(db, owner, owned_id)
message_id = 0
if owned is not None:
saved = save_assistant_message(
db,
owned,
content=text,
thought=thought,
conversation_id=conversation_id,
kind="draft",
draft_format=resolved,
draft_name=draft_name,
sources=sources,
)
message_id = saved.id
yield _sse({"type": "saved", "messageId": message_id, "kind": "draft", "draftFormat": resolved, "draftName": draft_name})
except Exception:
db.rollback()
yield _sse({"type": "error", "message": "文稿已生成,但没能保存,请稍后重试"})
return StreamingResponse(generate(), media_type="text/event-stream")
@router.get("/sessions/{session_id}/messages/{message_id}/{file_format}")
def download_draft(
session_id: int,
message_id: int,
file_format: str,
principal: dict = Depends(require_agent),
db: Session = Depends(get_db),
) -> Response:
if file_format not in DRAFT_FORMATS:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="文稿不存在")
actor = _actor(db, principal)
session = get_owned_session(db, actor.key, session_id)
row = db.get(ValuationMessage, message_id) if session is not None else None
if session is None or row is None or row.session_id != session.id or row.role != "assistant" or row.kind != "draft":
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="文稿不存在")
stored = (row.draft_format or "docx").lower()
if stored not in DRAFT_FORMATS:
stored = "docx"
if file_format != stored:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="文稿不存在")
content, media_type, _default_name = build_draft_file(stored, row.content or "")
filename = quote(f"{(row.draft_name or '').strip() or '辅助文稿'}.{stored}")
return Response(
content=content,
media_type=media_type,
headers={"Content-Disposition": f"attachment; filename*=UTF-8''{filename}"},
)
+141 -1
View File
@@ -11,6 +11,8 @@ from app.services.password import hash_password, validate_password
SUPER_CODE = "R_SUPER"
SUPER_NAME = "超级管理员"
AGENT_ADMIN_CODE = "R_AGENT_ADMIN"
AGENT_ADMIN_NAME = "智能体管理员"
PAGES = [
{
@@ -128,6 +130,98 @@ AI_AGENT_RETIRED_MENU_NAMES = (
)
def ensure_site_member_menu(db: Session) -> None:
"""把门户注册用户列表放在系统管理已有菜单的最后。已存在时不改人工排序。"""
directory = db.scalar(
select(AdminResource).where(AdminResource.parent_id.is_(None), AdminResource.name == "System")
)
if directory is None:
return
existing = _find_resource(db, directory.id, "SiteMember")
siblings = list(
db.scalars(
select(AdminResource).where(
AdminResource.parent_id == directory.id,
AdminResource.type == "menu",
)
).all()
)
sort = existing.sort if existing is not None else (max((row.sort or 0) for row in siblings) + 1 if siblings else 1)
menu = _ensure_resource(
db,
parent_id=directory.id,
resource_type="menu",
name="SiteMember",
title="门户网站注册用户",
path="/system/site-member",
component="/system/site-member",
icon="",
permission="",
sort=sort,
visible=True,
)
buttons = []
for index, (code, title) in enumerate(
(
("site-member:view", "查看"),
("site-member:edit", "编辑"),
("site-member:delete", "删除"),
),
start=1,
):
buttons.append(
_ensure_resource(
db,
parent_id=menu.id,
resource_type="button",
name=code,
title=title,
path="",
component="",
icon="",
permission=code,
sort=index,
visible=False,
)
)
role = db.scalar(select(AdminRole).where(AdminRole.code == SUPER_CODE))
if role is None:
db.flush()
return
linked = set(
db.scalars(select(AdminRoleResource.resource_id).where(AdminRoleResource.role_id == role.id)).all()
)
for resource_id in (menu.id, *(button.id for button in buttons)):
if resource_id not in linked:
db.add(AdminRoleResource(role_id=role.id, resource_id=resource_id))
db.flush()
def retire_agent_user_menu(db: Session) -> None:
"""去掉已经不用的智能体用户菜单。"""
directory = db.scalar(
select(AdminResource).where(AdminResource.parent_id.is_(None), AdminResource.name == "System")
)
if directory is None:
return
rows = list(
db.scalars(
select(AdminResource).where(
AdminResource.parent_id == directory.id,
AdminResource.name == "AgentUser",
)
).all()
)
for row in rows:
_delete_resource_tree(db, row)
db.flush()
def ensure_agent_user_menu(db: Session) -> None:
"""兼容旧调用。智能体用户菜单已撤销。"""
retire_agent_user_menu(db)
def ensure_system_menu_order(db: Session) -> None:
"""Move existing System directory to the end of the sidebar without recreating children."""
directory = db.scalar(
@@ -209,6 +303,22 @@ def ensure_ai_agent_menu(db: Session) -> None:
)
for name, title, path, icon, sort in AI_AGENT_MENUS
]
pages.insert(
0,
_ensure_resource(
db,
parent_id=directory.id,
resource_type="menu",
name="AiAgentMarket",
title="智能体市场",
path="/dify/market",
component="/dify/market",
icon="ri:store-3-line",
permission="",
sort=0,
visible=True,
),
)
soft_deleted_pages = []
for name, title, path, icon, sort in AI_AGENT_SOFT_DELETED_MENUS:
row = _ensure_resource(
@@ -227,7 +337,7 @@ def ensure_ai_agent_menu(db: Session) -> None:
_soft_delete_resource(db, row)
soft_deleted_pages.append(row)
# Collapse any child duplicates under the kept directory.
for name, *_rest in (*AI_AGENT_MENUS, *AI_AGENT_SOFT_DELETED_MENUS):
for name, *_rest in (*AI_AGENT_MENUS, *AI_AGENT_SOFT_DELETED_MENUS, ("AiAgentMarket",)):
siblings = list(
db.scalars(
select(AdminResource)
@@ -988,6 +1098,33 @@ def ensure_about_menu(db: Session) -> None:
db.flush()
def ensure_agent_admin_role(db: Session) -> None:
"""内置「智能体管理员」。第一次创建时挂到当前绑定的 admin,避免原入口立刻消失。"""
now = utcnow()
role = db.scalar(select(AdminRole).where(AdminRole.code == AGENT_ADMIN_CODE))
if role is None:
role = AdminRole(
code=AGENT_ADMIN_CODE,
name=AGENT_ADMIN_NAME,
description="可管理估价智能体的推荐问题和报告模版",
status="active",
created_at=now,
updated_at=now,
)
db.add(role)
db.flush()
else:
return
from app.models.agent_user import linked_admin_user
admin = linked_admin_user(db)
if admin is None:
return
if db.get(AdminUserRole, (admin.id, role.id)) is None:
db.add(AdminUserRole(user_id=admin.id, role_id=role.id))
db.flush()
def seed_superuser(db: Session, username: str, password: str) -> None:
username = username.strip()
if not username:
@@ -1097,7 +1234,10 @@ def seed_superuser(db: Session, username: str, password: str) -> None:
db.flush()
ensure_home_menu(db)
ensure_ai_agent_menu(db)
ensure_site_member_menu(db)
ensure_agent_user_menu(db)
ensure_system_menu_order(db)
ensure_agent_admin_role(db)
def main() -> int:
+14
View File
@@ -0,0 +1,14 @@
from fastapi import Request
from app.core.config import get_settings
def client_ip(request: Request) -> str:
if get_settings().trust_proxy:
forwarded = request.headers.get("x-forwarded-for", "")
first = forwarded.split(",")[0].strip()
if first:
return first[:64]
if request.client is None:
return ""
return request.client.host or ""
+9
View File
@@ -32,6 +32,12 @@ class Settings(BaseSettings):
minio_bucket_private: str = "gsfdc-private"
minio_secure: bool = False
minio_base_url: str = ""
# 浏览器能打开的 MinIO 主机名,只用于私有文件的签名链接。空则与 minio_endpoint 相同。
minio_public_endpoint: str = ""
minio_public_secure: bool = True
# 置于反向代理之后时,用 X-Forwarded-For 的第一段作为访客地址。
trust_proxy: bool = False
expose_docs: bool = True
field_aes_key: str = ""
gaode_key: str = ""
gaode_security_js_code: str = ""
@@ -46,6 +52,9 @@ class Settings(BaseSettings):
dify_sso_secret: str = ""
dify_sso_email_domain: str = "gsrea.local"
dify_sso_ttl_sec: int = 90
dify_api_base: str = "http://127.0.0.1:13080/v1"
dify_valuation_api_key: str = ""
valuation_admin_emails: str = ""
@property
def cors_origin_list(self) -> list[str]:
+10
View File
@@ -24,3 +24,13 @@ async def require_member(
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="请先登录")
return decode_access_token(credentials.credentials, "member")
async def require_agent(
credentials: HTTPAuthorizationCredentials | None = Depends(bearer),
) -> dict:
if credentials is None:
from fastapi import HTTPException, status
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="请先登录")
return decode_access_token(credentials.credentials, "agent")
+2 -1
View File
@@ -6,6 +6,7 @@ from fastapi.responses import JSONResponse, Response
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.middleware.cors import CORSMiddleware
from app.core.client_ip import client_ip
from app.core.config import get_settings
from app.core.crypto import decrypt_json, encrypt_json
@@ -24,7 +25,7 @@ def _skip_encrypt(path: str, content_type: str) -> bool:
class AccessGuardMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request: Request, call_next):
client = request.client.host if request.client else ""
client = client_ip(request)
if _ip_blocked(client):
return JSONResponse(status_code=403, content={"detail": "访问被拒绝"})
+4 -4
View File
@@ -6,7 +6,7 @@ from fastapi import HTTPException, status
from app.core.config import get_settings
TokenType = Literal["staff", "member"]
TokenType = Literal["staff", "member", "agent"]
def create_access_token(subject: str, token_type: TokenType) -> str:
@@ -17,9 +17,9 @@ def create_access_token(subject: str, token_type: TokenType) -> str:
detail="鉴权未配置",
)
minutes = (
settings.jwt_member_expire_minutes
if token_type == "member"
else settings.jwt_expire_minutes
settings.jwt_expire_minutes
if token_type == "staff"
else settings.jwt_member_expire_minutes
)
expire = datetime.now(timezone.utc) + timedelta(minutes=minutes)
payload = {"sub": subject, "typ": token_type, "exp": expire}
+27 -1
View File
@@ -20,10 +20,12 @@ def prepare_runtime() -> None:
import app.models.legal # noqa: F401
import app.models.discipline # noqa: F401
import app.models.expert # noqa: F401
import app.models.agent_user # noqa: F401
import app.models.member # noqa: F401
import app.models.uploaded_case # noqa: F401
import app.models.rbac # noqa: F401
import app.models.security # noqa: F401
import app.models.valuation # noqa: F401
from app.db import Base, SessionLocal, get_engine
from app.models.content import ensure_site_defaults
from app.models.home import (
@@ -47,6 +49,11 @@ def prepare_runtime() -> None:
ensure_article_body_capacity(db)
ensure_uploaded_case_columns(db)
seed_ip_blacklist(db)
from app.models.valuation import ensure_default_suggestions, ensure_default_template, ensure_valuation_columns
ensure_valuation_columns(db)
ensure_default_suggestions(db)
ensure_default_template(db)
from app.commands.create_superuser import (
ensure_about_menu,
ensure_ai_agent_menu,
@@ -58,6 +65,8 @@ def prepare_runtime() -> None:
ensure_report_menu,
ensure_discipline_menu,
ensure_edu_menu,
ensure_agent_user_menu,
ensure_site_member_menu,
ensure_system_menu_order,
ensure_tech_menu,
)
@@ -73,7 +82,18 @@ def prepare_runtime() -> None:
ensure_tech_menu(db)
ensure_edu_menu(db)
ensure_ai_agent_menu(db)
ensure_site_member_menu(db)
ensure_agent_user_menu(db)
ensure_system_menu_order(db)
from app.models.agent_user import ensure_agent_admin_link
ensure_agent_admin_link(db)
from app.commands.create_superuser import ensure_agent_admin_role
ensure_agent_admin_role(db)
from app.models.member import ensure_member_columns
ensure_member_columns(db)
db.commit()
finally:
db.close()
@@ -88,7 +108,13 @@ def prepare_runtime() -> None:
def create_app() -> FastAPI:
settings = get_settings()
app = FastAPI(title=settings.app_name, docs_url="/docs", openapi_url="/openapi.json")
docs_url = "/docs" if settings.expose_docs else None
app = FastAPI(
title=settings.app_name,
docs_url=docs_url,
redoc_url="/redoc" if settings.expose_docs else None,
openapi_url="/openapi.json" if settings.expose_docs else None,
)
install_middleware(app)
app.include_router(api_router)
prepare_runtime()
+381
View File
@@ -0,0 +1,381 @@
"""估价智能体登录账号。
特殊账号不另存一份密码:登录和资料都读用户管理里钉住的那一位工作人员。
"""
from datetime import datetime, timezone
from sqlalchemy import Boolean, DateTime, Integer, String, func, inspect, or_, select, text
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import Mapped, mapped_column
from app.db import Base
from app.models.rbac import AdminRole, AdminUser, AdminUserRole
AGENT_ADMIN_ROLE_CODE = "R_AGENT_ADMIN"
AGENT_ADMIN_ROLE_NAME = "智能体管理员"
AGENT_STATUSES = ("active", "disabled", "cancelled")
def _mysql_args() -> dict:
return {"mysql_charset": "utf8mb4", "mysql_collate": "utf8mb4_unicode_ci"}
def _now() -> datetime:
return datetime.now(timezone.utc).replace(tzinfo=None)
def _iso(value: datetime | None) -> str | None:
if value is None:
return None
return value.isoformat(timespec="seconds")
class AgentUser(Base):
__tablename__ = "agent_user"
__table_args__ = _mysql_args()
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
username: Mapped[str] = mapped_column(String(64), unique=True, nullable=False)
password_hash: Mapped[str] = mapped_column(String(255), nullable=False)
display_name: Mapped[str] = mapped_column(String(64), nullable=False, default="")
status: Mapped[str] = mapped_column(String(16), nullable=False, default="active")
failed_login_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
locked_until: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, default=_now)
updated_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, default=_now)
class AgentAdminLink(Base):
"""智能体里的特殊账号对应哪一位工作人员。全表只有 id=1 这一行。"""
__tablename__ = "agent_admin_link"
__table_args__ = _mysql_args()
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=False)
admin_user_id: Mapped[int] = mapped_column(Integer, nullable=False)
agent_enabled: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True)
class AgentActor:
def __init__(self, key: str, username: str, display_name: str, can_manage: bool) -> None:
self.key = key
self.username = username
self.display_name = display_name
self.can_manage = can_manage
def ensure_agent_admin_link(db) -> None:
"""把用户名为 admin 的工作人员钉成门户注册用户里的特殊账号。已钉住时不改指向。"""
bind = db.get_bind()
if bind.dialect.name == "mysql":
names = {column["name"] for column in inspect(bind).get_columns("agent_admin_link")} if inspect(bind).has_table("agent_admin_link") else set()
if names and "agent_enabled" not in names:
db.execute(
text("ALTER TABLE agent_admin_link ADD COLUMN agent_enabled TINYINT(1) NOT NULL DEFAULT 1")
)
db.flush()
admin = db.scalar(select(AdminUser).where(AdminUser.username == "admin"))
if admin is None:
return
bind = db.get_bind()
if bind.dialect.name == "mysql":
db.execute(
text(
"INSERT INTO agent_admin_link (id, admin_user_id) VALUES (1, :admin_id) "
"ON DUPLICATE KEY UPDATE id = id"
),
{"admin_id": admin.id},
)
else:
db.execute(
text("INSERT OR IGNORE INTO agent_admin_link (id, admin_user_id) VALUES (1, :admin_id)"),
{"admin_id": admin.id},
)
db.flush()
def linked_admin_user(db) -> AdminUser | None:
link = db.get(AgentAdminLink, 1)
if link is None:
return db.scalar(select(AdminUser).where(AdminUser.username == "admin"))
return db.get(AdminUser, link.admin_user_id)
def _staff_key(user_id: int) -> str:
return f"staff-{user_id}"
def _agent_key(user_id: int) -> str:
return f"agent-{user_id}"
def parse_agent_user_key(raw: str) -> tuple[str, int]:
kind, separator, ident = (raw or "").partition("-")
if separator != "-" or kind not in {"staff", "agent"} or not ident.isdigit():
raise LookupError("用户不存在")
return kind, int(ident)
def serialize_staff_agent(user: AdminUser) -> dict:
return {
"id": _staff_key(user.id),
"builtin": True,
"username": user.username,
"displayName": user.display_name,
"mobileMask": user.mobile_mask or "",
"status": user.status,
"createdAt": _iso(user.created_at),
"updatedAt": _iso(user.updated_at),
}
def serialize_agent_user(row: AgentUser) -> dict:
return {
"id": _agent_key(row.id),
"builtin": False,
"username": row.username,
"displayName": row.display_name,
"mobileMask": "",
"status": row.status,
"createdAt": _iso(row.created_at),
"updatedAt": _iso(row.updated_at),
}
def _matches(user_name: str, display_name: str, keyword: str) -> bool:
if not keyword:
return True
folded = keyword.casefold()
return folded in user_name.casefold() or folded in (display_name or "").casefold()
def query_agent_users(db, *, current: int, size: int, username: str | None) -> dict:
if current < 1:
current = 1
if size < 1:
size = 10
if size > 200:
size = 200
keyword = (username or "").strip()
filters = []
if keyword:
filters.append(or_(AgentUser.username.contains(keyword), AgentUser.display_name.contains(keyword)))
rows = list(
db.scalars(select(AgentUser).where(*filters).order_by(AgentUser.id.desc())).all()
)
records = []
admin = linked_admin_user(db)
if admin is not None and _matches(admin.username, admin.display_name, keyword):
records.append(serialize_staff_agent(admin))
records.extend(serialize_agent_user(row) for row in rows)
total = len(records)
start = (current - 1) * size
return {
"records": records[start : start + size],
"current": current,
"size": size,
"total": total,
}
def get_agent_record(db, user_key: str) -> dict:
kind, user_id = parse_agent_user_key(user_key)
if kind == "staff":
admin = linked_admin_user(db)
if admin is None or admin.id != user_id:
raise LookupError("用户不存在")
return serialize_staff_agent(admin)
row = db.get(AgentUser, user_id)
if row is None:
raise LookupError("用户不存在")
return serialize_agent_user(row)
def _require_display_name(display_name: str) -> str:
text_value = (display_name or "").strip()
if not text_value:
raise ValueError("请填写姓名")
if len(text_value) > 64:
raise ValueError("姓名过长")
return text_value
def _require_username(username: str) -> str:
text_value = (username or "").strip()
if not text_value:
raise ValueError("请填写用户名")
if len(text_value) > 64:
raise ValueError("用户名过长")
return text_value
def _require_status(status_value: str) -> str:
text_value = (status_value or "").strip()
if text_value not in AGENT_STATUSES:
raise ValueError("用户状态不正确")
return text_value
def _username_taken(db, username: str) -> bool:
folded = username.casefold()
admin = linked_admin_user(db)
if admin is not None and admin.username.casefold() == folded:
return True
if folded == "admin":
return True
found = db.scalar(select(AgentUser.id).where(func.lower(AgentUser.username) == username.lower()))
return found is not None
def create_agent_user(db, *, username: str, password_hash: str, display_name: str, status: str) -> dict:
username_text = _require_username(username)
display_text = _require_display_name(display_name)
status_text = _require_status(status or "active")
if _username_taken(db, username_text):
raise ValueError("用户名已存在")
now = _now()
row = AgentUser(
username=username_text,
password_hash=password_hash,
display_name=display_text,
status=status_text,
failed_login_count=0,
created_at=now,
updated_at=now,
)
db.add(row)
try:
db.commit()
except IntegrityError as exc:
db.rollback()
raise ValueError("用户名已存在") from exc
db.refresh(row)
return serialize_agent_user(row)
def update_agent_record(
db,
user_key: str,
*,
display_name: str,
status: str,
password_hash: str | None,
) -> dict:
kind, user_id = parse_agent_user_key(user_key)
display_text = _require_display_name(display_name)
status_text = _require_status(status)
now = _now()
if kind == "staff":
admin = linked_admin_user(db)
if admin is None or admin.id != user_id:
raise LookupError("用户不存在")
admin.display_name = display_text
admin.status = status_text
if password_hash:
admin.password_hash = password_hash
admin.updated_at = datetime.now(timezone.utc)
db.commit()
db.refresh(admin)
return serialize_staff_agent(admin)
row = db.get(AgentUser, user_id)
if row is None:
raise LookupError("用户不存在")
row.display_name = display_text
row.status = status_text
if password_hash:
row.password_hash = password_hash
row.updated_at = now
db.commit()
db.refresh(row)
return serialize_agent_user(row)
def delete_agent_record(db, user_key: str) -> None:
kind, user_id = parse_agent_user_key(user_key)
if kind == "staff":
raise ValueError("该账号与用户管理中的 admin 是同一账号,不能在这里删除")
row = db.get(AgentUser, user_id)
if row is None:
raise LookupError("用户不存在")
db.delete(row)
db.commit()
def admin_agent_enabled(db) -> bool:
link = db.get(AgentAdminLink, 1)
if link is None:
return True
return bool(link.agent_enabled)
def set_admin_agent_enabled(db, enabled: bool) -> None:
link = db.get(AgentAdminLink, 1)
if link is None:
raise LookupError("用户不存在")
link.agent_enabled = bool(enabled)
db.flush()
def find_login_account(db, account: str):
"""门户注册用户登录智能体。特殊账号 admin 走用户管理里的同一条记录。"""
from app.models.member import get_member_by_email
name = (account or "").strip()
if not name:
return None
admin = linked_admin_user(db)
if admin is not None and admin.username.casefold() == name.casefold():
return "staff", admin, admin_agent_enabled(db)
member = get_member_by_email(db, name)
if member is None:
return None
return "member", member, bool(member.agent_enabled)
def staff_can_manage(db, user_id: int) -> bool:
found = db.scalar(
select(AdminUserRole.user_id)
.join(AdminRole, AdminRole.id == AdminUserRole.role_id)
.where(
AdminUserRole.user_id == user_id,
AdminRole.code == AGENT_ADMIN_ROLE_CODE,
AdminRole.status == "active",
)
)
return found is not None
def load_agent_actor(db, subject: str) -> AgentActor:
if subject.startswith("s:"):
try:
user_id = int(subject[2:])
except ValueError as exc:
raise LookupError("登录已失效") from exc
user = db.get(AdminUser, user_id)
if user is None or user.status != "active":
raise LookupError("登录已失效")
return AgentActor(
key=subject,
username=user.username,
display_name=user.display_name or user.username,
can_manage=staff_can_manage(db, user.id),
)
if subject.startswith("m:"):
from app.models.member import get_member_by_id
try:
user_id = int(subject[2:])
except ValueError as exc:
raise LookupError("登录已失效") from exc
row = get_member_by_id(db, user_id)
if row is None or row.status != "active" or not row.agent_enabled:
raise LookupError("登录已失效")
return AgentActor(
key=subject,
username=row.email,
display_name=row.email.split("@", 1)[0],
can_manage=False,
)
raise LookupError("登录已失效")
+109 -1
View File
@@ -1,6 +1,6 @@
from datetime import datetime, timezone
from sqlalchemy import DateTime, Integer, String, select
from sqlalchemy import Boolean, DateTime, Integer, String, func, inspect, select, text
from sqlalchemy.orm import Mapped, mapped_column
from app.db import Base
@@ -25,6 +25,7 @@ class SiteMember(Base):
email: Mapped[str] = mapped_column(String(191), unique=True, nullable=False)
password_hash: Mapped[str] = mapped_column(String(255), nullable=False)
status: Mapped[str] = mapped_column(String(16), nullable=False, default="active")
agent_enabled: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)
privacy_accepted_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, default=_now)
updated_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, default=_now)
@@ -60,3 +61,110 @@ def set_member_password(db, member: SiteMember, password_hash: str) -> None:
member.password_hash = password_hash
member.updated_at = _now()
db.commit()
def ensure_member_columns(db) -> None:
bind = db.get_bind()
if bind.dialect.name != "mysql":
return
names = {column["name"] for column in inspect(bind).get_columns("site_member")}
if "agent_enabled" not in names:
db.execute(
text("ALTER TABLE site_member ADD COLUMN agent_enabled TINYINT(1) NOT NULL DEFAULT 0")
)
db.commit()
def _iso(value: datetime | None) -> str | None:
if value is None:
return None
return value.isoformat(timespec="seconds")
def serialize_member(row: SiteMember) -> dict:
return {
"id": row.id,
"email": row.email,
"status": row.status,
"builtin": False,
"agentEnabled": bool(row.agent_enabled),
"displayName": "",
"privacyAcceptedAt": _iso(row.privacy_accepted_at),
"createdAt": _iso(row.created_at),
"updatedAt": _iso(row.updated_at),
}
def query_members(
db,
*,
current: int,
size: int,
email: str | None,
offset: int | None = None,
limit: int | None = None,
) -> dict:
if current < 1:
current = 1
if size < 1:
size = 10
if size > 200:
size = 200
filters = []
keyword = (email or "").strip().lower()
if keyword:
filters.append(SiteMember.email.contains(keyword))
total = db.scalar(select(func.count()).select_from(SiteMember).where(*filters)) or 0
start = (current - 1) * size if offset is None else max(offset, 0)
take = size if limit is None else max(limit, 0)
rows = db.scalars(
select(SiteMember)
.where(*filters)
.order_by(SiteMember.id.desc())
.offset(start)
.limit(take)
).all()
return {
"records": [serialize_member(row) for row in rows],
"current": current,
"size": size,
"total": int(total),
}
def update_member(
db,
member_id: int,
*,
email: str,
status: str,
password_hash: str | None,
agent_enabled: bool | None = None,
) -> SiteMember:
row = get_member_by_id(db, member_id)
if row is None:
raise LookupError("用户不存在")
normalized = email.strip().lower()
other = get_member_by_email(db, normalized)
if other is not None and other.id != row.id:
raise ValueError("该邮箱已注册")
if status not in MEMBER_STATUSES:
raise ValueError("状态不正确")
row.email = normalized
row.status = status
if agent_enabled is not None:
row.agent_enabled = bool(agent_enabled)
if password_hash:
row.password_hash = password_hash
row.updated_at = _now()
db.commit()
db.refresh(row)
return row
def delete_member(db, member_id: int) -> None:
row = get_member_by_id(db, member_id)
if row is None:
raise LookupError("用户不存在")
db.delete(row)
db.commit()
+207
View File
@@ -0,0 +1,207 @@
from datetime import datetime, timezone
import json
from sqlalchemy import Boolean, DateTime, Integer, String, Text, inspect, select, text
from sqlalchemy.dialects.mysql import MEDIUMTEXT
from sqlalchemy.orm import Mapped, mapped_column
from app.db import Base
def _now() -> datetime:
return datetime.now(timezone.utc).replace(tzinfo=None)
def _mysql_args() -> dict:
return {"mysql_charset": "utf8mb4", "mysql_collate": "utf8mb4_unicode_ci"}
def _long_text():
return Text().with_variant(MEDIUMTEXT(), "mysql")
WELCOME = (
"您好,我是智能估价。可依据库内估值报告,询问评估对象、基准日、价值类型、结论值或方法要点。"
)
DEFAULT_SUGGESTIONS = (
"日播时尚这份估值报告的评估对象和价值结论是什么?",
"华润三九相关估值报告采用了哪些主要方法?",
"浙江建投申报稿前部的评估报告清单包含哪些子报告?",
)
class ValuationSession(Base):
__tablename__ = "valuation_session"
__table_args__ = _mysql_args()
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
member_id: Mapped[int] = mapped_column(Integer, nullable=False, index=True)
owner_key: Mapped[str] = mapped_column(String(32), nullable=False, default="", index=True)
title: Mapped[str] = mapped_column(String(80), nullable=False, default="新会话")
dify_conversation_id: Mapped[str] = mapped_column(String(64), nullable=False, default="")
created_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, default=_now)
updated_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, default=_now)
class ValuationMessage(Base):
__tablename__ = "valuation_message"
__table_args__ = _mysql_args()
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
session_id: Mapped[int] = mapped_column(Integer, nullable=False, index=True)
role: Mapped[str] = mapped_column(String(16), nullable=False)
content: Mapped[str] = mapped_column(_long_text(), nullable=False, default="")
thought: Mapped[str] = mapped_column(_long_text(), nullable=False, default="")
attachments: Mapped[str] = mapped_column(Text, nullable=False, default="")
web_enabled: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)
kind: Mapped[str] = mapped_column(String(16), nullable=False, default="chat")
draft_format: Mapped[str] = mapped_column(String(8), nullable=False, default="")
draft_name: Mapped[str] = mapped_column(String(80), nullable=False, default="")
sources: Mapped[str] = mapped_column(Text, nullable=False, default="[]")
created_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, default=_now)
class ValuationFile(Base):
__tablename__ = "valuation_file"
__table_args__ = _mysql_args()
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
member_id: Mapped[int] = mapped_column(Integer, nullable=False, index=True)
owner_key: Mapped[str] = mapped_column(String(32), nullable=False, default="", index=True)
session_id: Mapped[int | None] = mapped_column(Integer, nullable=True, index=True)
filename: Mapped[str] = mapped_column(String(255), nullable=False)
extension: Mapped[str] = mapped_column(String(16), nullable=False)
content_type: Mapped[str] = mapped_column(String(128), nullable=False, default="")
size: Mapped[int] = mapped_column(Integer, nullable=False)
object_key: Mapped[str] = mapped_column(String(255), nullable=False)
created_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, default=_now)
DEFAULT_TEMPLATE_NAME = "估价说明草稿"
DEFAULT_TEMPLATE_OUTLINE = """一、评估对象概述
二、价值类型与评估基准日
三、评估方法与关键假设
四、主要参数与依据
五、结论摘要(辅助,非正式)"""
class ValuationTemplate(Base):
__tablename__ = "valuation_template"
__table_args__ = _mysql_args()
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
name: Mapped[str] = mapped_column(String(80), nullable=False)
filename: Mapped[str] = mapped_column(String(255), nullable=False, default="")
object_key: Mapped[str] = mapped_column(String(255), nullable=False, default="")
outline: Mapped[str] = mapped_column(_long_text(), nullable=False, default="")
enabled: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True)
created_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, default=_now)
class ValuationSuggestion(Base):
__tablename__ = "valuation_suggestion"
__table_args__ = _mysql_args()
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
text: Mapped[str] = mapped_column(String(200), nullable=False)
sort_order: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
enabled: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True)
created_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, default=_now)
def ensure_valuation_columns(db) -> None:
bind = db.get_bind()
if bind.dialect.name != "mysql":
return
names = {column["name"] for column in inspect(bind).get_columns("valuation_message")}
if "attachments" not in names:
db.execute(text("ALTER TABLE valuation_message ADD COLUMN attachments TEXT NULL"))
if "web_enabled" not in names:
db.execute(text("ALTER TABLE valuation_message ADD COLUMN web_enabled TINYINT(1) NOT NULL DEFAULT 0"))
if "kind" not in names:
db.execute(text("ALTER TABLE valuation_message ADD COLUMN kind VARCHAR(16) NOT NULL DEFAULT 'chat'"))
if "sources" not in names:
db.execute(text("ALTER TABLE valuation_message ADD COLUMN sources TEXT NULL"))
if "draft_format" not in names:
db.execute(text("ALTER TABLE valuation_message ADD COLUMN draft_format VARCHAR(8) NOT NULL DEFAULT ''"))
if "draft_name" not in names:
db.execute(text("ALTER TABLE valuation_message ADD COLUMN draft_name VARCHAR(80) NOT NULL DEFAULT ''"))
for table in ("valuation_session", "valuation_file"):
columns = {column["name"] for column in inspect(bind).get_columns(table)}
if "owner_key" not in columns:
db.execute(
text(f"ALTER TABLE {table} ADD COLUMN owner_key VARCHAR(32) NOT NULL DEFAULT ''")
)
for table, column in (
("valuation_message", "content"),
("valuation_message", "thought"),
("valuation_template", "outline"),
):
row = db.execute(
text(
"SELECT DATA_TYPE FROM information_schema.COLUMNS "
"WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = :table AND COLUMN_NAME = :column"
),
{"table": table, "column": column},
).first()
if row is not None and str(row[0]).lower() == "text":
db.execute(text(f"ALTER TABLE {table} MODIFY {column} MEDIUMTEXT"))
db.commit()
def attachment_names(raw: str) -> list[str]:
names: list[str] = []
for item in _json_list(raw):
if isinstance(item, str) and item.strip():
names.append(item.strip())
return names
def stored_knowledge_names(raw: str) -> list[str]:
names: list[str] = []
for item in _json_list(raw):
if isinstance(item, str) and item.strip():
names.append(item.strip())
elif isinstance(item, dict) and item.get("kind") != "attachment":
name = str(item.get("name") or "").strip()
if name:
names.append(name)
return names
def _json_list(raw: str) -> list:
if not raw:
return []
try:
value = json.loads(raw)
except json.JSONDecodeError:
return []
return value if isinstance(value, list) else []
def ensure_default_template(db) -> None:
exists = db.scalar(select(ValuationTemplate.id).limit(1))
if exists is not None:
return
db.add(
ValuationTemplate(
name=DEFAULT_TEMPLATE_NAME,
filename="估价说明草稿.docx",
object_key="",
outline=DEFAULT_TEMPLATE_OUTLINE,
enabled=True,
created_at=_now(),
)
)
db.commit()
def ensure_default_suggestions(db) -> None:
exists = db.scalar(select(ValuationSuggestion.id).limit(1))
if exists is not None:
return
for index, text in enumerate(DEFAULT_SUGGESTIONS):
db.add(ValuationSuggestion(text=text, sort_order=index, enabled=True, created_at=_now()))
db.commit()
+2 -1
View File
@@ -2,6 +2,7 @@ import logging
from sqlalchemy import select
from app.core.client_ip import client_ip
from app.core.config import get_settings
logger = logging.getLogger("gsfdc.audit")
@@ -80,7 +81,7 @@ def record_admin_call(request, status_code: int) -> None:
if not path.startswith("/api/admin"):
return
user_id, username = _staff_from_header(request)
client = request.client.host if request.client else ""
client = client_ip(request)
write_audit(
user_id=user_id,
username=username,
+249
View File
@@ -0,0 +1,249 @@
import json
from collections.abc import Iterator
import httpx
from app.core.config import get_settings
class DifyNotConfigured(RuntimeError):
pass
class DifyChatError(RuntimeError):
pass
_THINK_OPEN = "<think>"
_THINK_CLOSE = "</think>"
_REASON_MARK = "<!--dify-deepseek-reasoning-->"
def _ensure_parse_state(state: dict) -> None:
state.setdefault("answer", "")
state.setdefault("thoughts", {})
state.setdefault("in_think", False)
state.setdefault("carry", "")
state.setdefault("think_text", "")
def _clean_thought(text: str) -> str:
return (text or "").replace(_REASON_MARK, "").strip()
def joined_thought(state: dict) -> str:
_ensure_parse_state(state)
parts = [_clean_thought(item) for item in state["thoughts"].values()]
extra = _clean_thought(state["think_text"])
return "\n\n".join(part for part in (*parts, extra) if part)
def _hold_partial(text: str, token: str) -> tuple[str, str]:
limit = min(len(token) - 1, len(text))
for size in range(limit, 0, -1):
if text.endswith(token[:size]):
return text[:-size], text[-size:]
return text, ""
def feed_answer_chunk(state: dict, chunk: str, *, flush: bool = False) -> list[dict]:
"""把模型夹在 think 标签里的推理从可见回答中拆出。"""
_ensure_parse_state(state)
buf = state["carry"] + chunk
state["carry"] = ""
out: list[dict] = []
while True:
if state["in_think"]:
close_at = buf.find(_THINK_CLOSE)
if close_at < 0:
body, hold = (buf, "") if flush else _hold_partial(buf, _THINK_CLOSE)
state["carry"] = hold
if body:
state["think_text"] += body
out.append({"type": "thought", "text": joined_thought(state)})
break
state["think_text"] += buf[:close_at]
out.append({"type": "thought", "text": joined_thought(state)})
state["in_think"] = False
buf = buf[close_at + len(_THINK_CLOSE) :]
continue
open_at = buf.find(_THINK_OPEN)
if open_at < 0:
body, hold = (buf, "") if flush else _hold_partial(buf, _THINK_OPEN)
state["carry"] = hold
if body:
state["answer"] += body
out.append({"type": "delta", "text": body})
break
visible = buf[:open_at]
if visible:
state["answer"] += visible
out.append({"type": "delta", "text": visible})
state["in_think"] = True
buf = buf[open_at + len(_THINK_OPEN) :]
return out
def split_stored_reasoning(content: str, thought: str = "") -> tuple[str, str]:
state = {"answer": "", "thoughts": {}, "in_think": False, "carry": "", "think_text": ""}
feed_answer_chunk(state, content or "", flush=True)
extra = _clean_thought(state["think_text"])
prior = _clean_thought(thought)
merged = "\n\n".join(part for part in (prior, extra) if part)
return state["answer"].strip(), merged
def apply_dify_event(event: dict, state: dict) -> list[dict]:
_ensure_parse_state(state)
kind = event.get("event")
if event.get("conversation_id"):
state["conversation_id"] = event["conversation_id"]
out: list[dict] = []
if kind in ("message", "agent_message"):
chunk = event.get("answer") or ""
if chunk:
out.extend(feed_answer_chunk(state, chunk))
elif kind == "message_replace":
state["answer"] = ""
state["in_think"] = False
state["carry"] = ""
state["think_text"] = ""
feed_answer_chunk(state, event.get("answer") or "", flush=True)
out.append({"type": "replace", "text": state["answer"]})
thought = joined_thought(state)
if thought:
out.append({"type": "thought", "text": thought})
elif kind == "agent_thought":
thought = (event.get("thought") or "").strip()
if thought:
key = str(event.get("id") or len(state["thoughts"]) + 1)
state["thoughts"][key] = thought
out.append({"type": "thought", "text": joined_thought(state)})
elif kind == "error":
raise DifyChatError(event.get("message") or "Dify 返回错误")
elif kind == "message_end":
out.extend(feed_answer_chunk(state, "", flush=True))
documents = source_documents(event.get("metadata"))
if documents:
state["sources"] = documents
out.append({"type": "sources", "documents": documents})
out.append({"type": "done", "conversationId": state.get("conversation_id") or ""})
return out
def cited_documents(attachments: list[str], retrieved: list[str]) -> list[dict[str, str]]:
items: list[dict[str, str]] = []
seen: set[tuple[str, str]] = set()
attachment_names: set[str] = set()
for name in _unique_names(attachments):
items.append({"name": name, "kind": "attachment"})
seen.add(("attachment", name))
attachment_names.add(name)
for name in _unique_names(retrieved):
if name in attachment_names or ("knowledge", name) in seen:
continue
items.append({"name": name, "kind": "knowledge"})
seen.add(("knowledge", name))
return items
def _unique_names(items: list[str]) -> list[str]:
names: list[str] = []
seen: set[str] = set()
for item in items:
name = str(item or "").strip()
if not name or name in seen:
continue
seen.add(name)
names.append(name)
return names
def source_documents(metadata: object) -> list[str]:
if not isinstance(metadata, dict):
return []
resources = metadata.get("retriever_resources") or []
if not isinstance(resources, list):
return []
names: list[str] = []
seen: set[str] = set()
for item in resources:
if not isinstance(item, dict):
continue
name = str(item.get("document_name") or "").strip()
if not name or name in seen:
continue
seen.add(name)
names.append(name)
return names
def upload_dify_file(*, filename: str, content: bytes, content_type: str, user: str) -> str:
settings = get_settings()
key = (settings.dify_valuation_api_key or "").strip()
if not key:
raise DifyNotConfigured("未配置估价智能体 API Key")
base = (settings.dify_api_base or "http://127.0.0.1:13080/v1").rstrip("/")
timeout = httpx.Timeout(60.0, connect=10.0)
with httpx.Client(timeout=timeout) as client:
response = client.post(
f"{base}/files/upload",
headers={"Authorization": f"Bearer {key}"},
data={"user": user},
files={"file": (filename, content, content_type or "application/octet-stream")},
)
if response.status_code >= 400:
raise DifyChatError("附件未能交给估价智能体")
file_id = (response.json() or {}).get("id")
if not file_id:
raise DifyChatError("附件未能交给估价智能体")
return str(file_id)
def iter_dify_chat(
*,
query: str,
conversation_id: str,
user: str,
files: list[dict] | None = None,
) -> Iterator[dict]:
settings = get_settings()
key = (settings.dify_valuation_api_key or "").strip()
if not key:
raise DifyNotConfigured("未配置估价智能体 API Key")
base = (settings.dify_api_base or "http://127.0.0.1:13080/v1").rstrip("/")
payload = {
"inputs": {},
"query": query,
"response_mode": "streaming",
"conversation_id": conversation_id or "",
"user": user,
}
if files:
payload["files"] = files
state = {"answer": "", "thoughts": {}, "conversation_id": conversation_id or ""}
timeout = httpx.Timeout(120.0, connect=10.0)
with httpx.Client(timeout=timeout) as client:
with client.stream(
"POST",
f"{base}/chat-messages",
headers={"Authorization": f"Bearer {key}"},
json=payload,
) as response:
if response.status_code >= 400:
response.read()
raise DifyChatError(f"Dify 拒绝请求({response.status_code})")
for raw in response.iter_lines():
line = raw.decode() if isinstance(raw, bytes) else raw
if not line or not line.startswith("data:"):
continue
body = line[5:].strip()
if not body or body == "[DONE]":
continue
try:
event = json.loads(body)
except json.JSONDecodeError:
continue
yield from apply_dify_event(event, state)
if not state["answer"]:
raise DifyChatError("Dify 没有返回回答")
+49 -6
View File
@@ -40,21 +40,50 @@ def _endpoint() -> tuple[str, bool]:
return endpoint.rstrip("/"), secure
def _http_client() -> urllib3.PoolManager:
return urllib3.PoolManager(
timeout=urllib3.Timeout(connect=3.0, read=60.0),
retries=False,
)
def _client() -> Minio:
settings = get_settings()
endpoint, secure = _endpoint()
if not endpoint or not settings.minio_access_key or not settings.minio_secret_key:
_unconfigured()
http_client = urllib3.PoolManager(
timeout=urllib3.Timeout(connect=3.0, read=60.0),
retries=False,
)
return Minio(
endpoint,
access_key=settings.minio_access_key,
secret_key=settings.minio_secret_key,
secure=secure,
http_client=http_client,
region="us-east-1",
http_client=_http_client(),
)
def _signing_client() -> Minio:
"""私有链接要带浏览器能访问的主机名,签名里的 Host 必须和浏览器一致。"""
settings = get_settings()
public = settings.minio_public_endpoint.strip()
if not public:
return _client()
secure = bool(settings.minio_public_secure)
if public.startswith("https://"):
public = public[len("https://") :]
secure = True
elif public.startswith("http://"):
public = public[len("http://") :]
secure = False
if not settings.minio_access_key or not settings.minio_secret_key:
_unconfigured()
return Minio(
public.rstrip("/"),
access_key=settings.minio_access_key,
secret_key=settings.minio_secret_key,
secure=secure,
region="us-east-1",
http_client=_http_client(),
)
@@ -139,7 +168,7 @@ def private_object_url(object_key: str, expires_seconds: int = 60) -> tuple[str,
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="链接有效期无效")
expires = timedelta(seconds=expires_seconds)
try:
url = _client().presigned_get_object(bucket_name("private"), object_key, expires=expires)
url = _signing_client().presigned_get_object(bucket_name("private"), object_key, expires=expires)
except HTTPException:
raise
except Exception:
@@ -162,6 +191,20 @@ def upload_object(kind: str, object_key: str, data: bytes, content_type: str) ->
_unavailable()
def read_object(kind: str, object_key: str) -> bytes:
try:
response = _client().get_object(bucket_name(kind), object_key)
except HTTPException:
raise
except Exception:
_unavailable()
try:
return response.read()
finally:
response.close()
response.release_conn()
def remove_stored_object(kind: str, object_key: str) -> None:
try:
_client().remove_object(bucket_name(kind), object_key)
+360
View File
@@ -0,0 +1,360 @@
from sqlalchemy import func, select
from sqlalchemy.orm import Session
import json
from app.core.config import get_settings
from app.models.member import SiteMember
from app.services.dify_chat import cited_documents, split_stored_reasoning
from app.services.valuation_context import DRAFT_FORMATS, ensure_answer_note
from app.models.rbac import AdminUser
from app.models.valuation import (
WELCOME,
ValuationFile,
ValuationMessage,
ValuationSession,
ValuationSuggestion,
ValuationTemplate,
_now,
attachment_names,
stored_knowledge_names,
ensure_default_suggestions,
ensure_default_template,
)
from app.services.storage import remove_stored_object
def member_can_manage(db: Session, member: SiteMember) -> bool:
email = (member.email or "").strip().lower()
if not email:
return False
extra = {
item.strip().lower()
for item in (get_settings().valuation_admin_emails or "").split(",")
if item.strip()
}
if email in extra:
return True
matched = db.scalar(
select(AdminUser.id).where(
func.lower(AdminUser.username) == email,
AdminUser.status == "active",
)
)
return matched is not None
def suggestion_payload(row: ValuationSuggestion) -> dict:
return {
"id": row.id,
"text": row.text,
"enabled": bool(row.enabled),
"sortOrder": row.sort_order,
}
def list_suggestions(db: Session, *, enabled_only: bool) -> list[dict]:
ensure_default_suggestions(db)
stmt = select(ValuationSuggestion).order_by(ValuationSuggestion.sort_order, ValuationSuggestion.id)
if enabled_only:
stmt = stmt.where(ValuationSuggestion.enabled.is_(True))
return [suggestion_payload(row) for row in db.scalars(stmt)]
def add_suggestion(db: Session, text: str) -> dict:
clean = text.strip()
current = db.scalar(select(func.max(ValuationSuggestion.sort_order))) or 0
row = ValuationSuggestion(text=clean, sort_order=int(current) + 1, enabled=True, created_at=_now())
db.add(row)
db.commit()
db.refresh(row)
return suggestion_payload(row)
def update_suggestion(db: Session, suggestion_id: int, *, text: str | None, enabled: bool | None) -> dict | None:
row = db.get(ValuationSuggestion, suggestion_id)
if row is None:
return None
if text is not None:
row.text = text.strip()
if enabled is not None:
row.enabled = enabled
db.commit()
db.refresh(row)
return suggestion_payload(row)
def delete_suggestion(db: Session, suggestion_id: int) -> bool:
row = db.get(ValuationSuggestion, suggestion_id)
if row is None:
return False
db.delete(row)
db.commit()
return True
def session_payload(row: ValuationSession) -> dict:
return {
"id": row.id,
"title": row.title,
"updatedAt": row.updated_at.isoformat(timespec="seconds"),
}
def message_payload(row: ValuationMessage) -> dict:
content, thought = split_stored_reasoning(row.content, row.thought or "")
if row.role == "assistant" and (row.kind or "chat") == "chat" and content.strip() != WELCOME.strip():
content = ensure_answer_note(content)
return {
"id": row.id,
"role": row.role,
"content": content,
"thought": thought,
"attachments": attachment_names(row.attachments or ""),
"web": bool(row.web_enabled),
"kind": row.kind or "chat",
"draftFormat": message_draft_format(row),
"draftName": (row.draft_name or "").strip(),
"sources": attachment_names(getattr(row, "sources", "") or ""),
"createdAt": row.created_at.isoformat(timespec="seconds"),
}
def list_sessions(db: Session, owner: str) -> list[dict]:
rows = db.scalars(
select(ValuationSession)
.where(ValuationSession.owner_key == owner)
.order_by(ValuationSession.updated_at.desc(), ValuationSession.id.desc())
)
return [session_payload(row) for row in rows]
def get_owned_session(db: Session, owner: str, session_id: int) -> ValuationSession | None:
row = db.get(ValuationSession, session_id)
if row is None or row.owner_key != owner:
return None
return row
def create_session(db: Session, owner: str) -> dict:
now = _now()
row = ValuationSession(member_id=0, owner_key=owner, title="新会话", created_at=now, updated_at=now)
db.add(row)
db.flush()
db.add(
ValuationMessage(
session_id=row.id,
role="assistant",
content=WELCOME,
thought="",
created_at=now,
)
)
db.commit()
db.refresh(row)
return session_payload(row)
def rename_session(db: Session, owner: str, session_id: int, title: str) -> dict | None:
row = get_owned_session(db, owner, session_id)
if row is None:
return None
row.title = title.strip()[:40]
row.updated_at = _now()
db.commit()
db.refresh(row)
return session_payload(row)
def delete_session(db: Session, owner: str, session_id: int) -> bool:
row = get_owned_session(db, owner, session_id)
if row is None:
return False
files = list(db.scalars(select(ValuationFile).where(ValuationFile.session_id == row.id)))
for item in files:
try:
remove_stored_object("private", item.object_key)
except Exception:
pass
db.delete(item)
db.query(ValuationMessage).filter(ValuationMessage.session_id == row.id).delete()
db.delete(row)
db.commit()
return True
def list_messages(db: Session, owner: str, session_id: int) -> list[dict] | None:
row = get_owned_session(db, owner, session_id)
if row is None:
return None
messages = db.scalars(
select(ValuationMessage)
.where(ValuationMessage.session_id == row.id)
.order_by(ValuationMessage.created_at, ValuationMessage.id)
)
payloads = []
attached: list[str] = []
for item in messages:
payload = message_payload(item)
if payload["role"] == "user":
attached = payload["attachments"]
elif payload["role"] == "assistant":
payload["sources"] = cited_documents(attached, stored_knowledge_names(item.sources or ""))
attached = []
payloads.append(payload)
return payloads
def add_user_message(
db: Session,
session: ValuationSession,
content: str,
*,
attachments: list[str] | None = None,
web: bool = False,
) -> ValuationMessage:
import json
now = _now()
title_source = content.strip() or (attachments[0] if attachments else "")
if session.title == "新会话" and title_source:
session.title = title_source[:22]
session.updated_at = now
row = ValuationMessage(
session_id=session.id,
role="user",
content=content,
thought="",
attachments=json.dumps(attachments or [], ensure_ascii=False),
web_enabled=web,
created_at=now,
)
db.add(row)
db.commit()
db.refresh(session)
db.refresh(row)
return row
def owned_files(db: Session, owner: str, file_ids: list[int]) -> list[ValuationFile] | None:
if not file_ids:
return []
rows = list(db.scalars(select(ValuationFile).where(ValuationFile.id.in_(file_ids))))
found = {row.id: row for row in rows}
ordered = []
for file_id in file_ids:
row = found.get(file_id)
if row is None or row.owner_key != owner:
return None
ordered.append(row)
return ordered
def bind_files(db: Session, files: list[ValuationFile], session_id: int) -> None:
for row in files:
row.session_id = session_id
db.commit()
def template_format(filename: str) -> str:
extension = filename.rsplit(".", 1)[-1].lower() if "." in filename else ""
return "pptx" if extension == "pptx" else "docx"
def message_draft_format(row: ValuationMessage) -> str:
if (row.kind or "") != "draft":
return ""
value = (row.draft_format or "docx").lower()
return value if value in DRAFT_FORMATS else "docx"
def template_payload(row: ValuationTemplate) -> dict:
return {
"id": row.id,
"name": row.name,
"filename": row.filename,
"format": template_format(row.filename),
"enabled": bool(row.enabled),
}
def list_templates(db: Session, *, enabled_only: bool) -> list[dict]:
ensure_default_template(db)
stmt = select(ValuationTemplate).order_by(ValuationTemplate.id)
if enabled_only:
stmt = stmt.where(ValuationTemplate.enabled.is_(True))
return [template_payload(row) for row in db.scalars(stmt)]
def get_template(db: Session, template_id: int, *, enabled_only: bool) -> ValuationTemplate | None:
row = db.get(ValuationTemplate, template_id)
if row is None or (enabled_only and not row.enabled):
return None
return row
def add_template(db: Session, *, name: str, filename: str, object_key: str, outline: str) -> dict:
row = ValuationTemplate(
name=name.strip()[:80],
filename=filename[:255],
object_key=object_key,
outline=outline,
enabled=True,
created_at=_now(),
)
db.add(row)
db.commit()
db.refresh(row)
return template_payload(row)
def set_template_enabled(db: Session, template_id: int, enabled: bool) -> dict | None:
row = db.get(ValuationTemplate, template_id)
if row is None:
return None
row.enabled = enabled
db.commit()
db.refresh(row)
return template_payload(row)
def delete_template(db: Session, template_id: int) -> ValuationTemplate | None:
row = db.get(ValuationTemplate, template_id)
if row is None:
return None
db.delete(row)
db.commit()
return row
def save_assistant_message(
db: Session,
session: ValuationSession,
*,
content: str,
thought: str,
conversation_id: str,
kind: str = "chat",
draft_format: str = "",
draft_name: str = "",
sources: list[str] | None = None,
) -> ValuationMessage:
now = _now()
if conversation_id:
session.dify_conversation_id = conversation_id[:64]
session.updated_at = now
row = ValuationMessage(
session_id=session.id,
role="assistant",
content=content,
thought=thought,
kind=kind,
draft_format=draft_format if draft_format in DRAFT_FORMATS else "",
draft_name=draft_name.strip()[:80],
sources=json.dumps(sources or [], ensure_ascii=False),
created_at=now,
)
db.add(row)
db.commit()
db.refresh(row)
return row
+840
View File
@@ -0,0 +1,840 @@
import csv
import html
import io
import posixpath
import re
import zipfile
import httpx
import xlsxwriter
from docx import Document
from docx.enum.text import WD_LINE_SPACING
from docx.oxml import OxmlElement
from docx.oxml.ns import qn
from docx.shared import Cm, Pt, RGBColor
from pptx import Presentation
from pptx.dml.color import RGBColor as PptRGB
from pptx.enum.shapes import MSO_SHAPE
from pptx.enum.text import PP_ALIGN
from pptx.util import Emu, Pt as PptPt
RISK_LINE = "本成稿为辅助文稿,不构成正式评估意见。"
ANSWER_NOTE = "本回答仅供参考,不构成正式评估意见。"
LEGACY_ANSWER_NOTES = (
("为演示性质,不构成正式评估意见", "仅供参考,不构成正式评估意见"),
("属于演示性质,不构成正式评估意见", "仅供参考,不构成正式评估意见"),
("演示回答不构成正式评估意见", ANSWER_NOTE),
)
ALLOWED_EXTENSIONS = frozenset({"pdf", "docx", "txt", "md", "xlsx", "xls", "csv", "jpg", "jpeg", "png", "webp"})
IMAGE_EXTENSIONS = frozenset({"jpg", "jpeg", "png", "webp"})
MAX_FILES = 5
DOCUMENT_EXCERPT_LIMIT = 32000
IMAGE_EXCERPT = "图片附件。请识别随附图片中的文字和表格,依据图片内容回答,不要只根据文件名回答。"
def file_kind(extension: str) -> str:
return "image" if extension.lower() in IMAGE_EXTENSIONS else "document"
WEB_RESULT_LIMIT = 8
WEB_SNIPPET_LIMIT = 500
WEB_UNAVAILABLE = "联网检索没有连上,本次没有取回网页摘录。"
_SEARCH_HEADERS = {
"User-Agent": (
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) "
"AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36"
),
"Accept-Language": "zh-CN,zh;q=0.9",
}
def _result_line(title: str, snippet: str, url: str) -> str:
snippet = re.sub(r"(详情|\.\.\.)$", "", snippet).strip()
return " ".join(part for part in (title, snippet, f"来源:{url}" if url else "") if part)[:WEB_SNIPPET_LIMIT]
def _parse_sogou(page: str, limit: int) -> list[str]:
chunks = re.split(r'(?=<h3\b[^>]*class="[^"]*vr-title)', page, flags=re.I)
items: list[str] = []
seen: set[str] = set()
for chunk in chunks[1:]:
link = re.search(r'<a[^>]*href="(https?://[^"]+)"[^>]*>(.*?)</a>', chunk, flags=re.I | re.S)
if link is None:
continue
url = html.unescape(link.group(1)).strip()
if not url or url in seen:
continue
title = _plain(re.sub(r"<!--.*?-->", "", link.group(2), flags=re.S))
summary = re.search(r'class="[^"]*summary[^"]*"[^>]*>(.*?)</div>', chunk, flags=re.I | re.S)
snippet = _plain(re.sub(r"<!--.*?-->", "", summary.group(1), flags=re.S)) if summary else ""
line = _result_line(title, snippet, url)
if not title and not snippet:
continue
seen.add(url)
items.append(line)
if len(items) >= limit:
break
return items
def _parse_so(page: str, limit: int) -> list[str]:
chunks = re.split(r'(?=<h3\b[^>]*class="[^"]*res-title)', page, flags=re.I)
items: list[str] = []
seen: set[str] = set()
for chunk in chunks[1:]:
real = re.search(r'data-mdurl="(https?://[^"]+)"', chunk, flags=re.I)
link = re.search(r'<a[^>]*href="(https?://[^"]+)"[^>]*>(.*?)</a>', chunk, flags=re.I | re.S)
if link is None:
continue
url = html.unescape((real.group(1) if real else link.group(1))).strip()
if not url or url in seen or "so.com/link" in url:
continue
title = _plain(link.group(2))
summary = re.search(r'data-result-summary[^>]*>(.*?)</span>', chunk, flags=re.I | re.S)
if summary is None:
summary = re.search(r'class="[^"]*res-desc[^"]*"[^>]*>(.*?)</(?:p|div)>', chunk, flags=re.I | re.S)
snippet = _plain(summary.group(1)) if summary else ""
line = _result_line(title, snippet, url)
if not title and not snippet:
continue
seen.add(url)
items.append(line)
if len(items) >= limit:
break
return items
def parse_search_snippets(page: str, limit: int = WEB_RESULT_LIMIT) -> list[str]:
if 'class="res-title"' in page or 'class="res-desc"' in page:
found = _parse_so(page, limit)
if found:
return found
return _parse_sogou(page, limit)
def _fetch_search_page(url: str, params: dict[str, str]) -> str | None:
try:
response = httpx.get(
url,
params=params,
headers=_SEARCH_HEADERS,
timeout=httpx.Timeout(10.0, connect=5.0),
follow_redirects=True,
)
except httpx.HTTPError:
return None
if response.status_code >= 400 or "captcha" in str(response.url):
return None
return response.text
def search_web(query: str) -> list[str]:
text = query.strip()[:200]
if not text:
return []
pages = [
_fetch_search_page("https://www.sogou.com/web", {"query": text}),
_fetch_search_page("https://www.so.com/s", {"q": text}),
]
if all(page is None for page in pages):
return [WEB_UNAVAILABLE]
items: list[str] = []
seen: set[str] = set()
for page in pages:
if not page:
continue
for line in parse_search_snippets(page, WEB_RESULT_LIMIT):
url = line.split("来源:", 1)[-1]
if url in seen:
continue
seen.add(url)
items.append(line)
if len(items) >= WEB_RESULT_LIMIT:
return items
return items
def extract_excerpt(extension: str, content: bytes, limit: int | None = None) -> str:
kind = extension.lower().lstrip(".")
if kind in {"txt", "md", "csv"}:
text = _plain_bytes(content)
elif kind == "docx":
text = _docx_text(content)
elif kind == "pptx":
text = _pptx_text(content)
elif kind == "xlsx":
text = _xlsx_text(content)
elif kind == "xls":
text = _xls_text(content)
elif kind == "pdf":
text = _pdf_text(content)
elif kind in IMAGE_EXTENSIONS:
text = IMAGE_EXCERPT
else:
text = ""
cap = DOCUMENT_EXCERPT_LIMIT if limit is None else limit
text = text.replace("\x00", "")
text = text.replace("\r\n", "\n").replace("\r", "\n")
text = re.sub(r"[^\S\n]+", " ", text)
text = re.sub(r"\n{3,}", "\n\n", text).strip()
return text[:cap]
def _plain_bytes(content: bytes) -> str:
for encoding in ("utf-8-sig", "gb18030"):
try:
return content.decode(encoding)
except UnicodeDecodeError:
continue
return content.decode("utf-8", errors="ignore")
def wants_document(query: str) -> bool:
text = query.strip()
if not text:
return False
if "按模版生成" in text or "按模板生成" in text:
return True
verbs = ("生成", "起草", "撰写", "写成", "编写", "出一份", "写一份", "做一份", "帮忙写", "帮我写", "请写")
nouns = (
"文档",
"文稿",
"报告",
"说明",
"模版",
"模板",
"幻灯片",
"演示",
"课件",
"PPT",
"ppt",
"表格",
"参数表",
"电子表",
"Excel",
"excel",
"CSV",
"csv",
"Markdown",
"markdown",
"纯文本",
)
return any(word in text for word in verbs) and any(word in text for word in nouns)
def draft_prompt(
*,
template_name: str,
outline: str,
question: str,
file_excerpts: list[tuple[str, str]],
web: bool,
web_snippets: list[str],
template_format: str = "docx",
) -> str:
if template_name and outline.strip() and template_format == "pptx":
lead = (
"请检索知识库,严格按模版中的幻灯片顺序写一份演示文稿。"
"每一页以「第N页」单独一行开始,下一行只写该页标题,随后每行一个要点并以「- 」开头。"
"页数和顺序与模版一致。只根据本次要求和检索结果撰写,不要把此前会话闲聊写入正文。"
)
template_block = f"【模版】{template_name}\n{outline.strip()}"
elif template_name and outline.strip():
lead = (
"请检索知识库,严格按模版章节写一份辅助文稿。只根据本次要求和检索结果撰写,不要把此前会话闲聊写入正文。"
"正文用 Markdown 表达结构:文档标题用「# 」,章节用「## 」,小节用「### 」,说明写成段落,并列项用「- 」,关键词用「**」。"
)
template_block = f"【模版】{template_name}\n{outline.strip()}"
else:
lead = (
"请检索知识库,按本次要求生成辅助文稿,不必套用固定模版。"
"请根据本次要求决定成品类型,不要默认成某一种。"
"可交付类型:Word(docx)、PPT(pptx)、Excel(xlsx)、CSV(csv)、Markdown(md)、纯文本(txt)。"
"用户指定了类型就用该类型;没有指定时,按内容选择最合适的一种。"
"正文第一行必须单独写成「格式:docx」「格式:pptx」「格式:xlsx」「格式:csv」「格式:md」或「格式:txt」,后面再写正文。"
"Word 按章节写,并用 Markdown 表达结构:文档标题用「# 」,章节用「## 」,小节用「### 」,说明写成段落,并列项用「- 」,关键词用「**」。"
"PPT 每一页以「第N页」单独一行开始,下一行只写标题,随后每行一个要点并以「- 」开头。"
"Excel 和 CSV 用「|」分隔单元格,第一行写表头。"
"Markdown 和纯文本按本次要求直接写正文。"
"只根据本次要求和检索结果撰写,不要把此前会话闲聊写入正文。"
)
template_block = "【模版】未指定。请根据本次要求决定成品类型。"
parts = [
lead,
"没有依据的数据写「待补充」,不要编造。",
f"文末必须原样包含:{RISK_LINE}",
template_block,
"【本次要求】" + (question.strip() or "请根据知识库检索结果生成文档。"),
]
if file_excerpts:
blocks = []
for name, body in file_excerpts:
cleaned = body.strip()
blocks.append(f"{name}\n{cleaned}" if cleaned else f"{name}(未能提取正文)")
parts.append("【附件】\n" + "\n\n".join(blocks))
if web:
if web_snippets:
parts.append("【联网摘录】\n" + "\n".join(f"- {item}" for item in web_snippets))
else:
parts.append("【联网摘录】没有检索到可用结果。")
return "\n".join(parts)
def with_risk_line(text: str) -> str:
cleaned = text.strip()
if RISK_LINE in cleaned:
return cleaned
return f"{cleaned}\n\n{RISK_LINE}" if cleaned else RISK_LINE
def ensure_answer_note(text: str) -> str:
cleaned = text.strip()
for legacy, replacement in LEGACY_ANSWER_NOTES:
cleaned = cleaned.replace(legacy, replacement)
cleaned = cleaned.replace(f"{ANSWER_NOTE}。", ANSWER_NOTE)
duplicate = f"{ANSWER_NOTE}\n\n{ANSWER_NOTE}"
while duplicate in cleaned:
cleaned = cleaned.replace(duplicate, ANSWER_NOTE)
if ANSWER_NOTE in cleaned or RISK_LINE in cleaned:
return cleaned
return f"{cleaned}\n\n{ANSWER_NOTE}" if cleaned else ANSWER_NOTE
_MD_BOLD = re.compile(r"\*\*(.+?)\*\*")
_HEADING_LINE = re.compile(r"^(#{1,3})\s+(.+)$")
_BULLET_LINE = re.compile(r"^[-*•]\s+(.+)$")
_NUMBER_LINE = re.compile(r"^\d+[.、]\s+(.+)$")
_QUOTE_LINE = re.compile(r"^>\s?(.+)$")
_CHAPTER_LINE = re.compile(r"^[一二三四五六七八九十]+、\S")
def _docx_blocks(text: str):
for raw in text.splitlines():
line = raw.strip()
if not line or line in {"---", "***"} or line.startswith("```"):
continue
heading = _HEADING_LINE.match(line)
if heading:
yield f"h{len(heading.group(1))}", heading.group(2).strip()
continue
bullet = _BULLET_LINE.match(line)
if bullet:
yield "bullet", bullet.group(1).strip()
continue
number = _NUMBER_LINE.match(line)
if number:
yield "number", number.group(1).strip()
continue
quote = _QUOTE_LINE.match(line)
if quote:
yield "quote", quote.group(1).strip()
continue
if _CHAPTER_LINE.match(line) and len(line) <= 40:
yield "h2", line
continue
yield "p", line
def _set_word_font(run, name: str, size: float, *, bold: bool = False, color: str = "1F2937") -> None:
run.bold = bold
run.font.size = Pt(size)
run.font.color.rgb = RGBColor.from_string(color)
run.font.name = name
fonts = run._element.get_or_add_rPr().get_or_add_rFonts()
fonts.set(qn("w:ascii"), name)
fonts.set(qn("w:hAnsi"), name)
fonts.set(qn("w:eastAsia"), name)
def _fill_word_runs(paragraph, text: str, *, size: float, color: str = "1F2937", name: str = "微软雅黑") -> None:
parts = _MD_BOLD.split(text.replace("`", ""))
if not parts:
parts = [text]
for index, part in enumerate(parts):
if not part:
continue
run = paragraph.add_run(part)
_set_word_font(run, name, size, bold=index % 2 == 1, color=color)
def _shade_paragraph(paragraph, fill: str) -> None:
props = paragraph._p.get_or_add_pPr()
shade = OxmlElement("w:shd")
shade.set(qn("w:val"), "clear")
shade.set(qn("w:color"), "auto")
shade.set(qn("w:fill"), fill)
props.append(shade)
def build_docx(text: str) -> bytes:
document = Document()
section = document.sections[0]
section.page_width = Cm(21)
section.page_height = Cm(29.7)
section.top_margin = Cm(2.2)
section.bottom_margin = Cm(2.2)
section.left_margin = Cm(2.5)
section.right_margin = Cm(2.5)
header = section.header.paragraphs[0]
header.alignment = 1
_fill_word_runs(header, "甘肃省房地产价格评估行业协会", size=9, color="64748B")
footer = section.footer.paragraphs[0]
footer.alignment = 1
_fill_word_runs(footer, "辅助文稿 · 不构成正式评估意见", size=9, color="94A3B8")
normal = document.styles["Normal"]
normal.font.name = "微软雅黑"
normal.font.size = Pt(12)
normal._element.get_or_add_rPr().get_or_add_rFonts().set(qn("w:eastAsia"), "微软雅黑")
for kind, content in _docx_blocks(text or "待补充"):
if kind == "h1":
paragraph = document.add_paragraph(style="Heading 1")
paragraph.paragraph_format.space_before = Pt(6)
paragraph.paragraph_format.space_after = Pt(10)
_fill_word_runs(paragraph, content, size=20, color="1E3A5F", name="微软雅黑")
elif kind == "h2":
paragraph = document.add_paragraph(style="Heading 2")
paragraph.paragraph_format.space_before = Pt(14)
paragraph.paragraph_format.space_after = Pt(6)
_fill_word_runs(paragraph, content, size=15, color="1E3A5F")
elif kind == "h3":
paragraph = document.add_paragraph(style="Heading 3")
paragraph.paragraph_format.space_before = Pt(10)
paragraph.paragraph_format.space_after = Pt(4)
_fill_word_runs(paragraph, content, size=13, color="334155")
elif kind == "bullet":
paragraph = document.add_paragraph(style="List Bullet")
paragraph.paragraph_format.space_after = Pt(3)
_fill_word_runs(paragraph, content, size=12)
elif kind == "number":
paragraph = document.add_paragraph(style="List Number")
paragraph.paragraph_format.space_after = Pt(3)
_fill_word_runs(paragraph, content, size=12)
elif kind == "quote":
paragraph = document.add_paragraph()
paragraph.paragraph_format.left_indent = Cm(0.6)
paragraph.paragraph_format.space_after = Pt(6)
_shade_paragraph(paragraph, "F4F7FB")
_fill_word_runs(paragraph, content, size=11, color="475569")
else:
paragraph = document.add_paragraph()
paragraph.paragraph_format.space_after = Pt(8)
paragraph.paragraph_format.line_spacing_rule = WD_LINE_SPACING.ONE_POINT_FIVE
if content == RISK_LINE:
_shade_paragraph(paragraph, "FFF7ED")
_fill_word_runs(paragraph, content, size=11, color="9A3412")
else:
_fill_word_runs(paragraph, content, size=12)
buffer = io.BytesIO()
document.save(buffer)
return buffer.getvalue()
_SLIDE_HEADING = re.compile(r"^第\s*\d+\s*页\s*$")
_SLIDE_XML = re.compile(r"^ppt/slides/slide(\d+)\.xml$")
DRAFT_FORMATS = frozenset({"docx", "pptx", "xlsx", "csv", "md", "txt"})
_TITLE_PREFIX = re.compile(r"^(?:请)?(?:帮忙|帮我)?(?:生成|起草|撰写|写成|编写|写|做)(?:一份|一个)?")
def draft_title(template_name: str, question: str) -> str:
raw = template_name.strip() or _TITLE_PREFIX.sub("", question.strip())
cleaned = re.sub(r'[\\/:*?"<>|]+', "", raw)
cleaned = re.sub(r"\s+", " ", cleaned).strip(" ,。,.")
return cleaned[:40] or "辅助文稿"
_FORMAT_LINE = re.compile(r"^\s*格式\s*[::]\s*(docx|pptx|xlsx|csv|md|txt)\s*$", re.IGNORECASE)
def infer_free_format(question: str) -> str:
text = question.strip()
lowered = text.lower()
if any(word in text for word in ("幻灯片", "演示文稿", "课件")) or "ppt" in lowered:
return "pptx"
if "csv" in lowered:
return "csv"
if any(word in text for word in ("表格", "电子表", "参数表", "工作表")) or "excel" in lowered or "xlsx" in lowered:
return "xlsx"
if "markdown" in lowered:
return "md"
if any(word in text for word in ("纯文本", "文本文件")) or re.search(r"(?<![a-z])txt(?![a-z])", lowered):
return "txt"
return "docx"
def peel_free_format(buffer: str, *, finished: bool, question: str = "") -> tuple[str, str]:
if not finished and "\n" not in buffer and len(buffer) < 24:
return "", ""
first, _separator, rest = buffer.partition("\n")
match = _FORMAT_LINE.match(first)
if match:
return match.group(1).lower(), rest.lstrip("\n")
return infer_free_format(question), buffer
def slide_blocks(text: str) -> list[tuple[str, list[str]]]:
groups: list[list[str]] = [[]]
started = False
for raw in text.splitlines():
line = raw.strip()
if not line:
continue
if _SLIDE_HEADING.match(line):
if started and groups[-1]:
groups.append([])
elif not started:
groups[-1] = []
started = True
continue
groups[-1].append(line)
groups = [group for group in groups if group] or [["辅助文稿"]]
slides: list[tuple[str, list[str]]] = []
for group in groups[:40]:
title = re.sub(r"^标题[::]\s*", "", group[0])[:120] or "未命名"
body = [re.sub(r"^[-•·]\s*", "", line)[:400] for line in group[1:]]
slides.append((title, body))
if len(groups) > 40:
title, body = slides[-1]
extra = [line for group in groups[40:] for line in group]
slides[-1] = (title, body + extra[:30])
return slides
def _plain_slide_text(value: str) -> str:
text = _MD_BOLD.sub(r"\1", value.replace("`", ""))
text = re.sub(r"^#{1,3}\s+", "", text.strip())
return text or "待补充"
def _paint_shape(shape, color: str) -> None:
shape.fill.solid()
shape.fill.fore_color.rgb = PptRGB.from_string(color)
shape.line.fill.background()
def _write_slide_text(paragraph, text: str, *, size: int, color: str, bold: bool = False) -> None:
paragraph.clear()
paragraph.alignment = PP_ALIGN.LEFT
run = paragraph.add_run()
run.text = text
run.font.size = PptPt(size)
run.font.bold = bold
run.font.color.rgb = PptRGB.from_string(color)
run.font.name = "微软雅黑"
def build_pptx(text: str) -> bytes:
presentation = Presentation()
presentation.slide_width = Emu(12192000)
presentation.slide_height = Emu(6858000)
blank = presentation.slide_layouts[6]
slides = slide_blocks(text)
for index, (title, lines) in enumerate(slides, start=1):
slide = presentation.slides.add_slide(blank)
background = slide.shapes.add_shape(MSO_SHAPE.RECTANGLE, 0, 0, presentation.slide_width, presentation.slide_height)
_paint_shape(background, "F7F9FC")
bar = slide.shapes.add_shape(MSO_SHAPE.RECTANGLE, 0, 0, presentation.slide_width, Emu(1320000))
_paint_shape(bar, "1E3A5F")
accent = slide.shapes.add_shape(MSO_SHAPE.RECTANGLE, 0, Emu(1320000), presentation.slide_width, Emu(70000))
_paint_shape(accent, "C4A35A")
title_box = slide.shapes.add_textbox(Emu(520000), Emu(280000), Emu(10000000), Emu(820000))
_write_slide_text(title_box.text_frame.paragraphs[0], _plain_slide_text(title), size=28, color="FFFFFF", bold=True)
page_box = slide.shapes.add_textbox(Emu(10600000), Emu(360000), Emu(1100000), Emu(500000))
page = page_box.text_frame.paragraphs[0]
page.alignment = PP_ALIGN.RIGHT
run = page.add_run()
run.text = f"{index:02d}"
run.font.size = PptPt(18)
run.font.bold = True
run.font.color.rgb = PptRGB.from_string("C4A35A")
run.font.name = "微软雅黑"
body = slide.shapes.add_textbox(Emu(640000), Emu(1680000), Emu(10900000), Emu(4400000))
frame = body.text_frame
frame.word_wrap = True
usable = [_plain_slide_text(line) for line in lines] or ["待补充"]
for line_index, line in enumerate(usable):
paragraph = frame.paragraphs[0] if line_index == 0 else frame.add_paragraph()
paragraph.clear()
paragraph.level = 0
paragraph.space_after = PptPt(14)
mark = paragraph.add_run()
mark.text = "▸ "
mark.font.size = PptPt(20)
mark.font.color.rgb = PptRGB.from_string("C4A35A")
mark.font.name = "微软雅黑"
content = paragraph.add_run()
content.text = line
content.font.size = PptPt(20)
content.font.color.rgb = PptRGB.from_string("1F2937")
content.font.name = "微软雅黑"
foot = slide.shapes.add_textbox(Emu(520000), Emu(6320000), Emu(11000000), Emu(360000))
_write_slide_text(
foot.text_frame.paragraphs[0],
"甘肃省房地产价格评估行业协会 · 辅助文稿,不构成正式评估意见",
size=11,
color="94A3B8",
)
buffer = io.BytesIO()
presentation.save(buffer)
return buffer.getvalue()
def _table_rows(text: str) -> list[list[str]]:
rows: list[list[str]] = []
for raw in text.splitlines():
line = raw.strip()
if not line or line == RISK_LINE or line.startswith("工作表"):
continue
if "|" in line:
cells = [cell.strip() for cell in line.strip("|").split("|")]
elif "\t" in line:
cells = [cell.strip() for cell in line.split("\t")]
else:
cells = [line]
if cells and all(set(cell) <= set("-: ") and cell for cell in cells):
continue
rows.append(cells)
return rows or [["待补充"]]
def build_xlsx(text: str) -> bytes:
buffer = io.BytesIO()
workbook = xlsxwriter.Workbook(buffer, {"in_memory": True})
sheet = workbook.add_worksheet("文稿")
for row_index, cells in enumerate(_table_rows(text)):
for column_index, value in enumerate(cells):
sheet.write(row_index, column_index, value)
workbook.close()
return buffer.getvalue()
def build_csv(text: str) -> bytes:
buffer = io.StringIO()
writer = csv.writer(buffer)
writer.writerows(_table_rows(text))
return buffer.getvalue().encode("utf-8-sig")
def build_text(text: str) -> bytes:
return (text.strip() or "待补充").encode("utf-8")
def build_draft_file(fmt: str, text: str) -> tuple[bytes, str, str]:
if fmt == "pptx":
media = "application/vnd.openxmlformats-officedocument.presentationml.presentation"
return build_pptx(text), media, "辅助文稿.pptx"
if fmt == "xlsx":
media = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
return build_xlsx(text), media, "辅助文稿.xlsx"
if fmt == "csv":
return build_csv(text), "text/csv; charset=utf-8", "辅助文稿.csv"
if fmt == "md":
return build_text(text), "text/markdown; charset=utf-8", "辅助文稿.md"
if fmt == "txt":
return build_text(text), "text/plain; charset=utf-8", "辅助文稿.txt"
media = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
return build_docx(text), media, "辅助文稿.docx"
def _drawing_lines(payload: bytes) -> list[str]:
xml = payload.decode("utf-8", "ignore")
lines = []
for paragraph in re.findall(r"<a:p\b.*?</a:p>", xml, flags=re.DOTALL):
parts = re.findall(r"<a:t[^>]*>(.*?)</a:t>", paragraph)
line = html.unescape("".join(parts)).strip()
if line:
lines.append(line)
return lines
def _slide_notes(archive: zipfile.ZipFile, slide_name: str) -> list[str]:
rels_name = "ppt/slides/_rels/" + slide_name.rsplit("/", 1)[-1] + ".rels"
if rels_name not in archive.namelist():
return []
xml = archive.read(rels_name).decode("utf-8", "ignore")
match = re.search(r'relationships/notesSlide"\s+Target="([^"]+)"', xml)
if match is None:
match = re.search(r'Target="([^"]+)"[^>]*relationships/notesSlide"', xml)
if match is None:
return []
path = posixpath.normpath(posixpath.join("ppt/slides", match.group(1)))
if path not in archive.namelist():
return []
return _drawing_lines(archive.read(path))
def _pptx_text(content: bytes) -> str:
try:
archive = zipfile.ZipFile(io.BytesIO(content))
except zipfile.BadZipFile:
return ""
with archive:
slides = []
for name in archive.namelist():
match = _SLIDE_XML.match(name)
if match:
slides.append((int(match.group(1)), name))
slides.sort()
blocks = []
for number, name in slides:
lines = [f"第{number}页", *_drawing_lines(archive.read(name))]
notes = _slide_notes(archive, name)
if notes:
lines.append("备注:" + " ".join(notes))
blocks.append("\n".join(line for line in lines if line))
return "\n\n".join(blocks)
def compose_query(
question: str,
*,
file_names: list[str],
web: bool,
web_snippets: list[str],
file_excerpts: list[tuple[str, str]] | None = None,
) -> str:
text = question.strip() or "请结合附件说明要点。"
excerpts = file_excerpts or []
if not file_names and not excerpts and not web:
return text
parts = []
if excerpts:
blocks = []
for name, body in excerpts:
cleaned = body.strip()
blocks.append(f"{name}\n{cleaned}" if cleaned else f"{name}(未能提取正文,请阅读随附文件)")
parts.append("【附件】\n" + "\n\n".join(blocks))
elif file_names:
parts.append("【附件】" + "、".join(file_names))
if web:
if web_snippets:
parts.append("【联网摘录】\n" + "\n".join(f"- {item}" for item in web_snippets))
else:
parts.append("【联网摘录】没有检索到可用结果。")
parts.append("【问题】" + text)
parts.append("请在依据中标明来自知识库、附件或联网;使用了联网摘录时写上来源网址。没有对应材料时不要编造。")
return "\n".join(parts)
def _docx_text(content: bytes) -> str:
try:
with zipfile.ZipFile(io.BytesIO(content)) as archive:
names = [
name
for name in archive.namelist()
if name.startswith("word/")
and (
name.endswith("/document.xml")
or name.rsplit("/", 1)[-1].startswith(("header", "footer", "footnotes", "endnotes"))
)
]
names.sort(key=lambda name: (not name.endswith("/document.xml"), name))
parts = []
for name in names:
xml = archive.read(name).decode("utf-8", "ignore")
xml = re.sub(r"</w:p>", "\n", xml)
xml = re.sub(r"<w:tab[^>]*/>", "\t", xml)
parts.append(html.unescape(re.sub(r"<[^>]+>", "", xml)))
except zipfile.BadZipFile:
return ""
return "\n".join(parts)
def _xlsx_text(content: bytes) -> str:
try:
with zipfile.ZipFile(io.BytesIO(content)) as archive:
names = archive.namelist()
shared = _xlsx_shared_strings(archive, names)
lines = []
for name in sorted(item for item in names if item.startswith("xl/worksheets/sheet") and item.endswith(".xml")):
xml = archive.read(name).decode("utf-8", "ignore")
for row in re.findall(r"<row\b[^>]*>(.*?)</row>", xml, flags=re.S):
cells = [_xlsx_cell(attrs, inner, shared) for attrs, inner in re.findall(r"<c\b([^>]*)>(.*?)</c>", row, flags=re.S)]
line = "\t".join(cell for cell in cells if cell)
if line:
lines.append(line)
except zipfile.BadZipFile:
return ""
return "\n".join(lines)
def _xlsx_shared_strings(archive: zipfile.ZipFile, names: list[str]) -> list[str]:
if "xl/sharedStrings.xml" not in names:
return []
xml = archive.read("xl/sharedStrings.xml").decode("utf-8", "ignore")
values = []
for item in re.findall(r"<si\b.*?</si>", xml, flags=re.S):
texts = re.findall(r"<t\b[^>]*>(.*?)</t>", item, flags=re.S)
values.append(html.unescape("".join(texts)))
return values
def _xlsx_cell(attrs: str, inner: str, shared: list[str]) -> str:
if 't="s"' in attrs:
index = re.search(r"<v>(\d+)</v>", inner)
if index and int(index.group(1)) < len(shared):
return shared[int(index.group(1))]
return ""
if 't="inlineStr"' in attrs:
texts = re.findall(r"<t\b[^>]*>(.*?)</t>", inner, flags=re.S)
return html.unescape("".join(texts))
value = re.search(r"<v>(.*?)</v>", inner)
return html.unescape(value.group(1)) if value else ""
def _xls_text(content: bytes) -> str:
import xlrd
try:
book = xlrd.open_workbook(file_contents=content)
except Exception:
return ""
lines = []
for sheet in book.sheets():
for row_idx in range(sheet.nrows):
cells = []
for col_idx in range(sheet.ncols):
cell = sheet.cell(row_idx, col_idx)
if cell.ctype in (xlrd.XL_CELL_EMPTY, xlrd.XL_CELL_BLANK):
continue
if cell.ctype == xlrd.XL_CELL_DATE:
try:
cells.append(xlrd.xldate_as_datetime(cell.value, book.datemode).strftime("%Y-%m-%d"))
continue
except Exception:
pass
if cell.ctype == xlrd.XL_CELL_NUMBER and float(cell.value).is_integer():
cells.append(str(int(cell.value)))
continue
text = str(cell.value).strip()
if text:
cells.append(text)
if cells:
lines.append("\t".join(cells))
return "\n".join(lines)
def _pdf_text(content: bytes) -> str:
from pypdf import PdfReader
try:
reader = PdfReader(io.BytesIO(content))
if reader.is_encrypted:
reader.decrypt("")
except Exception:
return ""
pages: list[str] = []
for page in reader.pages:
try:
pages.append(page.extract_text() or "")
except Exception:
continue
return "\n".join(pages)
def _xml_escape(value: str) -> str:
return value.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
def _plain(value: str) -> str:
cleaned = re.sub(r"<[^>]+>", " ", html.unescape(value))
return re.sub(r"\s+", " ", cleaned).strip()
+59
View File
@@ -0,0 +1,59 @@
#!/bin/sh
set -eu
python - <<'PY'
import os
import time
import urllib.request
import pymysql
import redis
deadline = time.time() + 180
mysql = dict(
host=os.environ.get("MYSQL_HOST", "mysql"),
port=int(os.environ.get("MYSQL_PORT", "3306")),
user=os.environ.get("MYSQL_USER", "gsfdc"),
password=os.environ.get("MYSQL_PASSWORD", ""),
database=os.environ.get("MYSQL_DATABASE", "gsfdc"),
connect_timeout=3,
)
redis_host = os.environ.get("REDIS_HOST", "redis")
redis_port = int(os.environ.get("REDIS_PORT", "6379"))
redis_password = os.environ.get("REDIS_PASSWORD") or None
minio = os.environ.get("MINIO_ENDPOINT", "minio:9000").removeprefix("http://").removeprefix("https://")
minio_url = "http://" + minio.rstrip("/") + "/minio/health/live"
last = "starting"
while time.time() < deadline:
try:
conn = pymysql.connect(**mysql)
conn.close()
client = redis.Redis(
host=redis_host,
port=redis_port,
password=redis_password,
socket_connect_timeout=3,
socket_timeout=3,
)
client.ping()
with urllib.request.urlopen(minio_url, timeout=3) as response:
if response.status != 200:
raise RuntimeError(f"minio {response.status}")
print("dependencies ready", flush=True)
break
except Exception as exc:
last = str(exc)
time.sleep(3)
else:
raise SystemExit(f"dependencies not ready: {last}")
PY
workers="${UVICORN_WORKERS:-1}"
exec python -m uvicorn app.main:app \
--host 0.0.0.0 \
--port 8000 \
--workers "$workers" \
--proxy-headers \
--forwarded-allow-ips "*" \
--no-access-log
+7
View File
@@ -11,4 +11,11 @@ redis==6.4.0
minio==7.2.18
bcrypt==5.0.0
pillow==11.3.0
pypdf==6.21.4
xlrd==2.0.1
xlwt==1.3.0
python-multipart==0.0.20
python-pptx==1.0.2
python-docx==1.2.0
lxml==6.1.3
XlsxWriter==3.3.4
+334
View File
@@ -0,0 +1,334 @@
"""智能体登录使用门户注册用户。勾选允许后才能进入,admin 与用户管理是同一条记录。"""
import os
import re
import uuid
from datetime import datetime, timezone
import pytest
from fastapi.testclient import TestClient
from sqlalchemy import select, text
from sqlalchemy.orm import Session
os.environ["JWT_SECRET"] = "test-secret-must-be-32-characters!"
os.environ["API_PAYLOAD_ENCRYPT"] = "false"
from app.commands.create_superuser import seed_superuser
from app.core.config import get_settings
from app.core.security import create_access_token
from app.db import Base, get_db, get_engine
from app.main import create_app
from app.models.member import create_member
from app.models.agent_user import AGENT_ADMIN_ROLE_CODE
from app.models.rbac import AdminResource, AdminRole, AdminRoleResource, AdminUser, AdminUserRole
from app.services.password import hash_password, verify_password
get_settings.cache_clear()
def _safe_error(exc: Exception) -> str:
raw = str(exc).splitlines()[0] if str(exc) else ""
raw = re.sub(r"://\S+", "://***", raw)
raw = re.sub(r"password=\S+", "password=***", raw, flags=re.I)
return f"{exc.__class__.__name__}: {raw[:180]}"
def _suffix(prefix: str) -> str:
return f"{prefix}-{uuid.uuid4().hex[:10]}"
def _staff_headers(subject: str = "1") -> dict[str, str]:
return {"Authorization": f"Bearer {create_access_token(subject, 'staff')}"}
def _session(client: TestClient) -> Session:
return Session(
bind=client.app.state.connection,
autoflush=False,
expire_on_commit=False,
join_transaction_mode="create_savepoint",
)
@pytest.fixture
def client():
get_settings.cache_clear()
if not get_settings().database_url.strip():
pytest.skip("DATABASE_URL 未配置")
os.environ["API_PAYLOAD_ENCRYPT"] = "false"
get_settings.cache_clear()
try:
engine = get_engine()
with engine.connect() as probe:
probe.execute(text("SELECT 1"))
Base.metadata.create_all(bind=engine)
except Exception as exc:
pytest.skip(f"数据库不可用:{_safe_error(exc)}")
connection = engine.connect()
transaction = connection.begin()
try:
app = create_app()
app.state.connection = connection
def override_db():
db = Session(
bind=connection,
autoflush=False,
expire_on_commit=False,
join_transaction_mode="create_savepoint",
)
try:
yield db
finally:
db.close()
app.dependency_overrides[get_db] = override_db
with TestClient(app) as test_client:
yield test_client
finally:
try:
transaction.rollback()
except Exception:
pass
connection.close()
def _grant_agent_admin(client: TestClient, user_id: int) -> None:
db = _session(client)
try:
role = db.scalar(select(AdminRole).where(AdminRole.code == AGENT_ADMIN_ROLE_CODE))
if role is None:
now = datetime.now(timezone.utc)
role = AdminRole(
code=AGENT_ADMIN_ROLE_CODE,
name="智能体管理员",
description="可管理估价智能体的推荐问题和报告模版",
status="active",
created_at=now,
updated_at=now,
)
db.add(role)
db.flush()
if db.get(AdminUserRole, (user_id, role.id)) is None:
db.add(AdminUserRole(user_id=user_id, role_id=role.id))
db.commit()
finally:
db.close()
def _pin_staff(client: TestClient, user_id: int) -> None:
db = _session(client)
try:
db.execute(
text(
"INSERT INTO agent_admin_link (id, admin_user_id) VALUES (1, :admin_id) "
"ON DUPLICATE KEY UPDATE admin_user_id = :admin_id"
),
{"admin_id": user_id},
)
db.commit()
finally:
db.close()
def test_portal_member_needs_agent_flag(client: TestClient):
headers = _staff_headers()
password = "Passw0rd1"
db = _session(client)
try:
member = create_member(
db,
email=f"{_suffix('portal')}@example.com",
password_hash=hash_password(password),
privacy_accepted_at=datetime.now(timezone.utc).replace(tzinfo=None),
)
member_id = member.id
member_email = member.email
finally:
db.close()
portal = client.post("/api/site/auth/login", json={"email": member_email, "password": password})
assert portal.status_code == 200, portal.text
member_headers = {"Authorization": f"Bearer {portal.json()['accessToken']}"}
assert client.post("/api/site/member/valuation/sessions", headers=member_headers).status_code == 403
blocked = client.post("/api/site/auth/agent-login", json={"username": member_email, "password": password})
assert blocked.status_code == 403, blocked.text
assert client.post(
"/api/site/auth/agent-login",
json={"username": member_email, "password": "wrong-pass"},
).status_code == 401
enabled = client.put(
f"/api/admin/site-members/{member_id}",
headers=headers,
json={"email": member_email, "status": "active", "agentEnabled": True},
)
assert enabled.status_code == 200, enabled.text
assert enabled.json()["agentEnabled"] is True
assert enabled.json()["builtin"] is False
logged_in = client.post("/api/site/auth/agent-login", json={"username": member_email, "password": password})
assert logged_in.status_code == 200, logged_in.text
assert logged_in.json()["tokenType"] == "agent"
agent_headers = {"Authorization": f"Bearer {logged_in.json()['accessToken']}"}
session = client.post("/api/site/member/valuation/sessions", headers=agent_headers)
assert session.status_code == 201, session.text
disabled = client.put(
f"/api/admin/site-members/{member_id}",
headers=headers,
json={"email": member_email, "status": "active", "agentEnabled": False},
)
assert disabled.status_code == 200
assert client.get("/api/site/auth/agent/me", headers=agent_headers).status_code == 401
def test_builtin_admin_is_listed_with_site_members(client: TestClient):
headers = _staff_headers()
username = _suffix("staffadmin")
password = "Staffpass1"
db = _session(client)
try:
now = datetime.now(timezone.utc)
user = AdminUser(
username=username,
password_hash=hash_password(password),
display_name="同步前",
mobile_mask="",
status="active",
failed_login_count=0,
created_at=now,
updated_at=now,
)
db.add(user)
db.commit()
db.refresh(user)
user_id = user.id
finally:
db.close()
_pin_staff(client, user_id)
listed = client.get("/api/admin/site-members", headers=headers, params={"email": username})
assert listed.status_code == 200, listed.text
assert listed.json()["total"] == 1
assert listed.json()["records"][0]["id"] == f"staff-{user_id}"
assert listed.json()["records"][0]["builtin"] is True
assert listed.json()["records"][0]["agentEnabled"] is True
logged_in = client.post("/api/site/auth/agent-login", json={"username": username, "password": password})
assert logged_in.status_code == 200, logged_in.text
me = client.get(
"/api/site/auth/agent/me",
headers={"Authorization": f"Bearer {logged_in.json()['accessToken']}"},
)
assert me.status_code == 200
assert me.json()["canManage"] is False
assert me.json()["username"] == username
_grant_agent_admin(client, user_id)
granted = client.get("/api/site/auth/agent/me", headers={"Authorization": f"Bearer {logged_in.json()['accessToken']}"})
assert granted.status_code == 200
assert granted.json()["canManage"] is True
updated = client.put(
f"/api/admin/site-members/staff-{user_id}",
headers=headers,
json={"email": username, "displayName": "同步后", "status": "active", "password": "Staffpass2", "agentEnabled": False},
)
assert updated.status_code == 200, updated.text
assert updated.json()["displayName"] == "同步后"
assert updated.json()["agentEnabled"] is False
db = _session(client)
try:
stored = db.get(AdminUser, user_id)
assert stored is not None
assert stored.display_name == "同步后"
assert verify_password("Staffpass2", stored.password_hash)
finally:
db.close()
again = client.post("/api/site/auth/agent-login", json={"username": username, "password": "Staffpass2"})
assert again.status_code == 403, again.text
removed = client.delete(f"/api/admin/site-members/staff-{user_id}", headers=headers)
assert removed.status_code == 400
def test_logged_in_staff_opens_agent_market(client: TestClient):
username = _suffix("desk")
db = _session(client)
try:
now = datetime.now(timezone.utc)
user = AdminUser(
username=username,
password_hash=hash_password("Deskpass1"),
display_name="值班员",
mobile_mask="",
status="active",
failed_login_count=0,
created_at=now,
updated_at=now,
)
db.add(user)
db.commit()
db.refresh(user)
user_id = user.id
finally:
db.close()
headers = {"Authorization": f"Bearer {create_access_token(str(user_id), 'staff')}"}
issued = client.post("/api/admin/auth/agent-session", headers=headers)
assert issued.status_code == 200, issued.text
assert issued.json()["username"] == username
assert issued.json()["displayName"] == "值班员"
agent_headers = {"Authorization": f"Bearer {issued.json()['accessToken']}"}
me = client.get("/api/site/auth/agent/me", headers=agent_headers)
assert me.status_code == 200, me.text
assert me.json()["username"] == username
assert me.json()["canManage"] is False
opened = client.post("/api/site/member/valuation/sessions", headers=agent_headers)
assert opened.status_code == 201, opened.text
assert client.post("/api/admin/auth/agent-session").status_code == 401
def test_agent_market_menu_replaces_agent_user_menu(client: TestClient):
db = _session(client)
try:
seed_superuser(db, _suffix("boot"), "Seedpass1")
db.commit()
system = db.scalar(
select(AdminResource).where(AdminResource.parent_id.is_(None), AdminResource.name == "System")
)
assert system is not None
system_pages = list(
db.scalars(
select(AdminResource).where(
AdminResource.parent_id == system.id,
AdminResource.type == "menu",
AdminResource.status == "active",
)
).all()
)
assert all(item.name != "AgentUser" for item in system_pages)
directory = db.scalar(
select(AdminResource).where(AdminResource.parent_id.is_(None), AdminResource.name == "AiAgent")
)
assert directory is not None
page = db.scalar(
select(AdminResource).where(
AdminResource.parent_id == directory.id,
AdminResource.name == "AiAgentMarket",
)
)
assert page is not None
assert page.title == "智能体市场"
assert page.path == "/dify/market"
assert page.component == "/dify/market"
assert page.sort == 0
role = db.scalar(select(AdminRole).where(AdminRole.code == "R_SUPER"))
assert role is not None
linked = set(
db.scalars(select(AdminRoleResource.resource_id).where(AdminRoleResource.role_id == role.id)).all()
)
assert page.id in linked
finally:
db.close()
+233
View File
@@ -0,0 +1,233 @@
"""管理端门户注册用户:列表、查看、编辑、删除,以及系统管理菜单。"""
import os
import re
import uuid
from datetime import datetime, timezone
import pytest
from fastapi.testclient import TestClient
from sqlalchemy import select, text
from sqlalchemy.orm import Session
os.environ["JWT_SECRET"] = "test-secret-must-be-32-characters!"
os.environ["API_PAYLOAD_ENCRYPT"] = "false"
from app.commands.create_superuser import seed_superuser
from app.core.config import get_settings
from app.core.security import create_access_token
from app.db import Base, get_db, get_engine
from app.main import create_app
from app.models.member import create_member
from app.models.rbac import AdminResource, AdminRole, AdminRoleResource
from app.services.password import hash_password
get_settings.cache_clear()
def _safe_error(exc: Exception) -> str:
raw = str(exc).splitlines()[0] if str(exc) else ""
raw = re.sub(r"://\S+", "://***", raw)
raw = re.sub(r"password=\S+", "password=***", raw, flags=re.I)
return f"{exc.__class__.__name__}: {raw[:180]}"
def _suffix(prefix: str) -> str:
return f"{prefix}-{uuid.uuid4().hex[:10]}"
def _staff_headers(subject: str = "1") -> dict[str, str]:
return {"Authorization": f"Bearer {create_access_token(subject, 'staff')}"}
def _session(client: TestClient) -> Session:
return Session(
bind=client.app.state.connection,
autoflush=False,
expire_on_commit=False,
join_transaction_mode="create_savepoint",
)
def _add_member(client: TestClient, email: str, password: str = "Passw0rd1") -> int:
db = _session(client)
try:
row = create_member(
db,
email=email,
password_hash=hash_password(password),
privacy_accepted_at=datetime.now(timezone.utc).replace(tzinfo=None),
)
return row.id
finally:
db.close()
@pytest.fixture
def client():
get_settings.cache_clear()
if not get_settings().database_url.strip():
pytest.skip("DATABASE_URL 未配置")
os.environ["API_PAYLOAD_ENCRYPT"] = "false"
get_settings.cache_clear()
try:
engine = get_engine()
with engine.connect() as probe:
probe.execute(text("SELECT 1"))
Base.metadata.create_all(bind=engine)
except Exception as exc:
pytest.skip(f"数据库不可用:{_safe_error(exc)}")
connection = engine.connect()
transaction = connection.begin()
try:
app = create_app()
app.state.connection = connection
def override_db():
db = Session(
bind=connection,
autoflush=False,
expire_on_commit=False,
join_transaction_mode="create_savepoint",
)
try:
yield db
finally:
db.close()
app.dependency_overrides[get_db] = override_db
with TestClient(app) as test_client:
yield test_client
finally:
try:
transaction.rollback()
except Exception:
pass
connection.close()
def test_site_members_require_staff(client: TestClient):
missing = client.get("/api/admin/site-members")
assert missing.status_code == 401
member = create_access_token("9", "member")
rejected = client.get("/api/admin/site-members", headers={"Authorization": f"Bearer {member}"})
assert rejected.status_code == 403
def test_list_view_edit_and_delete_site_member(client: TestClient):
headers = _staff_headers()
email = _suffix("member") + "@example.com"
other = _suffix("other") + "@example.com"
member_id = _add_member(client, email)
_add_member(client, other)
listed = client.get("/api/admin/site-members", headers=headers, params={"email": email, "current": 1, "size": 10})
assert listed.status_code == 200, listed.text
body = listed.json()
assert body["total"] == 1
record = body["records"][0]
assert record["id"] == member_id
assert record["email"] == email
assert record["status"] == "active"
assert record["privacyAcceptedAt"]
assert "password" not in record
assert "password_hash" not in listed.text
detail = client.get(f"/api/admin/site-members/{member_id}", headers=headers)
assert detail.status_code == 200
assert detail.json()["email"] == email
assert "password" not in detail.json()
renamed = _suffix("renamed") + "@example.com"
updated = client.put(
f"/api/admin/site-members/{member_id}",
headers=headers,
json={"email": renamed, "status": "disabled", "password": "Newpass12"},
)
assert updated.status_code == 200, updated.text
assert updated.json()["email"] == renamed
assert updated.json()["status"] == "disabled"
assert "password" not in updated.json()
blocked = client.post("/api/site/auth/login", json={"email": renamed, "password": "Newpass12"})
assert blocked.status_code == 401
restored = client.put(
f"/api/admin/site-members/{member_id}",
headers=headers,
json={"email": renamed, "status": "active"},
)
assert restored.status_code == 200, restored.text
signed_in = client.post("/api/site/auth/login", json={"email": renamed, "password": "Newpass12"})
assert signed_in.status_code == 200, signed_in.text
duplicate = client.put(
f"/api/admin/site-members/{member_id}",
headers=headers,
json={"email": other, "status": "active"},
)
assert duplicate.status_code == 400
assert duplicate.json()["detail"] == "该邮箱已注册"
weak = client.put(
f"/api/admin/site-members/{member_id}",
headers=headers,
json={"email": renamed, "status": "active", "password": "short"},
)
assert weak.status_code == 400
missing = client.get("/api/admin/site-members/99999999", headers=headers)
assert missing.status_code == 404
removed = client.delete(f"/api/admin/site-members/{member_id}", headers=headers)
assert removed.status_code == 200, removed.text
gone = client.get(f"/api/admin/site-members/{member_id}", headers=headers)
assert gone.status_code == 404
listed_again = client.get("/api/admin/site-members", headers=headers, params={"email": renamed})
assert listed_again.json()["total"] == 0
def test_site_member_menu_is_last_under_system(client: TestClient):
db = _session(client)
try:
seed_superuser(db, _suffix("boot"), "Seedpass1")
db.commit()
directory = db.scalar(
select(AdminResource).where(AdminResource.parent_id.is_(None), AdminResource.name == "System")
)
assert directory is not None
pages = list(
db.scalars(
select(AdminResource).where(
AdminResource.parent_id == directory.id,
AdminResource.type == "menu",
AdminResource.status == "active",
)
).all()
)
page = next(item for item in pages if item.name == "SiteMember")
assert all(item.name != "AgentUser" for item in pages)
assert page.title == "门户网站注册用户"
assert page.path == "/system/site-member"
assert page.component == "/system/site-member"
assert page.sort == max(item.sort or 0 for item in pages)
buttons = list(
db.scalars(select(AdminResource).where(AdminResource.parent_id == page.id).order_by(AdminResource.sort)).all()
)
assert [item.permission for item in buttons] == [
"site-member:view",
"site-member:edit",
"site-member:delete",
]
role = db.scalar(select(AdminRole).where(AdminRole.code == "R_SUPER"))
assert role is not None
linked = set(
db.scalars(
select(AdminRoleResource.resource_id).where(AdminRoleResource.role_id == role.id)
).all()
)
assert page.id in linked
assert all(item.id in linked for item in buttons)
finally:
db.close()
+12 -7
View File
@@ -747,16 +747,21 @@ def test_ensure_ai_agent_menu_removes_duplicate_roots(client: TestClient):
assert home is not None
assert home.status == "cancelled"
assert home.visible is False
marketplace = db.scalar(
select(AdminResource).where(
AdminResource.parent_id == first.id,
AdminResource.name == "AiAgentMarketplace",
)
)
assert marketplace is not None
assert marketplace.status == "active"
assert marketplace.visible is True
tree = list_resource_tree(db)
ai_nodes = [node for node in tree if node["name"] == "AiAgent"]
assert len(ai_nodes) == 1
# Soft-deleted menus must not appear in menu-admin tree.
home_titles = [
child["title"]
for child in (ai_nodes[0].get("children") or [])
if child["name"] == "AiAgentHome"
]
assert home_titles == []
child_names = {child["name"] for child in (ai_nodes[0].get("children") or [])}
assert "AiAgentHome" not in child_names
assert "AiAgentMarketplace" in child_names
finally:
db.close()
+706
View File
@@ -0,0 +1,706 @@
"""智能估价会话与推荐问题。使用独立 SQLite,不连接业务库。"""
import io
import json
import zipfile
from urllib.parse import unquote
import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient
from sqlalchemy import create_engine
from sqlalchemy.orm import Session
from sqlalchemy.pool import StaticPool
from app.api.site.valuation import router
from app.core.config import get_settings
from app.core.security import create_access_token
from app.db import Base, get_db
from app.models.agent_user import AgentAdminLink
from app.models.member import SiteMember
from app.models.agent_user import AGENT_ADMIN_ROLE_CODE
from app.models.rbac import AdminRole, AdminUser, AdminUserRole
from app.models.valuation import (
ValuationFile,
ValuationMessage,
ValuationSession,
ValuationSuggestion,
ValuationTemplate,
)
from app.services.dify_chat import apply_dify_event, cited_documents
from app.services.valuation_context import (
ANSWER_NOTE,
build_docx,
build_pptx,
compose_query,
draft_prompt,
draft_title,
ensure_answer_note,
extract_excerpt,
peel_free_format,
parse_search_snippets,
wants_document,
)
@pytest.fixture
def client(monkeypatch):
monkeypatch.setenv("JWT_SECRET", "test-secret-must-be-32-characters!")
get_settings.cache_clear()
engine = create_engine("sqlite://", connect_args={"check_same_thread": False}, poolclass=StaticPool)
tables = [
m.__table__
for m in (
SiteMember,
AgentAdminLink,
AdminUser,
AdminRole,
AdminUserRole,
ValuationSession,
ValuationMessage,
ValuationFile,
ValuationSuggestion,
ValuationTemplate,
)
]
Base.metadata.create_all(engine, tables=tables)
with Session(engine) as db:
db.add(
SiteMember(
id=1,
email="estimator@example.com",
password_hash="x",
status="active",
agent_enabled=True,
)
)
db.add(AdminUser(id=1, username="admin", password_hash="x", display_name="管理员", status="active"))
db.add(AdminUser(id=2, username="clerk", password_hash="x", display_name="工作人员", status="active"))
role = AdminRole(id=1, code=AGENT_ADMIN_ROLE_CODE, name="智能体管理员", status="active")
db.add(role)
db.flush()
db.add(AdminUserRole(user_id=1, role_id=role.id))
db.commit()
def database():
with Session(engine) as db:
yield db
app = FastAPI()
app.include_router(router, prefix="/api/site/member/valuation")
app.dependency_overrides[get_db] = database
return TestClient(app)
def token(owner: str) -> dict:
return {"Authorization": f"Bearer {create_access_token(owner, 'agent')}"}
def test_document_request_is_separate_from_ordinary_questions():
assert wants_document("请帮忙生成一份估值说明")
assert wants_document("请按模版生成文档")
assert wants_document("请生成一份PPT")
assert wants_document("请生成一份估价参数表")
assert not wants_document("华润三九估值报告的评估对象是什么?")
prompt = draft_prompt(
template_name="住宅草稿",
outline="一、评估对象概述",
question="请帮忙生成一份估值说明",
file_excerpts=[],
web=False,
web_snippets=[],
)
assert "检索知识库" in prompt
assert "【本次要求】请帮忙生成一份估值说明" in prompt
assert "【会话】" not in prompt
assert "不要把此前会话闲聊写入正文" in prompt
plain = draft_prompt(
template_name="",
outline="",
question="请帮忙生成一份说明",
file_excerpts=[],
web=False,
web_snippets=[],
)
assert "未指定" in plain
assert "格式:pptx" in plain
assert "格式:xlsx" in plain
assert "只能是 Word 或 PPT" not in plain
assert peel_free_format("格式:pptx\n第1页\n估价方法", finished=False) == ("pptx", "第1页\n估价方法")
assert peel_free_format("格式:xlsx\n项目|内容", finished=False) == ("xlsx", "项目|内容")
assert peel_free_format("一、评估对象", finished=True) == ("docx", "一、评估对象")
assert peel_free_format("项目|内容", finished=True, question="请生成一份参数表")[0] == "xlsx"
assert draft_title("住宅估价说明", "请帮忙生成一份别的") == "住宅估价说明"
assert draft_title("", "请帮忙生成一份住宅估价说明") == "住宅估价说明"
assert draft_title("", "请生成一份估价参数表") == "估价参数表"
def test_compose_query_marks_web_and_files():
plain = compose_query("评估对象是什么?", file_names=[], web=False, web_snippets=[])
assert plain == "评估对象是什么?"
mixed = compose_query("看附件", file_names=["报告.pdf"], web=True, web_snippets=["公开信息"])
assert "【附件】报告.pdf" in mixed
assert "【联网摘录】" in mixed
assert "公开信息" in mixed
def test_extract_excerpt_reads_plain_text():
assert "测试厂房" in extract_excerpt("txt", "评估对象:测试厂房。".encode())
assert "测试厂房" in extract_excerpt("csv", "机构,对象\n甘肃,测试厂房".encode("gb18030"))
def test_extract_excerpt_reads_office_files():
assert "测试厂房" in extract_excerpt("docx", build_docx("评估对象:测试厂房。"))
workbook = extract_excerpt("xlsx", _xlsx_with_text("评估对象", "测试厂房"))
assert "测试厂房" in workbook
assert "80万元" in workbook
assert "测试厂房" in extract_excerpt("xls", _xls_with_text("评估对象", "测试厂房"))
slides = extract_excerpt("pptx", _sample_pptx(), limit=8000)
assert "第1页" in slides
assert "住宅坐落" in slides
assert "必须写权属" in slides
assert "第2页" in slides
assert "估价结果" in slides
assert "图片附件" in extract_excerpt("png", b"\x89PNG")
assert "图片附件" in extract_excerpt("jpg", b"\xff\xd8")
assert "图片附件" in extract_excerpt("webp", b"RIFF")
def test_docx_renders_markdown_as_headings_and_paragraphs():
payload = build_docx("# 估价说明\n\n## 一、评估对象概述\n\n正文一段。\n\n- 坐落:待补充\n\n**关键词**说明")
xml = zipfile.ZipFile(io.BytesIO(payload)).read("word/document.xml").decode("utf-8")
assert "Heading1" in xml
assert "Heading2" in xml
assert "ListBullet" in xml
assert "**" not in xml
assert "评估对象概述" in extract_excerpt("docx", payload)
def test_extract_excerpt_reads_pdf_text():
text = extract_excerpt("pdf", _text_pdf("Project LGZB-2026-526"))
assert "LGZB-2026-526" in text
assert "FlateDecode" not in text
def test_pptx_drops_preamble_before_the_first_page():
payload = build_pptx(
"知识库中未检索到本次住宅估价相关的报告内容,以下各页信息均无法从知识库取得依据,一律标注为「待补充」。\n"
"待补充\n"
"第1页\n"
"住宅坐落与权属\n"
"- 住宅坐落:待补充\n"
"第2页\n"
"住宅比较案例\n"
"- 比较案例一:名称待补充\n"
)
titles = _pptx_titles(payload)
assert titles == ["住宅坐落与权属", "住宅比较案例"]
assert "知识库中未检索到" not in "\n".join(titles)
def _pptx_titles(payload: bytes) -> list[str]:
import html
import re
titles = []
with zipfile.ZipFile(io.BytesIO(payload)) as archive:
names = sorted(
name
for name in archive.namelist()
if name.startswith("ppt/slides/slide") and name.endswith(".xml")
)
for name in names:
xml = archive.read(name).decode("utf-8", "ignore")
texts = [
html.unescape("".join(re.findall(r"<a:t[^>]*>(.*?)</a:t>", paragraph)))
for paragraph in re.findall(r"<a:p\b.*?</a:p>", xml, flags=re.DOTALL)
]
titles.append(next(text.strip() for text in texts if text.strip()))
return titles
def _sample_pptx() -> bytes:
from pptx import Presentation
presentation = Presentation()
layout = presentation.slide_layouts[1]
first = presentation.slides.add_slide(layout)
first.shapes.title.text = "住宅坐落"
first.placeholders[1].text = "写明地址"
first.notes_slide.notes_text_frame.text = "必须写权属"
second = presentation.slides.add_slide(layout)
second.shapes.title.text = "估价结果"
second.placeholders[1].text = "写明总价"
buffer = io.BytesIO()
presentation.save(buffer)
return buffer.getvalue()
def _text_pdf(message: str) -> bytes:
stream = f"BT /F1 12 Tf 36 100 Td ({message}) Tj ET\n".encode("ascii")
objects = [
b"1 0 obj<</Type/Catalog/Pages 2 0 R>>endobj\n",
b"2 0 obj<</Type/Pages/Count 1/Kids[3 0 R]>>endobj\n",
b"3 0 obj<</Type/Page/Parent 2 0 R/MediaBox[0 0 300 144]/Contents 4 0 R/Resources<</Font<</F1 5 0 R>>>>>>endobj\n",
b"<< /Length " + str(len(stream)).encode("ascii") + b" >>\nstream\n" + stream + b"endstream\nendobj\n",
b"5 0 obj<</Type/Font/Subtype/Type1/BaseFont/Helvetica>>endobj\n",
]
objects[3] = b"4 0 obj" + objects[3]
body = bytearray(b"%PDF-1.4\n")
offsets = [0]
for item in objects:
offsets.append(len(body))
body.extend(item)
xref = len(body)
body.extend(f"xref\n0 {len(offsets)}\n".encode("ascii"))
body.extend(b"0000000000 65535 f \n")
for offset in offsets[1:]:
body.extend(f"{offset:010d} 00000 n \n".encode("ascii"))
body.extend(f"trailer<</Size {len(offsets)}/Root 1 0 R>>\nstartxref\n{xref}\n%%EOF\n".encode("ascii"))
return bytes(body)
def _xlsx_with_text(label: str, value: str) -> bytes:
import io
import zipfile
shared = (
'<?xml version="1.0" encoding="UTF-8"?>'
'<sst xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" count="2" uniqueCount="2">'
f"<si><t>{label}</t></si><si><t>{value}</t></si></sst>"
)
sheet = (
'<?xml version="1.0" encoding="UTF-8"?>'
'<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><sheetData>'
'<row r="1"><c r="A1" t="s"><v>0</v></c><c r="B1" t="inlineStr"><is><t>80万元</t></is></c></row>'
'<row r="2"><c r="A2" t="s"><v>1</v></c></row>'
"</sheetData></worksheet>"
)
buffer = io.BytesIO()
with zipfile.ZipFile(buffer, "w") as archive:
archive.writestr("xl/sharedStrings.xml", shared)
archive.writestr("xl/worksheets/sheet1.xml", sheet)
return buffer.getvalue()
def _xls_with_text(label: str, value: str) -> bytes:
import io
import xlwt
book = xlwt.Workbook()
sheet = book.add_sheet("名录")
sheet.write(0, 0, label)
sheet.write(0, 1, value)
buffer = io.BytesIO()
book.save(buffer)
return buffer.getvalue()
def test_parse_search_snippets_reads_results():
html = (
'<h3 class="vr-title"><a href="https://example.com/a"><em>学会简介</em></a></h3>'
'<div class="card_normal_result__summary_1a50">英文缩写为 CIREA。详情</div>'
'<h3 class="vr-title"><a href="https://example.com/a">重复</a></h3>'
'<div class="card_normal_result__summary_1a50">重复结果</div>'
)
assert parse_search_snippets(html) == ["学会简介 英文缩写为 CIREA。 来源:https://example.com/a"]
so_html = (
'<h3 class="res-title"><a data-mdurl="https://example.com/b" href="https://www.so.com/link?m=1">学会</a></h3>'
'<div class="res-desc"><span>英文缩写 CIREA。</span></div>'
)
assert parse_search_snippets(so_html) == ["学会 英文缩写 CIREA。 来源:https://example.com/b"]
def test_attachment_and_knowledge_sources_are_labeled():
assert cited_documents(
["数据治理平台建设.pdf"],
["03-华润三九-估值报告.pdf"],
) == [
{"name": "数据治理平台建设.pdf", "kind": "attachment"},
{"name": "03-华润三九-估值报告.pdf", "kind": "knowledge"},
]
assert cited_documents([], ["03-华润三九-估值报告.pdf"]) == [
{"name": "03-华润三九-估值报告.pdf", "kind": "knowledge"},
]
assert cited_documents(["数据治理平台建设.pdf"], []) == [
{"name": "数据治理平台建设.pdf", "kind": "attachment"},
]
def test_message_end_lists_source_documents():
state = {"answer": "", "thoughts": {}, "conversation_id": ""}
events = apply_dify_event(
{
"event": "message_end",
"conversation_id": "c1",
"metadata": {
"retriever_resources": [
{"document_name": "日播时尚估值报告.pdf", "score": 0.9},
{"document_name": "日播时尚估值报告.pdf", "score": 0.4},
{"document_name": "华润三九评估说明.docx", "score": 0.7},
{"document_name": " ", "score": 0.1},
]
},
},
state,
)
sources = next(item for item in events if item["type"] == "sources")
assert sources["documents"] == ["日播时尚估值报告.pdf", "华润三九评估说明.docx"]
def test_apply_dify_event_hides_think_tags():
from app.services.dify_chat import apply_dify_event, split_stored_reasoning
state = {"answer": "", "thoughts": {}, "conversation_id": ""}
first = apply_dify_event({"event": "message", "answer": "<thi"}, state)
assert first == []
second = apply_dify_event({"event": "message", "answer": "nk>先核对基准日</think>结论是 2"}, state)
assert "".join(item["text"] for item in second if item["type"] == "delta") == "结论是 2"
assert any(item["type"] == "thought" and "先核对基准日" in item["text"] for item in second)
assert "<think>" not in state["answer"]
visible, thought = split_stored_reasoning(
"<think>\n<!--dify-deepseek-reasoning-->推理</think>正式结论",
"",
)
assert visible == "正式结论"
assert "推理" in thought
assert "dify-deepseek-reasoning" not in thought
def test_apply_dify_event_collects_answer_and_thought():
state = {"answer": "", "thoughts": {}, "conversation_id": ""}
assert apply_dify_event({"event": "agent_thought", "id": "t1", "thought": "先检索"}, state)[0]["type"] == "thought"
assert apply_dify_event({"event": "message", "answer": "结论", "conversation_id": "c1"}, state)[0]["text"] == "结论"
done = apply_dify_event({"event": "message_end", "conversation_id": "c1"}, state)
assert done[-1]["conversationId"] == "c1"
assert state["answer"] == "结论"
def test_sessions_are_private_and_start_with_welcome(client):
member = {"Authorization": f"Bearer {create_access_token('1', 'member')}"}
assert client.post("/api/site/member/valuation/sessions", headers=member).status_code == 403
created = client.post("/api/site/member/valuation/sessions", headers=token("m:1"))
assert created.status_code == 201
session_id = created.json()["id"]
assert created.json()["title"] == "新会话"
messages = client.get(f"/api/site/member/valuation/sessions/{session_id}/messages", headers=token("m:1"))
assert messages.status_code == 200
assert messages.json()["items"][0]["role"] == "assistant"
assert client.get(f"/api/site/member/valuation/sessions/{session_id}/messages", headers=token("s:1")).status_code == 404
def test_rename_and_delete_only_owner(client):
session_id = client.post("/api/site/member/valuation/sessions", headers=token("m:1")).json()["id"]
renamed = client.patch(
f"/api/site/member/valuation/sessions/{session_id}",
headers=token("m:1"),
json={"title": "日播时尚"},
)
assert renamed.status_code == 200
assert renamed.json()["title"] == "日播时尚"
assert client.delete(f"/api/site/member/valuation/sessions/{session_id}", headers=token("s:1")).status_code == 404
assert client.delete(f"/api/site/member/valuation/sessions/{session_id}", headers=token("m:1")).status_code == 204
assert client.get("/api/site/member/valuation/sessions", headers=token("m:1")).json()["items"] == []
def test_member_cannot_change_suggestions_admin_can(client):
assert client.post(
"/api/site/member/valuation/suggestions",
headers=token("m:1"),
json={"text": "新问题"},
).status_code == 403
created = client.post(
"/api/site/member/valuation/suggestions",
headers=token("s:1"),
json={"text": "新问题"},
)
assert created.status_code == 201
public = client.get("/api/site/member/valuation/bootstrap", headers=token("m:1")).json()
assert any(item["text"] == "新问题" for item in public["suggestions"])
assert public["canManage"] is False
assert client.get("/api/site/member/valuation/bootstrap", headers=token("s:1")).json()["canManage"] is True
assert client.get("/api/site/member/valuation/bootstrap", headers=token("s:2")).json()["canManage"] is False
assert client.post(
"/api/site/member/valuation/suggestions",
headers=token("s:2"),
json={"text": "工作人员不能改"},
).status_code == 403
def test_rejects_unsupported_attachment_and_unknown_file(client):
rejected = client.post(
"/api/site/member/valuation/files",
headers=token("m:1"),
files={"file": ("note.gif", b"GIF89a", "image/gif")},
)
assert rejected.status_code == 400
session_id = client.post("/api/site/member/valuation/sessions", headers=token("m:1")).json()["id"]
missing = client.post(
f"/api/site/member/valuation/sessions/{session_id}/messages",
headers=token("m:1"),
json={"query": "看一下", "fileIds": [99]},
)
assert missing.status_code == 404
def test_template_upload_is_admin_only_and_draft_keeps_risk_line(client, monkeypatch):
monkeypatch.setattr("app.api.site.valuation.upload_object", lambda *args, **kwargs: None)
monkeypatch.setattr("app.api.site.valuation.read_upload_limit", lambda db: 10 * 1024 * 1024)
payload = build_docx("一、评估对象概述\n二、价值类型")
rejected = client.post(
"/api/site/member/valuation/templates",
headers=token("m:1"),
data={"name": "住宅草稿"},
files={"file": ("house.docx", payload, "application/vnd.openxmlformats-officedocument.wordprocessingml.document")},
)
assert rejected.status_code == 403
created = client.post(
"/api/site/member/valuation/templates",
headers=token("s:1"),
data={"name": "住宅草稿"},
files={"file": ("house.docx", payload, "application/vnd.openxmlformats-officedocument.wordprocessingml.document")},
)
assert created.status_code == 201
assert created.json()["format"] == "docx"
template_id = created.json()["id"]
session_id = client.post("/api/site/member/valuation/sessions", headers=token("m:1")).json()["id"]
def fake_stream(**kwargs):
assert kwargs["conversation_id"] == ""
assert "住宅草稿" in kwargs["query"]
assert "评估对象概述" in kwargs["query"]
assert "【会话】" not in kwargs["query"]
assert "检索知识库" in kwargs["query"]
yield {"type": "delta", "text": "一、评估对象概述\n待补充"}
yield {"type": "done", "conversationId": "draft-1"}
monkeypatch.setattr("app.api.site.valuation.iter_dify_chat", fake_stream)
response = client.post(
f"/api/site/member/valuation/sessions/{session_id}/drafts",
headers=token("m:1"),
json={"templateId": template_id, "query": "请帮忙生成一份估值说明"},
)
assert response.status_code == 200
saved = client.get(f"/api/site/member/valuation/sessions/{session_id}/messages", headers=token("m:1")).json()["items"][-1]
assert saved["kind"] == "draft"
assert "不构成正式评估意见" in saved["content"]
download = client.get(
f"/api/site/member/valuation/sessions/{session_id}/messages/{saved['id']}/docx",
headers=token("m:1"),
)
assert download.status_code == 200
assert download.content.startswith(b"PK")
assert saved["draftName"] == "住宅草稿"
assert "住宅草稿.docx" in unquote(download.headers["content-disposition"])
stored = client.get(f"/api/site/member/valuation/sessions/{session_id}/messages", headers=token("m:1")).json()["items"]
assert stored[-2]["role"] == "user"
assert stored[-2]["content"] == "请帮忙生成一份估值说明"
def fake_plain(**kwargs):
assert kwargs["conversation_id"] == ""
assert "未指定" in kwargs["query"]
assert "请帮忙生成一份说明" in kwargs["query"]
yield {"type": "delta", "text": "普通文档正文"}
yield {"type": "done", "conversationId": "draft-2"}
monkeypatch.setattr("app.api.site.valuation.iter_dify_chat", fake_plain)
plain = client.post(
f"/api/site/member/valuation/sessions/{session_id}/drafts",
headers=token("m:1"),
json={"query": "请帮忙生成一份说明"},
)
assert plain.status_code == 200
assert client.get(
f"/api/site/member/valuation/sessions/{session_id}/messages/{saved['id']}/docx",
headers=token("s:1"),
).status_code == 404
assert client.patch(
f"/api/site/member/valuation/templates/{template_id}",
headers=token("s:1"),
json={"enabled": False},
).status_code == 200
assert client.post(
f"/api/site/member/valuation/sessions/{session_id}/drafts",
headers=token("m:1"),
json={"templateId": template_id},
).status_code == 404
def test_pptx_template_downloads_as_slides(client, monkeypatch):
monkeypatch.setattr("app.api.site.valuation.upload_object", lambda *args, **kwargs: None)
monkeypatch.setattr("app.api.site.valuation.read_upload_limit", lambda db: 10 * 1024 * 1024)
rejected = client.post(
"/api/site/member/valuation/templates",
headers=token("s:1"),
data={"name": "旧格式"},
files={"file": ("deck.ppt", b"old-ppt", "application/vnd.ms-powerpoint")},
)
assert rejected.status_code == 400
created = client.post(
"/api/site/member/valuation/templates",
headers=token("s:1"),
data={"name": "住宅汇报"},
files={
"file": (
"house.pptx",
_sample_pptx(),
"application/vnd.openxmlformats-officedocument.presentationml.presentation",
)
},
)
assert created.status_code == 201
assert created.json()["format"] == "pptx"
template_id = created.json()["id"]
session_id = client.post("/api/site/member/valuation/sessions", headers=token("m:1")).json()["id"]
def fake_stream(**kwargs):
assert "幻灯片" in kwargs["query"]
assert "第1页" in kwargs["query"]
assert "必须写权属" in kwargs["query"]
yield {"type": "delta", "text": "第1页\n住宅坐落\n- 兰州市城关区待补充\n第2页\n估价结果\n- 待补充"}
yield {"type": "done", "conversationId": "draft-ppt"}
monkeypatch.setattr("app.api.site.valuation.iter_dify_chat", fake_stream)
response = client.post(
f"/api/site/member/valuation/sessions/{session_id}/drafts",
headers=token("m:1"),
json={"templateId": template_id, "query": "请帮忙生成一份估价说明"},
)
assert response.status_code == 200
saved = client.get(f"/api/site/member/valuation/sessions/{session_id}/messages", headers=token("m:1")).json()["items"][-1]
assert saved["draftFormat"] == "pptx"
assert saved["draftName"] == "住宅汇报"
download = client.get(
f"/api/site/member/valuation/sessions/{session_id}/messages/{saved['id']}/pptx",
headers=token("m:1"),
)
assert download.status_code == 200
assert download.content.startswith(b"PK")
assert "住宅汇报.pptx" in unquote(download.headers["content-disposition"])
with zipfile.ZipFile(io.BytesIO(download.content)) as archive:
xml = "\n".join(
archive.read(name).decode("utf-8", "ignore")
for name in archive.namelist()
if name.startswith("ppt/slides/slide") and name.endswith(".xml")
)
assert "住宅坐落" in xml
assert "估价结果" in xml
assert client.get(
f"/api/site/member/valuation/sessions/{session_id}/messages/{saved['id']}/docx",
headers=token("m:1"),
).status_code == 404
packed = build_pptx("第1页\n住宅坐落\n- 待补充")
assert packed.startswith(b"PK")
def test_free_generation_can_choose_pptx(client, monkeypatch):
monkeypatch.setattr("app.api.site.valuation.search_web", lambda query: [])
def fake_stream(**kwargs):
assert kwargs["conversation_id"] == ""
assert "格式:pptx" in kwargs["query"]
assert "请生成一份估价方法幻灯片" in kwargs["query"]
yield {"type": "delta", "text": "格式:pptx\n第1页\n估价方法\n- 比较法待补充"}
yield {"type": "done", "conversationId": "draft-free"}
monkeypatch.setattr("app.api.site.valuation.iter_dify_chat", fake_stream)
session_id = client.post("/api/site/member/valuation/sessions", headers=token("m:1")).json()["id"]
response = client.post(
f"/api/site/member/valuation/sessions/{session_id}/drafts",
headers=token("m:1"),
json={"query": "请生成一份估价方法幻灯片"},
)
assert response.status_code == 200
assert "格式:pptx" not in response.text
saved = client.get(f"/api/site/member/valuation/sessions/{session_id}/messages", headers=token("m:1")).json()["items"][-1]
assert saved["draftFormat"] == "pptx"
assert "格式:" not in saved["content"]
assert "估价方法" in saved["content"]
download = client.get(
f"/api/site/member/valuation/sessions/{session_id}/messages/{saved['id']}/pptx",
headers=token("m:1"),
)
assert download.status_code == 200
assert download.content.startswith(b"PK")
def test_free_generation_follows_the_prompt_for_xlsx_and_markdown(client, monkeypatch):
def fake_sheet(**kwargs):
assert "请生成一份估价参数表" in kwargs["query"]
yield {"type": "delta", "text": "格式:xlsx\n项目|内容\n建筑面积|待补充"}
yield {"type": "done", "conversationId": "draft-sheet"}
monkeypatch.setattr("app.api.site.valuation.iter_dify_chat", fake_sheet)
session_id = client.post("/api/site/member/valuation/sessions", headers=token("m:1")).json()["id"]
response = client.post(
f"/api/site/member/valuation/sessions/{session_id}/drafts",
headers=token("m:1"),
json={"query": "请生成一份估价参数表"},
)
assert response.status_code == 200
saved = client.get(f"/api/site/member/valuation/sessions/{session_id}/messages", headers=token("m:1")).json()["items"][-1]
assert saved["draftFormat"] == "xlsx"
assert "格式:" not in saved["content"]
sheet = client.get(
f"/api/site/member/valuation/sessions/{session_id}/messages/{saved['id']}/xlsx",
headers=token("m:1"),
)
assert sheet.status_code == 200
with zipfile.ZipFile(io.BytesIO(sheet.content)) as archive:
xml = "\n".join(archive.read(name).decode("utf-8", "ignore") for name in archive.namelist())
assert "建筑面积" in xml
def fake_note(**kwargs):
assert "Markdown" in kwargs["query"]
yield {"type": "delta", "text": "# 估价说明\n比较法待补充"}
yield {"type": "done", "conversationId": "draft-md"}
monkeypatch.setattr("app.api.site.valuation.iter_dify_chat", fake_note)
noted = client.post(
f"/api/site/member/valuation/sessions/{session_id}/drafts",
headers=token("m:1"),
json={"query": "请生成一份 Markdown 估价说明"},
)
assert noted.status_code == 200
item = client.get(f"/api/site/member/valuation/sessions/{session_id}/messages", headers=token("m:1")).json()["items"][-1]
assert item["draftFormat"] == "md"
text = client.get(
f"/api/site/member/valuation/sessions/{session_id}/messages/{item['id']}/md",
headers=token("m:1"),
)
assert text.status_code == 200
assert "比较法待补充" in text.text
def test_answer_note_uses_production_wording():
assert ensure_answer_note("评估对象是股权。") == f"评估对象是股权。\n\n{ANSWER_NOTE}"
assert ensure_answer_note("评估对象是股权。\n\n演示回答不构成正式评估意见。") == f"评估对象是股权。\n\n{ANSWER_NOTE}"
assert ensure_answer_note(f"本回答属于演示性质,不构成正式评估意见。\n\n{ANSWER_NOTE}") == ANSWER_NOTE
assert ensure_answer_note("本回答为演示性质,不构成正式评估意见;请补充材料。") == f"本回答仅供参考,不构成正式评估意见;请补充材料。\n\n{ANSWER_NOTE}"
assert "演示" not in ANSWER_NOTE
def test_chat_persists_streamed_answer(client, monkeypatch):
session_id = client.post("/api/site/member/valuation/sessions", headers=token("m:1")).json()["id"]
def fake_stream(**kwargs):
assert kwargs["user"] == "m:1"
yield {"type": "thought", "text": "检索知识库"}
yield {"type": "delta", "text": "评估对象是股权。"}
yield {"type": "done", "conversationId": "conv-1"}
monkeypatch.setattr("app.api.site.valuation.iter_dify_chat", fake_stream)
response = client.post(
f"/api/site/member/valuation/sessions/{session_id}/messages",
headers=token("m:1"),
json={"query": "日播时尚的评估对象是什么?"},
)
assert response.status_code == 200
events = [json.loads(line[5:]) for line in response.text.splitlines() if line.startswith("data:")]
assert events[0]["type"] == "thought"
assert any(item["type"] == "done" for item in events)
stored = client.get(f"/api/site/member/valuation/sessions/{session_id}/messages", headers=token("m:1")).json()["items"]
assert stored[-1]["content"] == "评估对象是股权。\n\n本回答仅供参考,不构成正式评估意见。"
assert stored[-1]["thought"] == "检索知识库"
assert client.get("/api/site/member/valuation/sessions", headers=token("m:1")).json()["items"][0]["title"].startswith("日播时尚")