feat: 增加会员服务与估价模版智能体
会员服务改为固定栏目,首页在线服务不再进入报告审核。估价模版智能体可多会话制作模版并下载,下载过程显示加载状态。 Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
55b5a87482
commit
2074a45681
63 files changed
+6428
-461
No files matched your search
@@ -64,7 +64,7 @@
|
||||
- 数据挖掘的采集、清洗、建模和图表。首页数据看板与通知公告相同,发布文章用富文本展示说明或图片,不嵌示意图页面,不接真实指数,不采集数据。见 `docs/adr/0005-homepage-dashboard-as-articles.md`。
|
||||
- 智能估价平台(个人/企业在线评估、价格参考报告)。
|
||||
- 与中房学、住建厅窗口的数据对接、单点登录和回写。
|
||||
- 报告审核做成审核引擎或接入模型。本期只做门户演示页,提交后提示尚未开通,不保存。见 `docs/adr/0010-report-query-is-filing-lookup.md`。
|
||||
- 报告审核做成审核引擎、演示页或接入模型。门户不提供报告审核入口和页面。见 `docs/adr/0010-report-query-is-filing-lookup.md`。
|
||||
- 把报告查询做成文件验真或核验码。按该 ADR,只对照报告中心已发布的备案。
|
||||
- 单独手机站、旧站修补、本地物理服务器。
|
||||
|
||||
|
||||
+31
-13
@@ -1,6 +1,6 @@
|
||||
# 协会门户
|
||||
|
||||
甘肃省房地产价格评估行业协会门户上的栏目和配置对象。一词只指一件事。含首页、「关于协会」、「机构名录」、「行业党建」、「专家服务」、「技术交流」、「资料库」、「继续教育」、「报告核验」与「行业自律」相关栏目。
|
||||
甘肃省房地产价格评估行业协会门户上的栏目和配置对象。一词只指一件事。含首页、「关于协会」、「机构名录」、「行业党建」、「专家服务」、「技术交流」、「资料库」、「继续教育」、「会员服务」、「报告核验」与「行业自律」相关栏目。
|
||||
|
||||
## Language
|
||||
|
||||
@@ -25,8 +25,8 @@ _Avoid_: 定位标语, 轮播
|
||||
_Avoid_: 新闻动态, 通知公告, 政策法规, 入口
|
||||
|
||||
**快捷菜单**:
|
||||
页头菜单栏里与首页并列的可配置项。本期是会员服务。每项可配名称、地址、一张图、是否展示和顺序。继续教育(栏目)、组织概况、资质荣誉、机构名录、行业党建(栏目)、专家服务(栏目)、技术交流(栏目)、行业自律(栏目)、联系合作不是快捷菜单,是固定站内栏目。
|
||||
_Avoid_: 服务对象入口, 高频功能入口, 轮播, 继续教育(栏目), 组织概况, 资质荣誉, 机构名录, 行业党建(栏目), 专家服务(栏目), 技术交流(栏目), 行业自律(栏目), 联系合作
|
||||
页头菜单栏里与首页并列的可配置项。会员服务已改为固定栏目,不再从这里进入。继续教育(栏目)、组织概况、资质荣誉、机构名录、行业党建(栏目)、专家服务(栏目)、技术交流(栏目)、行业自律(栏目)、联系合作、会员服务(栏目)不是快捷菜单,是固定站内栏目。
|
||||
_Avoid_: 服务对象入口, 高频功能入口, 轮播, 继续教育(栏目), 会员服务(栏目), 组织概况, 资质荣誉, 机构名录, 行业党建(栏目), 专家服务(栏目), 技术交流(栏目), 行业自律(栏目), 联系合作
|
||||
|
||||
**新闻动态**:
|
||||
首页上单独展示的一类内容,在管理后台另行设置。首页只取该类最新的若干条,条数由管理端配置。
|
||||
@@ -45,7 +45,7 @@ _Avoid_: 轮播, 新闻动态, 通知公告
|
||||
_Avoid_: 三张卡片, 高频功能入口, 轮播, 详情
|
||||
|
||||
**高频功能入口**:
|
||||
首页上的一块入口区,含报告查询、报告审核、投诉举报。报告查询与报告审核固定打开报告核验下的站内页;管理端可改这两项的名称、是否展示和顺序。投诉举报打开行业自律,地址仍可由后台调整。
|
||||
首页服务对象一行的最后一列,标题为在线服务,版式与估价师、估价机构、公众相同。列内是报告查询和投诉举报。报告查询固定打开报告核验;投诉举报打开行业自律,地址仍可由后台调整。
|
||||
_Avoid_: 服务对象入口, 轮播, 详情
|
||||
|
||||
**详情**:
|
||||
@@ -53,11 +53,11 @@ _Avoid_: 服务对象入口, 轮播, 详情
|
||||
_Avoid_: 入口, 外链
|
||||
|
||||
**荣誉滚动**:
|
||||
首页中部横向连续滚动的资质与获奖图片展示。与资质荣誉栏目不是同一份内容。
|
||||
首页中部横向连续滚动的资质与获奖图片。每张图片下方可有一句简短说明。与资质荣誉栏目不是同一份内容。
|
||||
_Avoid_: 会员单位, 轮播, 资质荣誉
|
||||
|
||||
**会员单位**:
|
||||
首页页脚上方横向滚动的单位卡片,含标志和名称。链接可空;有链接时在新窗口打开,无链接时点击无效果。
|
||||
首页页脚上方横向滚动的单位卡片,含标志和名称。数量达到 6 个时分成上下两行,下一行相对上一行错开半张卡片。链接可空;有链接时在新窗口打开,无链接时点击无效果。
|
||||
_Avoid_: 荣誉滚动, 入口
|
||||
|
||||
**数据看板**:
|
||||
@@ -103,11 +103,11 @@ _Avoid_: 协会简介, 组织机构, 栏目文章
|
||||
_Avoid_: 栏目文章, 专家委员会
|
||||
|
||||
**栏目文章**:
|
||||
可多条发布的标题 + 富文本 + 多附件内容,形态对齐通知公告。本期类别为年度报告/工作计划、工作简报、资质荣誉、机构名录、行业党建(模块)、技术研讨、技术交流(模块)、专项估价服务、政策分析、案例库、教育公告、警示案例、诚信档案、结果公示。
|
||||
可多条发布的标题 + 富文本 + 多附件内容,形态对齐通知公告。本期类别为年度报告/工作计划、工作简报、资质荣誉、机构名录、行业党建(模块)、技术研讨、技术交流(模块)、专项估价服务、政策分析、案例库、教育公告、会员资讯、警示案例、诚信档案、结果公示。
|
||||
_Avoid_: 单篇页, 专家委员会, 轮播, 荣誉滚动
|
||||
|
||||
**栏目列表分页**:
|
||||
门户上栏目文章列表的翻页与每页条数。默认每页 10 条,访客可改为 10、20 或 100 条/页。适用于年度报告/工作计划、工作简报、资质荣誉、机构名录、行业党建(模块)、技术研讨、技术交流(模块)、专项估价服务、政策分析、案例库、教育公告、警示案例、诚信档案、结果公示。
|
||||
门户上栏目文章列表的翻页与每页条数。默认每页 10 条,访客可改为 10、20 或 100 条/页。适用于年度报告/工作计划、工作简报、资质荣誉、机构名录、行业党建(模块)、技术研讨、技术交流(模块)、专项估价服务、政策分析、案例库、教育公告、会员资讯、警示案例、诚信档案、结果公示。
|
||||
_Avoid_: 首页展示条数, 无限滚动
|
||||
|
||||
**年度报告/工作计划**:
|
||||
@@ -214,10 +214,32 @@ _Avoid_: 在线课程, 视频课, 学分, 教育公告
|
||||
继续教育(栏目)下的一类栏目文章。每条含标题、富文本正文、多个附件、可选封面与是否发布,用来提前公示培训安排。
|
||||
_Avoid_: 在线教育, 通知公告, 课程表
|
||||
|
||||
## 会员服务
|
||||
|
||||
**会员服务(栏目)**:
|
||||
门户固定站内栏目。顶栏一项、无下拉;插在继续教育之后。页内子导航为「会员机构」「会员信息」「会员资讯」「培训报名」。
|
||||
_Avoid_: 快捷菜单, 中房学对接, 住建厅对接
|
||||
|
||||
**会员机构**:
|
||||
会员服务下的一组外链卡片。每张卡片一张图,图下是名称;点击在新窗口打开该网址。用来指向中房学、住建厅窗口等已有系统。
|
||||
_Avoid_: 会员信息, 机构名录, 数据对接
|
||||
|
||||
**协会会员**:
|
||||
由工作人员建立的一条会员档案,分个人会员和机构会员。创建时同步一条门户邮箱账号;登录后只能看到自己的档案。
|
||||
_Avoid_: 门户邮箱账号, 工作人员账号, 机构名录
|
||||
|
||||
**会员资讯**:
|
||||
会员服务下的一类栏目文章。每条含标题、富文本正文、多个附件、可选封面与是否发布,用来刊登章程、管理办法和会费办法。
|
||||
_Avoid_: 教育公告, 机构名录, 通知公告
|
||||
|
||||
**培训报名**:
|
||||
会员服务下的一场会议或培训。工作人员发布公告并配置用餐日期;会员登录后提交报名,用餐日期可多选。缴费只展示转账账户。
|
||||
_Avoid_: 继续教育系统, 在线支付, 教育公告
|
||||
|
||||
## 报告核验
|
||||
|
||||
**报告核验(栏目)**:
|
||||
门户固定站内栏目。页内子导航为报告查询、报告审核。首页高频功能入口可以进入这两个页面。
|
||||
门户固定站内栏目。栏目页即报告查询,没有页内子导航。首页高频功能入口可以进入报告查询。
|
||||
_Avoid_: 资料库, 专家服务(栏目)
|
||||
|
||||
**报告查询**:
|
||||
@@ -232,10 +254,6 @@ _Avoid_: 报告原件, 上传案例
|
||||
管理端中工作人员录入和发布报告备案的菜单。
|
||||
_Avoid_: 报告查询, 报告审核
|
||||
|
||||
**报告审核**:
|
||||
报告核验下的演示提问页。访客可选文件并提问;本期不产生审核结论。
|
||||
_Avoid_: 智能问答, 资料库, 审核引擎
|
||||
|
||||
## 行业自律
|
||||
|
||||
**行业自律(栏目)**:
|
||||
|
||||
+1
-1
@@ -31,7 +31,7 @@
|
||||
明确不做:
|
||||
|
||||
- 报告审核引擎,以及让会员在门户提交备案。备案只在报告中心由工作人员维护,见 `docs/adr/0010-report-query-is-filing-lookup.md`。
|
||||
- 中房学、住建厅的数据同步界面。只保留可配置外链的维护项。
|
||||
- 中房学、住建厅的数据同步界面。只保留可配置外链的维护项。会员服务的外链、档案、资讯和培训报名见 `docs/adr/0013-member-service-is-four-modules.md`。
|
||||
- 智能估价平台配置以外的业务页面。
|
||||
- 不限制大小的上传。上限由服务端配置,上传过程要可见,支持批量、粘贴、删除和下载。
|
||||
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
import request from '@/utils/http'
|
||||
|
||||
export function fetchMemberOrgs() {
|
||||
return request.get<{ items: Record<string, any>[] }>({ url: '/api/admin/membership/orgs' })
|
||||
}
|
||||
|
||||
export function saveMemberOrgs(data: Record<string, unknown>) {
|
||||
return request.put({ url: '/api/admin/membership/orgs', data })
|
||||
}
|
||||
|
||||
export function fetchProfiles(params: { current: number; size: number; keyword?: string }) {
|
||||
return request.get<{ records: Record<string, any>[]; total: number }>({
|
||||
url: '/api/admin/membership/profiles',
|
||||
params
|
||||
})
|
||||
}
|
||||
|
||||
export function fetchProfile(id: number) {
|
||||
return request.get<Record<string, any>>({ url: `/api/admin/membership/profiles/${id}` })
|
||||
}
|
||||
|
||||
export function createProfile(data: Record<string, unknown>) {
|
||||
return request.post<Record<string, any>>({ url: '/api/admin/membership/profiles', data })
|
||||
}
|
||||
|
||||
export function updateProfile(id: number, data: Record<string, unknown>) {
|
||||
return request.put({ url: `/api/admin/membership/profiles/${id}`, data })
|
||||
}
|
||||
|
||||
export function deleteProfile(id: number) {
|
||||
return request.del({ url: `/api/admin/membership/profiles/${id}` })
|
||||
}
|
||||
|
||||
export function fetchEvents() {
|
||||
return request.get<{ items: Record<string, any>[] }>({ url: '/api/admin/membership/events' })
|
||||
}
|
||||
|
||||
export function createEvent(data: Record<string, unknown>) {
|
||||
return request.post<Record<string, any>>({ url: '/api/admin/membership/events', data })
|
||||
}
|
||||
|
||||
export function updateEvent(id: number, data: Record<string, unknown>) {
|
||||
return request.put({ url: `/api/admin/membership/events/${id}`, data })
|
||||
}
|
||||
|
||||
export function deleteEvent(id: number) {
|
||||
return request.del({ url: `/api/admin/membership/events/${id}` })
|
||||
}
|
||||
|
||||
export function fetchRegistrations(eventId: number) {
|
||||
return request.get<{ items: Record<string, any>[] }>({
|
||||
url: `/api/admin/membership/events/${eventId}/registrations`
|
||||
})
|
||||
}
|
||||
|
||||
export function fetchRegistration(id: number) {
|
||||
return request.get<Record<string, any>>({ url: `/api/admin/membership/registrations/${id}` })
|
||||
}
|
||||
|
||||
export function createRegistration(eventId: number, data: Record<string, unknown>) {
|
||||
return request.post({ url: `/api/admin/membership/events/${eventId}/registrations`, data })
|
||||
}
|
||||
|
||||
export function updateRegistration(id: number, data: Record<string, unknown>) {
|
||||
return request.put({ url: `/api/admin/membership/registrations/${id}`, data })
|
||||
}
|
||||
|
||||
export function deleteRegistration(id: number) {
|
||||
return request.del({ url: `/api/admin/membership/registrations/${id}` })
|
||||
}
|
||||
@@ -43,6 +43,7 @@ const PAGE_AUTH_PREFIX: Record<string, string> = {
|
||||
'/expert/qa': 'expert:',
|
||||
'/tech': 'tech:',
|
||||
'/edu': 'edu:',
|
||||
'/member': 'membership:',
|
||||
'/institutions': 'directory:',
|
||||
'/library/policies': 'library:',
|
||||
'/library/cases': 'library:',
|
||||
@@ -84,6 +85,7 @@ const AUTH_TITLE: Record<string, string> = {
|
||||
'expert:reply': '回复',
|
||||
'tech:edit': '保存',
|
||||
'edu:edit': '保存',
|
||||
'membership:edit': '保存',
|
||||
'directory:edit': '保存',
|
||||
'library:edit': '保存',
|
||||
'report:edit': '保存',
|
||||
|
||||
@@ -25,7 +25,7 @@
|
||||
<ElTabPane label="高频功能" name="hot">
|
||||
<div class="flex flex-wrap items-center justify-between gap-3 mb-4">
|
||||
<p class="m-0 text-sm text-g-600"
|
||||
>报告查询、报告审核固定打开报告核验。投诉举报打开行业自律,地址仍可修改。可调整名称、顺序和是否显示。</p
|
||||
>报告查询固定打开报告核验。投诉举报打开行业自律,地址仍可修改。可调整名称、顺序和是否显示。</p
|
||||
>
|
||||
<ElButton v-auth="'home:edit'" type="primary" :loading="savingHot" @click="saveHotForm">
|
||||
保存高频功能
|
||||
@@ -37,7 +37,7 @@
|
||||
<ElTabPane label="快捷菜单" name="menu">
|
||||
<div class="flex flex-wrap items-center justify-between gap-3 mb-4">
|
||||
<p class="m-0 text-sm text-g-600"
|
||||
>快捷菜单只配置会员服务。关闭显示后,门户不出现该项。</p
|
||||
>会员服务已改为站内栏目,顶栏固定打开。这里保存的地址不再出现在顶栏。</p
|
||||
>
|
||||
<ElButton
|
||||
v-auth="'home:edit'"
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
<ElTabs v-if="ready" v-model="activeTab" type="border-card">
|
||||
<ElTabPane label="荣誉展示" name="honors">
|
||||
<div class="flex flex-wrap items-center justify-between gap-3 mb-4">
|
||||
<p class="m-0 text-sm text-g-600">图片按顺序滚动。没有图片的条目不会保存。</p>
|
||||
<p class="m-0 text-sm text-g-600">图片按顺序滚动。说明显示在图片下方,可留空,不超过 24 个字。没有图片的条目不会保存。</p>
|
||||
<div class="flex items-center gap-3">
|
||||
<span class="text-sm text-g-600">滚动间隔</span>
|
||||
<ElInputNumber
|
||||
@@ -32,6 +32,14 @@
|
||||
@pick="(payload) => assignImage(item, payload)"
|
||||
@clear="clearImage(item)"
|
||||
/>
|
||||
<ElInput
|
||||
v-model="item.caption"
|
||||
class="mt-3"
|
||||
maxlength="24"
|
||||
show-word-limit
|
||||
:disabled="!canEdit"
|
||||
placeholder="图片下方的简短说明,可留空"
|
||||
/>
|
||||
<div class="mt-3 flex items-center justify-between gap-2">
|
||||
<div class="flex items-center gap-2">
|
||||
<span class="text-sm text-g-600">顺序</span>
|
||||
@@ -124,6 +132,7 @@
|
||||
interface MediaItem {
|
||||
name?: string
|
||||
url?: string
|
||||
caption?: string
|
||||
imageFileId: number | null
|
||||
imageUrl: string
|
||||
sortOrder: number
|
||||
@@ -144,6 +153,7 @@
|
||||
const { canEdit, loading, ready, load } = useHomeEditor((data) => {
|
||||
honors.intervalSeconds = data.honors?.intervalSeconds || 8
|
||||
honors.items = (data.honors?.items || []).map((item: MediaItem) => ({
|
||||
caption: item.caption || '',
|
||||
imageFileId: item.imageFileId,
|
||||
imageUrl: item.imageUrl || '',
|
||||
sortOrder: item.sortOrder
|
||||
@@ -169,7 +179,12 @@
|
||||
}
|
||||
|
||||
const addHonor = () => {
|
||||
honors.items.push({ imageFileId: null, imageUrl: '', sortOrder: honors.items.length + 1 })
|
||||
honors.items.push({
|
||||
caption: '',
|
||||
imageFileId: null,
|
||||
imageUrl: '',
|
||||
sortOrder: honors.items.length + 1
|
||||
})
|
||||
}
|
||||
|
||||
const addMember = () => {
|
||||
@@ -193,6 +208,7 @@
|
||||
intervalSeconds: honors.intervalSeconds,
|
||||
items: honors.items.map((item) => ({
|
||||
imageFileId: item.imageFileId,
|
||||
caption: item.caption?.trim() || '',
|
||||
sortOrder: item.sortOrder
|
||||
}))
|
||||
})
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
<template>
|
||||
<div v-loading="loading" class="min-h-40">
|
||||
<div class="flex flex-wrap items-center justify-between gap-3 mb-4">
|
||||
<p class="m-0 text-sm text-g-600">每张卡片一张图,图下是机构服务名称。门户点击后在新窗口打开网址。</p>
|
||||
<ElButton v-auth="'membership:edit'" type="primary" :loading="saving" @click="save">保存</ElButton>
|
||||
</div>
|
||||
<div class="media-grid">
|
||||
<article v-for="(item, index) in items" :key="index" class="media-card">
|
||||
<HomeImageField
|
||||
:url="item.imageUrl"
|
||||
:disabled="!canEdit"
|
||||
@pick="(payload) => assignImage(item, payload)"
|
||||
@clear="clearImage(item)"
|
||||
/>
|
||||
<ElInput v-model="item.name" class="mt-3" :disabled="!canEdit" placeholder="名称,如中房学" />
|
||||
<ElInput v-model="item.url" class="mt-2" :disabled="!canEdit" placeholder="https://" />
|
||||
<div class="mt-3 flex items-center justify-between gap-2">
|
||||
<div class="flex items-center gap-2">
|
||||
<span class="text-sm text-g-600">顺序</span>
|
||||
<ElInputNumber v-model="item.sortOrder" :min="0" :disabled="!canEdit" controls-position="right" />
|
||||
</div>
|
||||
<ElButton v-if="canEdit" link type="danger" @click="items.splice(index, 1)">删除</ElButton>
|
||||
</div>
|
||||
</article>
|
||||
<button v-if="canEdit" type="button" class="media-add" @click="addItem">
|
||||
<span>添加外链</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { fetchMemberOrgs, saveMemberOrgs } from '@/api/membership'
|
||||
import { useAuth } from '@/hooks/core/useAuth'
|
||||
import HomeImageField from '@/views/home/components/HomeImageField.vue'
|
||||
|
||||
interface OrgItem {
|
||||
name: string
|
||||
url: string
|
||||
imageFileId: number | null
|
||||
imageUrl: string
|
||||
sortOrder: number
|
||||
}
|
||||
|
||||
const { hasAuth } = useAuth()
|
||||
const canEdit = computed(() => hasAuth('membership:edit'))
|
||||
const loading = ref(false)
|
||||
const saving = ref(false)
|
||||
const items = ref<OrgItem[]>([])
|
||||
|
||||
const load = async () => {
|
||||
loading.value = true
|
||||
try {
|
||||
const data = await fetchMemberOrgs()
|
||||
items.value = (data.items || []).map((item) => ({
|
||||
name: item.name || '',
|
||||
url: item.url || '',
|
||||
imageFileId: item.imageFileId ?? null,
|
||||
imageUrl: item.imageUrl || '',
|
||||
sortOrder: item.sortOrder ?? 0
|
||||
}))
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const assignImage = (item: OrgItem, payload: { id: number; url: string }) => {
|
||||
item.imageFileId = payload.id
|
||||
item.imageUrl = payload.url
|
||||
}
|
||||
|
||||
const clearImage = (item: OrgItem) => {
|
||||
item.imageFileId = null
|
||||
item.imageUrl = ''
|
||||
}
|
||||
|
||||
const addItem = () => {
|
||||
items.value.push({
|
||||
name: '',
|
||||
url: '',
|
||||
imageFileId: null,
|
||||
imageUrl: '',
|
||||
sortOrder: items.value.length + 1
|
||||
})
|
||||
}
|
||||
|
||||
const save = async () => {
|
||||
if (items.value.some((item) => !item.name.trim() || !item.url.trim() || !item.imageFileId)) {
|
||||
ElMessage.warning('每条外链都需要名称、网址和图片,或删除未完成的条目')
|
||||
return
|
||||
}
|
||||
saving.value = true
|
||||
try {
|
||||
await saveMemberOrgs({
|
||||
items: items.value.map((item) => ({
|
||||
name: item.name.trim(),
|
||||
url: item.url.trim(),
|
||||
imageFileId: item.imageFileId,
|
||||
sortOrder: item.sortOrder
|
||||
}))
|
||||
})
|
||||
ElMessage.success('已保存')
|
||||
await load()
|
||||
} finally {
|
||||
saving.value = false
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(load)
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.media-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.media-card,
|
||||
.media-add {
|
||||
padding: 14px;
|
||||
border: 1px solid var(--el-border-color);
|
||||
border-radius: 10px;
|
||||
background: var(--el-bg-color);
|
||||
}
|
||||
|
||||
.media-add {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
min-height: 168px;
|
||||
border-style: dashed;
|
||||
color: var(--el-color-primary);
|
||||
cursor: pointer;
|
||||
background: var(--el-fill-color-lighter);
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,308 @@
|
||||
<template>
|
||||
<div v-loading="loading">
|
||||
<div class="flex flex-wrap items-center justify-between gap-3 mb-4">
|
||||
<p class="m-0 text-sm text-g-600">
|
||||
工作人员建档。新建时若邮箱还没有门户账号,会同步一条注册用户;已有账号则挂到原账号上。删除档案不会删除门户登录账号。
|
||||
</p>
|
||||
<div class="flex items-center gap-2">
|
||||
<ElInput v-model="keyword" clearable placeholder="编号、姓名、单位或邮箱" class="w-64" @keyup.enter="load" />
|
||||
<ElButton @click="load">查询</ElButton>
|
||||
<ElButton v-auth="'membership:edit'" type="primary" @click="openCreate">新增会员</ElButton>
|
||||
</div>
|
||||
</div>
|
||||
<ElTable :data="records" border>
|
||||
<ElTableColumn prop="memberNo" label="会员编号" min-width="120" />
|
||||
<ElTableColumn prop="kindLabel" label="类型" width="110" />
|
||||
<ElTableColumn prop="displayName" label="名称" min-width="160" />
|
||||
<ElTableColumn prop="email" label="登录邮箱" min-width="180" />
|
||||
<ElTableColumn prop="membershipStatusLabel" label="状态" width="90" />
|
||||
<ElTableColumn label="操作" width="210" fixed="right">
|
||||
<template #default="{ row }">
|
||||
<ElButton link type="primary" @click="openView(row.id)">查看</ElButton>
|
||||
<ElButton v-auth="'membership:edit'" link type="primary" @click="openEdit(row.id)">编辑</ElButton>
|
||||
<ElButton v-auth="'membership:edit'" link type="danger" @click="remove(row)">删除</ElButton>
|
||||
</template>
|
||||
</ElTableColumn>
|
||||
</ElTable>
|
||||
<div class="mt-3 flex justify-end">
|
||||
<ElPagination
|
||||
v-model:current-page="current"
|
||||
v-model:page-size="size"
|
||||
:total="total"
|
||||
layout="total, prev, pager, next"
|
||||
@current-change="load"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<ElDialog v-model="viewVisible" title="会员信息" width="860px" align-center destroy-on-close>
|
||||
<ElDescriptions v-if="detail" :column="2" border>
|
||||
<ElDescriptionsItem label="会员类型">{{ text(detail.kindLabel) }}</ElDescriptionsItem>
|
||||
<ElDescriptionsItem label="会员状态">{{ text(detail.membershipStatusLabel) }}</ElDescriptionsItem>
|
||||
<ElDescriptionsItem label="登录邮箱">{{ text(detail.email) }}</ElDescriptionsItem>
|
||||
<ElDescriptionsItem label="会员编号">{{ text(detail.memberNo) }}</ElDescriptionsItem>
|
||||
<ElDescriptionsItem label="会费状态">{{ text(detail.feeStatusLabel) }}</ElDescriptionsItem>
|
||||
<ElDescriptionsItem label="入会日期">{{ text(detail.joinedOn) }}</ElDescriptionsItem>
|
||||
<ElDescriptionsItem label="到期日">{{ text(detail.expiresOn) }}</ElDescriptionsItem>
|
||||
<ElDescriptionsItem label="手机号">{{ text(detail.mobile) }}</ElDescriptionsItem>
|
||||
<ElDescriptionsItem label="所在地区">{{ text(detail.region) }}</ElDescriptionsItem>
|
||||
<ElDescriptionsItem label="通讯地址">{{ text(detail.address) }}</ElDescriptionsItem>
|
||||
<ElDescriptionsItem label="邮编">{{ text(detail.postalCode) }}</ElDescriptionsItem>
|
||||
<template v-if="detail.kind === 'individual'">
|
||||
<ElDescriptionsItem label="姓名">{{ text(detail.personName) }}</ElDescriptionsItem>
|
||||
<ElDescriptionsItem label="性别">{{ text(detail.genderLabel) }}</ElDescriptionsItem>
|
||||
<ElDescriptionsItem label="出生日期">{{ text(detail.birthDate) }}</ElDescriptionsItem>
|
||||
<ElDescriptionsItem label="身份证号">{{ text(detail.idCard) }}</ElDescriptionsItem>
|
||||
<ElDescriptionsItem label="学历">{{ text(detail.education) }}</ElDescriptionsItem>
|
||||
<ElDescriptionsItem label="专业">{{ text(detail.major) }}</ElDescriptionsItem>
|
||||
<ElDescriptionsItem label="职称">{{ text(detail.jobTitle) }}</ElDescriptionsItem>
|
||||
<ElDescriptionsItem label="从业年限">{{ text(detail.practiceYears) }}</ElDescriptionsItem>
|
||||
<ElDescriptionsItem label="工作单位">{{ text(detail.employer) }}</ElDescriptionsItem>
|
||||
<ElDescriptionsItem label="职务">{{ text(detail.position) }}</ElDescriptionsItem>
|
||||
<ElDescriptionsItem label="注册证号">{{ text(detail.appraiserRegNo) }}</ElDescriptionsItem>
|
||||
<ElDescriptionsItem label="资格证号">{{ text(detail.qualificationNo) }}</ElDescriptionsItem>
|
||||
<ElDescriptionsItem label="注册有效期">{{ text(detail.regValidUntil) }}</ElDescriptionsItem>
|
||||
</template>
|
||||
<template v-else>
|
||||
<ElDescriptionsItem label="单位全称">{{ text(detail.orgName) }}</ElDescriptionsItem>
|
||||
<ElDescriptionsItem label="信用代码">{{ text(detail.creditCode) }}</ElDescriptionsItem>
|
||||
<ElDescriptionsItem label="资质等级">{{ text(detail.qualificationLevel) }}</ElDescriptionsItem>
|
||||
<ElDescriptionsItem label="备案编号">{{ text(detail.filingNo) }}</ElDescriptionsItem>
|
||||
<ElDescriptionsItem label="法定代表人">{{ text(detail.legalPerson) }}</ElDescriptionsItem>
|
||||
<ElDescriptionsItem label="办公地址">{{ text(detail.officeAddress) }}</ElDescriptionsItem>
|
||||
<ElDescriptionsItem label="联系人">{{ text(detail.contactName) }}</ElDescriptionsItem>
|
||||
<ElDescriptionsItem label="联系人职务">{{ text(detail.contactPosition) }}</ElDescriptionsItem>
|
||||
<ElDescriptionsItem label="联系人手机">{{ text(detail.contactMobile) }}</ElDescriptionsItem>
|
||||
<ElDescriptionsItem label="联系人邮箱">{{ text(detail.contactEmail) }}</ElDescriptionsItem>
|
||||
</template>
|
||||
<ElDescriptionsItem label="备注" :span="2">{{ text(detail.remark) }}</ElDescriptionsItem>
|
||||
</ElDescriptions>
|
||||
<template #footer>
|
||||
<ElButton @click="viewVisible = false">关闭</ElButton>
|
||||
</template>
|
||||
</ElDialog>
|
||||
|
||||
<ElDialog v-model="visible" :title="editingId ? '编辑会员' : '新增会员'" width="860px" align-center destroy-on-close>
|
||||
<ElForm label-width="120px">
|
||||
<div class="grid">
|
||||
<ElFormItem label="会员类型" required>
|
||||
<ElRadioGroup v-model="form.kind">
|
||||
<ElRadio value="individual">个人会员</ElRadio>
|
||||
<ElRadio value="organization">机构会员</ElRadio>
|
||||
</ElRadioGroup>
|
||||
</ElFormItem>
|
||||
<ElFormItem label="会员状态" required>
|
||||
<ElSelect v-model="form.membershipStatus">
|
||||
<ElOption label="正常" value="active" />
|
||||
<ElOption label="暂停" value="suspended" />
|
||||
<ElOption label="退会" value="withdrawn" />
|
||||
</ElSelect>
|
||||
</ElFormItem>
|
||||
<ElFormItem label="登录邮箱" required>
|
||||
<ElInput v-model="form.email" autocomplete="off" />
|
||||
</ElFormItem>
|
||||
<ElFormItem :label="editingId ? '重置密码' : '初始密码'">
|
||||
<ElInput
|
||||
v-model="form.password"
|
||||
type="password"
|
||||
show-password
|
||||
maxlength="10"
|
||||
:placeholder="editingId ? '留空不修改,填写则不超过 10 位' : '默认 123456,可改成不超过 10 位的任意密码'"
|
||||
/>
|
||||
</ElFormItem>
|
||||
<ElFormItem label="会员编号">
|
||||
<ElInput v-model="form.memberNo" maxlength="40" placeholder="可手动填写,最多 40 个字" />
|
||||
</ElFormItem>
|
||||
<ElFormItem label="会费状态">
|
||||
<ElSelect v-model="form.feeStatus">
|
||||
<ElOption label="已缴" value="paid" />
|
||||
<ElOption label="未缴" value="unpaid" />
|
||||
<ElOption label="免缴" value="waived" />
|
||||
</ElSelect>
|
||||
</ElFormItem>
|
||||
<ElFormItem label="入会日期"><ElDatePicker v-model="form.joinedOn" value-format="YYYY-MM-DD" type="date" /></ElFormItem>
|
||||
<ElFormItem label="到期日"><ElDatePicker v-model="form.expiresOn" value-format="YYYY-MM-DD" type="date" /></ElFormItem>
|
||||
<ElFormItem label="手机号"><ElInput v-model="form.mobile" maxlength="11" /></ElFormItem>
|
||||
<ElFormItem label="所在地区"><ElInput v-model="form.region" placeholder="省市区" /></ElFormItem>
|
||||
<ElFormItem label="通讯地址"><ElInput v-model="form.address" /></ElFormItem>
|
||||
<ElFormItem label="邮编"><ElInput v-model="form.postalCode" /></ElFormItem>
|
||||
<template v-if="form.kind === 'individual'">
|
||||
<ElFormItem label="姓名" required><ElInput v-model="form.personName" /></ElFormItem>
|
||||
<ElFormItem label="性别">
|
||||
<ElRadioGroup v-model="form.gender">
|
||||
<ElRadio value="male">男</ElRadio>
|
||||
<ElRadio value="female">女</ElRadio>
|
||||
</ElRadioGroup>
|
||||
</ElFormItem>
|
||||
<ElFormItem label="出生日期"><ElDatePicker v-model="form.birthDate" value-format="YYYY-MM-DD" type="date" /></ElFormItem>
|
||||
<ElFormItem label="身份证号"><ElInput v-model="form.idCard" /></ElFormItem>
|
||||
<ElFormItem label="学历"><ElInput v-model="form.education" /></ElFormItem>
|
||||
<ElFormItem label="专业"><ElInput v-model="form.major" /></ElFormItem>
|
||||
<ElFormItem label="职称"><ElInput v-model="form.jobTitle" /></ElFormItem>
|
||||
<ElFormItem label="从业年限"><ElInputNumber v-model="form.practiceYears" :min="0" :max="80" /></ElFormItem>
|
||||
<ElFormItem label="工作单位"><ElInput v-model="form.employer" /></ElFormItem>
|
||||
<ElFormItem label="职务"><ElInput v-model="form.position" /></ElFormItem>
|
||||
<ElFormItem label="注册证号"><ElInput v-model="form.appraiserRegNo" maxlength="10" placeholder="10 位数字,可空" /></ElFormItem>
|
||||
<ElFormItem label="资格证号"><ElInput v-model="form.qualificationNo" /></ElFormItem>
|
||||
<ElFormItem label="注册有效期"><ElDatePicker v-model="form.regValidUntil" value-format="YYYY-MM-DD" type="date" /></ElFormItem>
|
||||
</template>
|
||||
<template v-else>
|
||||
<ElFormItem label="单位全称" required><ElInput v-model="form.orgName" /></ElFormItem>
|
||||
<ElFormItem label="信用代码"><ElInput v-model="form.creditCode" maxlength="18" /></ElFormItem>
|
||||
<ElFormItem label="资质等级"><ElInput v-model="form.qualificationLevel" /></ElFormItem>
|
||||
<ElFormItem label="备案编号"><ElInput v-model="form.filingNo" /></ElFormItem>
|
||||
<ElFormItem label="法定代表人"><ElInput v-model="form.legalPerson" /></ElFormItem>
|
||||
<ElFormItem label="办公地址"><ElInput v-model="form.officeAddress" /></ElFormItem>
|
||||
<ElFormItem label="联系人"><ElInput v-model="form.contactName" /></ElFormItem>
|
||||
<ElFormItem label="联系人职务"><ElInput v-model="form.contactPosition" /></ElFormItem>
|
||||
<ElFormItem label="联系人手机"><ElInput v-model="form.contactMobile" maxlength="11" /></ElFormItem>
|
||||
<ElFormItem label="联系人邮箱"><ElInput v-model="form.contactEmail" /></ElFormItem>
|
||||
</template>
|
||||
</div>
|
||||
<ElFormItem label="备注"><ElInput v-model="form.remark" type="textarea" :rows="2" /></ElFormItem>
|
||||
</ElForm>
|
||||
<template #footer>
|
||||
<ElButton @click="visible = false">取消</ElButton>
|
||||
<ElButton type="primary" :loading="saving" @click="save">保存</ElButton>
|
||||
</template>
|
||||
</ElDialog>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { createProfile, deleteProfile, fetchProfile, fetchProfiles, updateProfile } from '@/api/membership'
|
||||
|
||||
const loading = ref(false)
|
||||
const saving = ref(false)
|
||||
const visible = ref(false)
|
||||
const viewVisible = ref(false)
|
||||
const detail = ref<Record<string, any> | null>(null)
|
||||
|
||||
const text = (value: unknown) => (value === null || value === undefined || value === '' ? '—' : String(value))
|
||||
const keyword = ref('')
|
||||
const current = ref(1)
|
||||
const size = ref(10)
|
||||
const total = ref(0)
|
||||
const records = ref<Record<string, any>[]>([])
|
||||
const editingId = ref<number | null>(null)
|
||||
|
||||
const blank = () => ({
|
||||
email: '',
|
||||
password: '',
|
||||
kind: 'individual',
|
||||
memberNo: '',
|
||||
membershipStatus: 'active',
|
||||
joinedOn: '',
|
||||
expiresOn: '',
|
||||
feeStatus: 'unpaid',
|
||||
mobile: '',
|
||||
region: '',
|
||||
address: '',
|
||||
postalCode: '',
|
||||
remark: '',
|
||||
personName: '',
|
||||
gender: '',
|
||||
birthDate: '',
|
||||
idCard: '',
|
||||
education: '',
|
||||
major: '',
|
||||
jobTitle: '',
|
||||
practiceYears: null as number | null,
|
||||
employer: '',
|
||||
position: '',
|
||||
appraiserRegNo: '',
|
||||
qualificationNo: '',
|
||||
regValidUntil: '',
|
||||
photoFileId: null as number | null,
|
||||
orgName: '',
|
||||
creditCode: '',
|
||||
qualificationLevel: '',
|
||||
filingNo: '',
|
||||
legalPerson: '',
|
||||
contactName: '',
|
||||
contactPosition: '',
|
||||
contactMobile: '',
|
||||
contactEmail: '',
|
||||
officeAddress: ''
|
||||
})
|
||||
|
||||
const form = reactive(blank())
|
||||
|
||||
const load = async () => {
|
||||
loading.value = true
|
||||
try {
|
||||
const data = await fetchProfiles({ current: current.value, size: size.value, keyword: keyword.value.trim() })
|
||||
records.value = data.records || []
|
||||
total.value = data.total || 0
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const fill = (source: Record<string, any>) => {
|
||||
const next = blank()
|
||||
Object.assign(next, source, { password: '' })
|
||||
Object.assign(form, next)
|
||||
}
|
||||
|
||||
const openCreate = () => {
|
||||
editingId.value = null
|
||||
Object.assign(form, blank(), { password: '123456' })
|
||||
visible.value = true
|
||||
}
|
||||
|
||||
const openView = async (id: number) => {
|
||||
detail.value = await fetchProfile(id)
|
||||
viewVisible.value = true
|
||||
}
|
||||
|
||||
const openEdit = async (id: number) => {
|
||||
const data = await fetchProfile(id)
|
||||
editingId.value = id
|
||||
fill(data)
|
||||
visible.value = true
|
||||
}
|
||||
|
||||
const payload = () => ({
|
||||
...form,
|
||||
password: form.password.trim() || null,
|
||||
practiceYears: form.practiceYears
|
||||
})
|
||||
|
||||
const save = async () => {
|
||||
saving.value = true
|
||||
try {
|
||||
if (editingId.value) await updateProfile(editingId.value, payload())
|
||||
else await createProfile(payload())
|
||||
ElMessage.success('已保存')
|
||||
visible.value = false
|
||||
await load()
|
||||
} finally {
|
||||
saving.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const remove = async (row: Record<string, any>) => {
|
||||
await ElMessageBox.confirm(`删除「${row.displayName || row.email}」的会员档案?门户登录账号会保留。`, '删除会员', {
|
||||
type: 'warning'
|
||||
})
|
||||
await deleteProfile(row.id)
|
||||
ElMessage.success('已删除')
|
||||
await load()
|
||||
}
|
||||
|
||||
onMounted(load)
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.grid {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 0 16px;
|
||||
}
|
||||
|
||||
@media (max-width: 800px) {
|
||||
.grid {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,325 @@
|
||||
<template>
|
||||
<div v-loading="loading">
|
||||
<div class="flex flex-wrap items-center justify-between gap-3 mb-4">
|
||||
<p class="m-0 text-sm text-g-600">发布培训或会议公告。用餐日期按本场填写,报名时可多选。缴费只展示转账账户,不在线支付。</p>
|
||||
<ElButton v-auth="'membership:edit'" type="primary" @click="openEvent()">新增公告</ElButton>
|
||||
</div>
|
||||
<ElTable :data="events" border>
|
||||
<ElTableColumn prop="title" label="会议名称" min-width="180" />
|
||||
<ElTableColumn label="时间" min-width="180">
|
||||
<template #default="{ row }">{{ row.startsOn || '—' }} 至 {{ row.endsOn || '—' }}</template>
|
||||
</ElTableColumn>
|
||||
<ElTableColumn prop="place" label="地点" min-width="140" />
|
||||
<ElTableColumn label="名额" width="120">
|
||||
<template #default="{ row }">{{ row.registeredCount }}/{{ row.quota ?? '不限' }}</template>
|
||||
</ElTableColumn>
|
||||
<ElTableColumn label="发布" width="80">
|
||||
<template #default="{ row }">{{ row.published ? '已发布' : '草稿' }}</template>
|
||||
</ElTableColumn>
|
||||
<ElTableColumn label="操作" width="220" fixed="right">
|
||||
<template #default="{ row }">
|
||||
<ElButton link type="primary" @click="openRoster(row)">报名</ElButton>
|
||||
<ElButton v-auth="'membership:edit'" link type="primary" @click="openEvent(row)">编辑</ElButton>
|
||||
<ElButton v-auth="'membership:edit'" link type="danger" @click="removeEvent(row)">删除</ElButton>
|
||||
</template>
|
||||
</ElTableColumn>
|
||||
</ElTable>
|
||||
|
||||
<ElDialog v-model="eventVisible" :title="eventId ? '编辑公告' : '新增公告'" width="760px" align-center destroy-on-close>
|
||||
<ElForm label-width="110px">
|
||||
<ElFormItem label="会议名称" required><ElInput v-model="eventForm.title" /></ElFormItem>
|
||||
<div class="grid">
|
||||
<ElFormItem label="开始日期"><ElDatePicker v-model="eventForm.startsOn" value-format="YYYY-MM-DD" type="date" /></ElFormItem>
|
||||
<ElFormItem label="结束日期"><ElDatePicker v-model="eventForm.endsOn" value-format="YYYY-MM-DD" type="date" /></ElFormItem>
|
||||
<ElFormItem label="地点"><ElInput v-model="eventForm.place" /></ElFormItem>
|
||||
<ElFormItem label="名额"><ElInputNumber v-model="eventForm.quota" :min="1" /></ElFormItem>
|
||||
</div>
|
||||
<ElFormItem label="公告正文"><ArtWangEditor :key="editorKey" v-model="eventForm.bodyHtml" height="220px" /></ElFormItem>
|
||||
<ElFormItem label="用餐说明"><ElInput v-model="eventForm.mealNote" placeholder="例如:午餐自助餐 80 元/位" /></ElFormItem>
|
||||
<ElFormItem label="用餐日期">
|
||||
<div class="date-list">
|
||||
<div v-for="(_day, index) in eventForm.mealDates" :key="index" class="date-row">
|
||||
<ElInput v-model="eventForm.mealDates[index]" placeholder="例如 7月29日 或 2026-07-29" />
|
||||
<ElButton link type="danger" @click="eventForm.mealDates.splice(index, 1)">删除</ElButton>
|
||||
</div>
|
||||
<ElButton link type="primary" @click="eventForm.mealDates.push('')">添加用餐日期</ElButton>
|
||||
</div>
|
||||
</ElFormItem>
|
||||
<div class="grid">
|
||||
<ElFormItem label="账户名称"><ElInput v-model="eventForm.payeeName" /></ElFormItem>
|
||||
<ElFormItem label="开户行"><ElInput v-model="eventForm.bankName" /></ElFormItem>
|
||||
<ElFormItem label="账号"><ElInput v-model="eventForm.bankAccount" /></ElFormItem>
|
||||
<ElFormItem label="转账备注"><ElInput v-model="eventForm.transferNote" /></ElFormItem>
|
||||
</div>
|
||||
<ElFormItem label="食宿标准"><ElInput v-model="eventForm.lodgingNote" type="textarea" :rows="2" /></ElFormItem>
|
||||
<ElFormItem label="发布"><ElSwitch v-model="eventForm.published" /></ElFormItem>
|
||||
</ElForm>
|
||||
<template #footer>
|
||||
<ElButton @click="eventVisible = false">取消</ElButton>
|
||||
<ElButton type="primary" :loading="saving" @click="saveEvent">保存</ElButton>
|
||||
</template>
|
||||
</ElDialog>
|
||||
|
||||
<ElDialog v-model="rosterVisible" :title="`${rosterTitle} · 报名`" width="960px" align-center>
|
||||
<div class="mb-3 flex justify-end">
|
||||
<ElButton v-auth="'membership:edit'" type="primary" @click="openRegistration()">新增报名</ElButton>
|
||||
</div>
|
||||
<ElTable :data="registrations" border>
|
||||
<ElTableColumn prop="personName" label="姓名" width="100" />
|
||||
<ElTableColumn prop="orgName" label="单位" min-width="160" />
|
||||
<ElTableColumn prop="mobile" label="电话" width="130" />
|
||||
<ElTableColumn prop="lodgingLabel" label="住宿" width="100" />
|
||||
<ElTableColumn label="用餐日期" min-width="160">
|
||||
<template #default="{ row }">{{ (row.mealDates || []).join('、') || '—' }}</template>
|
||||
</ElTableColumn>
|
||||
<ElTableColumn label="操作" width="140">
|
||||
<template #default="{ row }">
|
||||
<ElButton v-auth="'membership:edit'" link type="primary" @click="openRegistration(row.id)">编辑</ElButton>
|
||||
<ElButton v-auth="'membership:edit'" link type="danger" @click="removeRegistration(row)">删除</ElButton>
|
||||
</template>
|
||||
</ElTableColumn>
|
||||
</ElTable>
|
||||
</ElDialog>
|
||||
|
||||
<ElDialog v-model="regVisible" :title="regId ? '编辑报名' : '新增报名'" width="720px" align-center destroy-on-close>
|
||||
<ElForm label-width="120px">
|
||||
<div class="grid">
|
||||
<ElFormItem label="所在地区" required><ElInput v-model="regForm.region" /></ElFormItem>
|
||||
<ElFormItem label="单位名称" required><ElInput v-model="regForm.orgName" /></ElFormItem>
|
||||
<ElFormItem label="姓名" required><ElInput v-model="regForm.personName" /></ElFormItem>
|
||||
<ElFormItem label="性别" required>
|
||||
<ElRadioGroup v-model="regForm.gender">
|
||||
<ElRadio value="male">男</ElRadio>
|
||||
<ElRadio value="female">女</ElRadio>
|
||||
</ElRadioGroup>
|
||||
</ElFormItem>
|
||||
<ElFormItem label="职务" required><ElInput v-model="regForm.position" /></ElFormItem>
|
||||
<ElFormItem label="身份证号" required><ElInput v-model="regForm.idCard" /></ElFormItem>
|
||||
<ElFormItem label="联系电话" required><ElInput v-model="regForm.mobile" maxlength="11" /></ElFormItem>
|
||||
<ElFormItem label="注册证号" required><ElInput v-model="regForm.appraiserRegNo" maxlength="10" /></ElFormItem>
|
||||
<ElFormItem label="邮箱" required><ElInput v-model="regForm.email" /></ElFormItem>
|
||||
<ElFormItem label="住宿" required>
|
||||
<ElRadioGroup v-model="regForm.lodging">
|
||||
<ElRadio value="association">协会代订</ElRadio>
|
||||
<ElRadio value="self">自理</ElRadio>
|
||||
</ElRadioGroup>
|
||||
</ElFormItem>
|
||||
</div>
|
||||
<template v-if="regForm.lodging === 'association'">
|
||||
<ElFormItem label="房间">
|
||||
<ElCheckbox v-model="regForm.roomStandard">标间</ElCheckbox>
|
||||
<ElInputNumber v-if="regForm.roomStandard" v-model="regForm.standardCount" :min="1" :max="99" class="ml-2" />
|
||||
<ElCheckbox v-model="regForm.roomSingle" class="ml-4">单间</ElCheckbox>
|
||||
<ElInputNumber v-if="regForm.roomSingle" v-model="regForm.singleCount" :min="1" :max="99" class="ml-2" />
|
||||
</ElFormItem>
|
||||
</template>
|
||||
<ElFormItem label="是否用餐" required>
|
||||
<ElRadioGroup v-model="regForm.dine">
|
||||
<ElRadio :value="true">是</ElRadio>
|
||||
<ElRadio :value="false">否</ElRadio>
|
||||
</ElRadioGroup>
|
||||
<span v-if="rosterMealNote" class="ml-3 text-sm text-g-600">{{ rosterMealNote }}</span>
|
||||
</ElFormItem>
|
||||
<ElFormItem v-if="regForm.dine" label="用餐日期">
|
||||
<ElCheckboxGroup v-model="regForm.mealDates">
|
||||
<ElCheckbox v-for="day in rosterMealDates" :key="day" :value="day">{{ day }}</ElCheckbox>
|
||||
</ElCheckboxGroup>
|
||||
<p v-if="!rosterMealDates.length" class="m-0 text-sm text-g-600">本场还没有配置用餐日期</p>
|
||||
</ElFormItem>
|
||||
</ElForm>
|
||||
<template #footer>
|
||||
<ElButton @click="regVisible = false">取消</ElButton>
|
||||
<ElButton type="primary" :loading="saving" @click="saveRegistration">保存</ElButton>
|
||||
</template>
|
||||
</ElDialog>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import {
|
||||
createEvent,
|
||||
createRegistration,
|
||||
deleteEvent,
|
||||
deleteRegistration,
|
||||
fetchEvents,
|
||||
fetchRegistration,
|
||||
fetchRegistrations,
|
||||
updateEvent,
|
||||
updateRegistration
|
||||
} from '@/api/membership'
|
||||
|
||||
const loading = ref(false)
|
||||
const saving = ref(false)
|
||||
const events = ref<Record<string, any>[]>([])
|
||||
const eventVisible = ref(false)
|
||||
const eventId = ref<number | null>(null)
|
||||
const editorKey = ref(0)
|
||||
const rosterVisible = ref(false)
|
||||
const rosterEventId = ref<number | null>(null)
|
||||
const rosterTitle = ref('')
|
||||
const rosterMealDates = ref<string[]>([])
|
||||
const rosterMealNote = ref('')
|
||||
const registrations = ref<Record<string, any>[]>([])
|
||||
const regVisible = ref(false)
|
||||
const regId = ref<number | null>(null)
|
||||
|
||||
const blankEvent = () => ({
|
||||
title: '',
|
||||
place: '',
|
||||
startsOn: '',
|
||||
endsOn: '',
|
||||
quota: null as number | null,
|
||||
bodyHtml: '',
|
||||
published: false,
|
||||
mealNote: '',
|
||||
mealDates: [] as string[],
|
||||
payeeName: '',
|
||||
bankName: '',
|
||||
bankAccount: '',
|
||||
transferNote: '',
|
||||
lodgingNote: ''
|
||||
})
|
||||
const eventForm = reactive(blankEvent())
|
||||
|
||||
const blankReg = () => ({
|
||||
region: '',
|
||||
orgName: '',
|
||||
personName: '',
|
||||
gender: 'male',
|
||||
position: '',
|
||||
idCard: '',
|
||||
mobile: '',
|
||||
appraiserRegNo: '',
|
||||
email: '',
|
||||
lodging: 'self',
|
||||
roomStandard: false,
|
||||
roomSingle: false,
|
||||
standardCount: 1,
|
||||
singleCount: 1,
|
||||
dine: false,
|
||||
mealDates: [] as string[]
|
||||
})
|
||||
const regForm = reactive(blankReg())
|
||||
|
||||
const load = async () => {
|
||||
loading.value = true
|
||||
try {
|
||||
const data = await fetchEvents()
|
||||
events.value = data.items || []
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const openEvent = (row?: Record<string, any>) => {
|
||||
const next = blankEvent()
|
||||
if (row) {
|
||||
eventId.value = row.id
|
||||
Object.assign(next, row, { mealDates: [...(row.mealDates || [])] })
|
||||
} else {
|
||||
eventId.value = null
|
||||
}
|
||||
Object.assign(eventForm, next)
|
||||
editorKey.value += 1
|
||||
eventVisible.value = true
|
||||
}
|
||||
|
||||
const saveEvent = async () => {
|
||||
saving.value = true
|
||||
try {
|
||||
const data = {
|
||||
...eventForm,
|
||||
mealDates: eventForm.mealDates.map((item) => item.trim()).filter(Boolean)
|
||||
}
|
||||
if (eventId.value) await updateEvent(eventId.value, data)
|
||||
else await createEvent(data)
|
||||
ElMessage.success('已保存')
|
||||
eventVisible.value = false
|
||||
await load()
|
||||
} finally {
|
||||
saving.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const removeEvent = async (row: Record<string, any>) => {
|
||||
await ElMessageBox.confirm(`删除「${row.title}」及其报名记录?`, '删除公告', { type: 'warning' })
|
||||
await deleteEvent(row.id)
|
||||
ElMessage.success('已删除')
|
||||
await load()
|
||||
}
|
||||
|
||||
const loadRoster = async () => {
|
||||
if (!rosterEventId.value) return
|
||||
const data = await fetchRegistrations(rosterEventId.value)
|
||||
registrations.value = data.items || []
|
||||
}
|
||||
|
||||
const openRoster = async (row: Record<string, any>) => {
|
||||
rosterEventId.value = row.id
|
||||
rosterTitle.value = row.title
|
||||
rosterMealDates.value = row.mealDates || []
|
||||
rosterMealNote.value = row.mealNote || ''
|
||||
rosterVisible.value = true
|
||||
await loadRoster()
|
||||
}
|
||||
|
||||
const openRegistration = async (id?: number) => {
|
||||
const next = blankReg()
|
||||
if (id) {
|
||||
const data = await fetchRegistration(id)
|
||||
regId.value = id
|
||||
Object.assign(next, data, { mealDates: [...(data.mealDates || [])] })
|
||||
} else {
|
||||
regId.value = null
|
||||
}
|
||||
Object.assign(regForm, next)
|
||||
regVisible.value = true
|
||||
}
|
||||
|
||||
const saveRegistration = async () => {
|
||||
if (!rosterEventId.value) return
|
||||
saving.value = true
|
||||
try {
|
||||
const data = { ...regForm, mealDates: regForm.dine ? regForm.mealDates : [] }
|
||||
if (regId.value) await updateRegistration(regId.value, data)
|
||||
else await createRegistration(rosterEventId.value, data)
|
||||
ElMessage.success('已保存')
|
||||
regVisible.value = false
|
||||
await loadRoster()
|
||||
await load()
|
||||
} finally {
|
||||
saving.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const removeRegistration = async (row: Record<string, any>) => {
|
||||
await ElMessageBox.confirm(`删除 ${row.personName} 的报名?`, '删除报名', { type: 'warning' })
|
||||
await deleteRegistration(row.id)
|
||||
ElMessage.success('已删除')
|
||||
await loadRoster()
|
||||
await load()
|
||||
}
|
||||
|
||||
onMounted(load)
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.grid {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 0 16px;
|
||||
}
|
||||
|
||||
.date-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.date-row {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
align-items: center;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,35 @@
|
||||
<template>
|
||||
<div class="flex flex-col gap-4">
|
||||
<ElTabs v-model="activeTab" type="border-card">
|
||||
<ElTabPane label="会员机构" name="orgs">
|
||||
<OrgLinks v-if="activeTab === 'orgs'" />
|
||||
</ElTabPane>
|
||||
<ElTabPane label="会员信息" name="profiles">
|
||||
<Profiles v-if="activeTab === 'profiles'" />
|
||||
</ElTabPane>
|
||||
<ElTabPane label="会员资讯" name="notices">
|
||||
<AboutColumnEditor
|
||||
v-if="activeTab === 'notices'"
|
||||
category="member_notices"
|
||||
title="会员资讯"
|
||||
edit-auth="membership:edit"
|
||||
enable-cover
|
||||
/>
|
||||
</ElTabPane>
|
||||
<ElTabPane label="培训报名" name="trainings">
|
||||
<Trainings v-if="activeTab === 'trainings'" />
|
||||
</ElTabPane>
|
||||
</ElTabs>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import AboutColumnEditor from '@/views/about/components/AboutColumnEditor.vue'
|
||||
import OrgLinks from './components/OrgLinks.vue'
|
||||
import Profiles from './components/Profiles.vue'
|
||||
import Trainings from './components/Trainings.vue'
|
||||
|
||||
defineOptions({ name: 'MemberService' })
|
||||
|
||||
const activeTab = ref('orgs')
|
||||
</script>
|
||||
@@ -1,3 +1,3 @@
|
||||
# 报告查询对照备案,报告审核先做演示
|
||||
# 报告查询对照备案
|
||||
|
||||
公众从首页「报告查询」进入报告核验,按报告编号对照工作人员在报告中心发布的备案。查到或查不到都写明以出具机构数据为准,协会结果仅供参考,结论不用「真」「伪」。不做核验码,不公开报告原件,会员不在门户提交备案。首页「报告审核」进入同栏目的演示页:可选文件、可提问,提交后只提示尚未开通,不保存、不调用模型。投诉举报从首页进入行业自律,地址仍可在后台调整。原先把这两项首页入口做成外链,是为了在规则未定时避免假结论;规则现已定为备案对照和免责说明,所以这两项改为固定站内页。
|
||||
公众从首页「报告查询」进入报告核验,按报告编号对照工作人员在报告中心发布的备案。查到或查不到都写明以出具机构数据为准,协会结果仅供参考,结论不用「真」「伪」。不做核验码,不公开报告原件,会员不在门户提交备案。投诉举报从首页进入行业自律,地址仍可在后台调整。报告查询的公开地址固定为站内页。门户不提供报告审核入口,也不做演示提问页。
|
||||
@@ -0,0 +1,5 @@
|
||||
# 会员服务是站内四个模块
|
||||
|
||||
合同 8.1 把中房学和住建厅写成对接,8.2 把培训报名写成链到甘肃省继续教育系统。协会确认的本期做法是:顶栏「会员服务」改为固定栏目,不再用快捷菜单外链。
|
||||
|
||||
会员机构只配置图片、名称和地址,新窗口打开,不做账号打通或数据回写。会员资讯用栏目文章发布章程和管理办法。协会会员由工作人员建档,并同步一条门户邮箱账号,会员登录后只看本人档案。培训报名在本站按旧会议报名表办理:每场公告自己配置用餐日期,报名时可以多选;转账账户写在公告里,不做在线支付。省继续教育系统若仍要入口,放在会员机构或在线教育的外链卡片上。
|
||||
+2
-1
@@ -24,10 +24,11 @@
|
||||
|
||||
- 运行时做成两套独立网站或两套完整页面代码。两套外观若要保留,只能是同一套页面下的两个主题包:各自含配色、字体、页头、页脚和首页模块排布,不含栏目页面的第二份实现。访客不提供换肤。后台是否开放切换,等协会确认后再做。
|
||||
- 数据看板和数据挖掘的真实图表。
|
||||
- 在报告审核页保存文件、调用模型或给出审核结论。查询页只对照已发布备案,见根目录 `docs/adr/0010-report-query-is-filing-lookup.md`。
|
||||
- 报告审核页。查询页只对照已发布备案,见根目录 `docs/adr/0010-report-query-is-filing-lookup.md`。
|
||||
- 智能估价平台的评估流程。
|
||||
- 中房学、住建厅窗口的对接页面。外链地址以后台配置为准。
|
||||
- 继续教育的学习过程、进度、学分,以及考试报名和缴费。门户栏目只做在线教育外链卡片和教育公告,见 `docs/adr/0011-continuing-education-is-links-and-notices.md`。
|
||||
- 会员服务做成站内栏目:外链卡片、会员档案查看、会员资讯和培训报名。中房学、住建厅仍只是外链,培训报名不做在线支付,见 `docs/adr/0013-member-service-is-four-modules.md`。
|
||||
- 行业自律做成投诉举报表单,以及警示案例、诚信档案、结果公示三类栏目文章,见 `docs/adr/0012-industry-discipline-articles-and-complaint-code.md`。
|
||||
|
||||
## 页面约束
|
||||
|
||||
+18
-28
@@ -40,13 +40,23 @@
|
||||
background: var(--c) center/cover no-repeat; opacity: .85;
|
||||
}
|
||||
.honor {
|
||||
width: 140px; height: 72px; background: center/cover no-repeat var(--honor1);
|
||||
border: 1px solid var(--line); position: relative;
|
||||
width: 140px; margin: 0; display: flex; flex-direction: column; align-items: center; gap: 6px;
|
||||
}
|
||||
.honor.b { background-image: var(--honor2); }
|
||||
.honor span {
|
||||
position: absolute; inset: auto 0 0; padding: 4px 6px;
|
||||
background: rgba(0,0,0,.45); color: #fff; font-size: 11px;
|
||||
.honor i {
|
||||
width: 140px; height: 72px; flex: none; border: 1px solid var(--line);
|
||||
background: center/cover no-repeat var(--honor1);
|
||||
}
|
||||
.honor figcaption {
|
||||
width: 100%; margin: 0; color: var(--muted); font-size: 12px; line-height: 1.45;
|
||||
text-align: center;
|
||||
}
|
||||
.member-rows { display: flex; flex-direction: column; gap: 10px; padding: 14px 0; }
|
||||
.member-rows .track { padding: 0; gap: 0; }
|
||||
.member-set { display: flex; gap: 16px; padding-right: 16px; flex: none; }
|
||||
.member-rows .track.stagger { animation-name: slide-stagger; }
|
||||
@keyframes slide-stagger {
|
||||
from { transform: translateX(-118px); }
|
||||
to { transform: translateX(calc(-50% - 118px)); }
|
||||
}
|
||||
footer.site { margin-top: 28px; padding: 28px 0 28px; background: var(--foot); color: var(--foot-fg); font-size: 13px; }
|
||||
footer.site h3 { margin: 0 0 10px; font-size: 14px; letter-spacing: .08em; }
|
||||
@@ -174,15 +184,6 @@
|
||||
}
|
||||
#tech .cat a:last-child { border-bottom: 0; }
|
||||
#tech .cat a:hover { color: var(--c); }
|
||||
#tech .hot {
|
||||
display: grid; grid-template-columns: repeat(3, 1fr); gap: 8px;
|
||||
}
|
||||
#tech .hot a {
|
||||
display: grid; place-items: center; text-align: center;
|
||||
min-height: 40px; padding: 8px 6px; border-radius: 8px;
|
||||
font-size: 14px; letter-spacing: .04em;
|
||||
color: #fff; background: linear-gradient(160deg, #1677ff, #0a4fd6);
|
||||
}
|
||||
#tech .board {
|
||||
padding: 14px; border-radius: 14px; display: flex; flex-direction: column; gap: 10px; min-height: 100%;
|
||||
}
|
||||
@@ -320,17 +321,8 @@
|
||||
color: #fff; font-size: 14px; font-weight: 500; line-height: 1.45;
|
||||
}
|
||||
#brand .gate { margin-top: 22px; }
|
||||
#brand .band {
|
||||
display: grid; grid-template-columns: repeat(3, 1fr); gap: 12px;
|
||||
}
|
||||
#brand .band a {
|
||||
text-align: center; padding: 14px 8px;
|
||||
font-size: 15px; letter-spacing: .18em; font-weight: 600;
|
||||
color: #fff; background: var(--c); border-radius: 10px;
|
||||
}
|
||||
#brand .band a:hover { background: #064a86; }
|
||||
#brand .rows {
|
||||
margin-top: 14px; display: grid; grid-template-columns: repeat(3, 1fr); gap: 0;
|
||||
margin-top: 0; display: grid; grid-template-columns: repeat(var(--entry-cols, 3), minmax(0, 1fr)); gap: 0;
|
||||
border: 1px solid var(--line); border-radius: var(--r); overflow: hidden; background: #fff;
|
||||
}
|
||||
#brand .rows .cat {
|
||||
@@ -356,10 +348,9 @@
|
||||
font-size: 18px; font-weight: 600; letter-spacing: .16em; color: #12304f;
|
||||
}
|
||||
#brand .marquee { background: var(--surface); border-radius: var(--r); }
|
||||
#brand .honor { border-radius: 8px; overflow: hidden; }
|
||||
#brand .honor i { border-radius: 8px; }
|
||||
#brand .member { border-radius: 10px; }
|
||||
#brand .map { border-radius: 10px; }
|
||||
#brand .honor span { background: rgba(6,36,63,.62); letter-spacing: .08em; }
|
||||
|
||||
@media (max-width: 860px) {
|
||||
#tech .cols, #tech .service-row, #tech .foot,
|
||||
@@ -391,6 +382,5 @@
|
||||
}
|
||||
#brand .slogan h2, #brand .slogan p { text-align: center; }
|
||||
#brand nav.menu { justify-content: flex-start; padding: 0 16px; gap: 8px 24px; }
|
||||
#brand .band { grid-template-columns: 1fr; }
|
||||
#brand .rows .cat + .cat { border-left: 0; border-top: 1px solid var(--line); }
|
||||
}
|
||||
@@ -0,0 +1,716 @@
|
||||
<template>
|
||||
<Teleport to="body">
|
||||
<div class="mask" @click.self="emit('close')">
|
||||
<div class="workspace" role="dialog" aria-modal="true" aria-labelledby="coach-title">
|
||||
<aside class="side">
|
||||
<div class="side-head">
|
||||
<div class="brand">
|
||||
<img class="logo" src="/association-logo.jpg" alt="" />
|
||||
<div>
|
||||
<h2 id="coach-title">估价模版智能体</h2>
|
||||
<p>制作报告模版</p>
|
||||
</div>
|
||||
</div>
|
||||
<button type="button" class="primary wide" :disabled="sending" @click="createSession">+ 新会话</button>
|
||||
</div>
|
||||
<div class="session-list">
|
||||
<p v-if="!sessions.length" class="empty">暂无会话</p>
|
||||
<div
|
||||
v-for="item in sessions"
|
||||
:key="item.id"
|
||||
class="session"
|
||||
:class="{ active: item.id === activeId }"
|
||||
@click="openSession(item.id)"
|
||||
>
|
||||
<div class="session-copy">
|
||||
<div class="title" :title="item.title">{{ item.title }}</div>
|
||||
<div class="meta">{{ formatTime(item.updatedAt) }}</div>
|
||||
</div>
|
||||
<div class="more-wrap" :class="{ open: menuId === item.id }" @click.stop>
|
||||
<button type="button" class="more-btn" aria-label="更多操作" @click="toggleMenu(item.id)">···</button>
|
||||
<div v-if="menuId === item.id" class="menu" role="menu">
|
||||
<button type="button" @click="rename(item)">重命名</button>
|
||||
<button type="button" class="danger" @click="remove(item)">删除</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="side-foot">
|
||||
<div class="user">
|
||||
<span class="avatar profile-avatar" aria-hidden="true">
|
||||
<img src="/user/avatar.webp" alt="" />
|
||||
</span>
|
||||
<div>
|
||||
<div class="name">{{ displayName || username }}</div>
|
||||
<div class="account">{{ username }}</div>
|
||||
</div>
|
||||
</div>
|
||||
<button type="button" class="logout" @click="emit('close')">关闭</button>
|
||||
</div>
|
||||
</aside>
|
||||
<div class="main">
|
||||
<div ref="scroller" class="thread" role="log" aria-live="polite">
|
||||
<p v-if="loading" class="empty">正在打开对话</p>
|
||||
<article v-for="item in messages" :key="item.id" class="row" :class="item.role">
|
||||
<span v-if="item.role === 'assistant'" class="avatar ai-avatar" aria-hidden="true">
|
||||
<img src="/association-logo.jpg" alt="" />
|
||||
</span>
|
||||
<span v-else class="avatar user-avatar" aria-hidden="true">
|
||||
<img src="/user/chat.png" alt="" />
|
||||
</span>
|
||||
<div class="bubble">
|
||||
<details v-if="item.thought" class="thought">
|
||||
<summary>思考过程</summary>
|
||||
<p>{{ item.thought }}</p>
|
||||
</details>
|
||||
<ul v-if="item.attachments.length" class="thumb-grid">
|
||||
<li v-for="(name, index) in item.attachments" :key="`${name}-${index}`" class="thumb-card">
|
||||
<div class="thumb-preview">
|
||||
<span class="thumb-file" aria-hidden="true">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M14 3H7a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8l-5-5Z" />
|
||||
<path d="M14 3v5h5" />
|
||||
</svg>
|
||||
<b>{{ fileExt(name) }}</b>
|
||||
</span>
|
||||
</div>
|
||||
<div class="thumb-name" :title="name">{{ name }}</div>
|
||||
</li>
|
||||
</ul>
|
||||
<div v-if="item.role === 'assistant' && item.content" class="md" v-html="renderAnswerMarkdown(item.content)" />
|
||||
<p v-else-if="item.content">{{ item.content }}</p>
|
||||
<button
|
||||
v-if="item.kind === 'template' && !item.pending"
|
||||
type="button"
|
||||
class="thumb-card download"
|
||||
:disabled="isDownloading(item.id)"
|
||||
:aria-busy="isDownloading(item.id)"
|
||||
:aria-label="isDownloading(item.id) ? `正在下载${fileName(item)}` : `下载${fileName(item)}`"
|
||||
@click="download(item)"
|
||||
>
|
||||
<span class="thumb-preview">
|
||||
<span class="thumb-file" aria-hidden="true">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M14 3H7a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8l-5-5Z" />
|
||||
<path d="M14 3v5h5" />
|
||||
</svg>
|
||||
<b>{{ item.draftFormat === "pptx" ? "PPTX" : "DOCX" }}</b>
|
||||
</span>
|
||||
</span>
|
||||
<span class="thumb-name" :title="fileName(item)">{{ fileName(item) }}</span>
|
||||
<span v-if="isDownloading(item.id)" class="download-mask">
|
||||
<span class="typing" aria-hidden="true"><span /><span /><span /></span>
|
||||
下载中
|
||||
</span>
|
||||
</button>
|
||||
<div v-else-if="item.pending" class="typing" aria-label="正在整理"><span /><span /><span /></div>
|
||||
<div v-if="showPrompts(item)" class="suggest">
|
||||
<button v-for="prompt in prompts" :key="prompt" type="button" @click="send(prompt)">{{ prompt }}</button>
|
||||
</div>
|
||||
</div>
|
||||
</article>
|
||||
</div>
|
||||
<form class="composer" @submit.prevent="send()">
|
||||
<ul v-if="pending.length" class="thumb-grid">
|
||||
<li v-for="item in pending" :key="item.id" class="thumb-card">
|
||||
<div class="thumb-preview">
|
||||
<img v-if="item.previewUrl" :src="item.previewUrl" :alt="item.name" />
|
||||
<span v-else class="thumb-file" aria-hidden="true">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M14 3H7a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8l-5-5Z" />
|
||||
<path d="M14 3v5h5" />
|
||||
</svg>
|
||||
<b>{{ fileExt(item.name) }}</b>
|
||||
</span>
|
||||
</div>
|
||||
<div class="thumb-name" :title="item.name">{{ item.name }}</div>
|
||||
<button type="button" class="thumb-remove" aria-label="移除附件" @click="removePending(item.id)">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round">
|
||||
<path d="M6 6l12 12M18 6 6 18" />
|
||||
</svg>
|
||||
</button>
|
||||
</li>
|
||||
</ul>
|
||||
<div class="composer-row">
|
||||
<button type="button" class="icon-btn" title="上传附件" aria-label="上传附件" :disabled="sending" @click="fileInput?.click()">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M14 3H7a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8l-5-5Z" />
|
||||
<path d="M14 3v5h5" />
|
||||
<path d="M12 18v-6" />
|
||||
<path d="M9.5 14.5 12 12l2.5 2.5" />
|
||||
</svg>
|
||||
</button>
|
||||
<label class="sr-only" for="template-coach-draft">输入整理要求</label>
|
||||
<textarea
|
||||
id="template-coach-draft"
|
||||
v-model="draft"
|
||||
rows="1"
|
||||
maxlength="2000"
|
||||
placeholder="说明章节,或上传历史文稿。Enter 发送"
|
||||
:disabled="sending"
|
||||
@keydown.enter.exact.prevent="send()"
|
||||
/>
|
||||
<button type="submit" class="primary" :disabled="!canSend">发送</button>
|
||||
</div>
|
||||
<div class="hint-row">
|
||||
<p class="hint">支持 pdf、docx、pptx、txt、md、xlsx、csv、jpg、png、webp。下载后请自行修改,再上传到模版列表。</p>
|
||||
<span class="pill">只制作模版</span>
|
||||
</div>
|
||||
</form>
|
||||
<p v-if="error" class="toast" role="status">{{ error }}</p>
|
||||
</div>
|
||||
<input
|
||||
ref="fileInput"
|
||||
class="sr-only"
|
||||
type="file"
|
||||
accept=".pdf,.docx,.pptx,.txt,.md,.xlsx,.xls,.csv,.jpg,.jpeg,.png,.webp"
|
||||
@change="onFile"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</Teleport>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { renderAnswerMarkdown } from "~/utils/answerMarkdown"
|
||||
|
||||
type CoachMessage = {
|
||||
id: number
|
||||
role: "assistant" | "user"
|
||||
content: string
|
||||
thought: string
|
||||
attachments: string[]
|
||||
kind?: string
|
||||
draftFormat?: string
|
||||
draftName?: string
|
||||
pending?: boolean
|
||||
}
|
||||
type PendingFile = { id: number; name: string; previewUrl: string }
|
||||
type SessionItem = { id: number; title: string; updatedAt: string }
|
||||
|
||||
const emit = defineEmits<{ close: [] }>()
|
||||
const { token, username, displayName } = useAgentAuth()
|
||||
const { get, post, upload } = useSiteApi()
|
||||
const apiBase = siteApiBase()
|
||||
|
||||
const prompts = [
|
||||
"按我上传的历史文稿整理成 Word 模版",
|
||||
"把当前提纲改成 PPT",
|
||||
"第1章要写坐落、用途、面积和权利状况",
|
||||
]
|
||||
const messages = ref<CoachMessage[]>([])
|
||||
const sessions = ref<SessionItem[]>([])
|
||||
const activeId = ref<number | null>(null)
|
||||
const menuId = ref<number | null>(null)
|
||||
const pending = ref<PendingFile[]>([])
|
||||
const draft = ref("")
|
||||
const sending = ref(false)
|
||||
const downloadingIds = ref<number[]>([])
|
||||
const loading = ref(true)
|
||||
const error = ref("")
|
||||
const scroller = ref<HTMLElement | null>(null)
|
||||
const fileInput = ref<HTMLInputElement | null>(null)
|
||||
let localId = 0
|
||||
|
||||
const canSend = computed(() => (draft.value.trim().length > 0 || pending.value.length > 0) && !sending.value && !loading.value && activeId.value !== null)
|
||||
const hasUserMessage = computed(() => messages.value.some((item) => item.role === "user"))
|
||||
|
||||
function formatTime(value: string) {
|
||||
const date = new Date(value)
|
||||
if (Number.isNaN(date.getTime())) return ""
|
||||
const month = date.getMonth() + 1
|
||||
const day = date.getDate()
|
||||
const hour = String(date.getHours()).padStart(2, "0")
|
||||
const minute = String(date.getMinutes()).padStart(2, "0")
|
||||
return `${month}/${day} ${hour}:${minute}`
|
||||
}
|
||||
|
||||
function showPrompts(item: CoachMessage) {
|
||||
return item.role === "assistant" && item.id === messages.value[0]?.id && !hasUserMessage.value && !sending.value
|
||||
}
|
||||
|
||||
function fileExt(name: string) {
|
||||
const ext = name.includes(".") ? name.slice(name.lastIndexOf(".") + 1).trim().toUpperCase() : ""
|
||||
return ext && ext.length <= 5 ? ext : "FILE"
|
||||
}
|
||||
|
||||
function fileName(item: CoachMessage) {
|
||||
const format = item.draftFormat === "pptx" ? "pptx" : "docx"
|
||||
return `${item.draftName?.trim() || "估价模版"}.${format}`
|
||||
}
|
||||
|
||||
function notify(message: string) {
|
||||
error.value = message
|
||||
window.setTimeout(() => {
|
||||
if (error.value === message) error.value = ""
|
||||
}, 2800)
|
||||
}
|
||||
|
||||
function parseSse(line: string) {
|
||||
if (!line.startsWith("data:")) return null
|
||||
try {
|
||||
return JSON.parse(line.slice(5).trim()) as {
|
||||
type: string
|
||||
text?: string
|
||||
message?: string
|
||||
messageId?: number
|
||||
kind?: string
|
||||
draftFormat?: string
|
||||
draftName?: string
|
||||
}
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
async function scrollToEnd() {
|
||||
await nextTick()
|
||||
if (scroller.value) scroller.value.scrollTop = scroller.value.scrollHeight
|
||||
}
|
||||
|
||||
function applyOpened(body: { sessionId: number; sessions: SessionItem[]; items: CoachMessage[] }) {
|
||||
sessions.value = body.sessions
|
||||
activeId.value = body.sessionId
|
||||
messages.value = body.items.map((item) => ({ ...item, attachments: item.attachments || [], pending: false }))
|
||||
menuId.value = null
|
||||
}
|
||||
|
||||
async function load() {
|
||||
loading.value = true
|
||||
try {
|
||||
const body = await get<{ sessionId: number; sessions: SessionItem[]; items: CoachMessage[] }>(
|
||||
"/member/valuation/template-coach",
|
||||
token.value,
|
||||
)
|
||||
applyOpened(body)
|
||||
} catch (exc: any) {
|
||||
notify(exc?.data?.detail || "暂时打不开模版对话")
|
||||
} finally {
|
||||
loading.value = false
|
||||
await scrollToEnd()
|
||||
}
|
||||
}
|
||||
|
||||
async function openSession(id: number) {
|
||||
if (sending.value || id === activeId.value) {
|
||||
menuId.value = null
|
||||
return
|
||||
}
|
||||
menuId.value = null
|
||||
try {
|
||||
const body = await get<{ sessionId: number; sessions: SessionItem[]; items: CoachMessage[] }>(
|
||||
`/member/valuation/template-coach/sessions/${id}`,
|
||||
token.value,
|
||||
)
|
||||
applyOpened(body)
|
||||
draft.value = ""
|
||||
pending.value = []
|
||||
await scrollToEnd()
|
||||
} catch (exc: any) {
|
||||
notify(exc?.data?.detail || "没能打开这段会话")
|
||||
}
|
||||
}
|
||||
|
||||
async function createSession() {
|
||||
if (sending.value) return
|
||||
sending.value = true
|
||||
try {
|
||||
const body = await post<{ sessionId: number; sessions: SessionItem[]; items: CoachMessage[] }>(
|
||||
"/member/valuation/template-coach/sessions",
|
||||
{},
|
||||
token.value,
|
||||
)
|
||||
applyOpened(body)
|
||||
draft.value = ""
|
||||
pending.value = []
|
||||
} catch (exc: any) {
|
||||
notify(exc?.data?.detail || "没能开始新会话")
|
||||
} finally {
|
||||
sending.value = false
|
||||
await scrollToEnd()
|
||||
}
|
||||
}
|
||||
|
||||
function toggleMenu(id: number) {
|
||||
menuId.value = menuId.value === id ? null : id
|
||||
}
|
||||
|
||||
async function rename(item: SessionItem) {
|
||||
menuId.value = null
|
||||
const title = window.prompt("重命名会话", item.title)?.trim().slice(0, 40)
|
||||
if (!title) return
|
||||
try {
|
||||
const updated = await patch<SessionItem>(`/member/valuation/template-coach/sessions/${item.id}`, { title }, token.value)
|
||||
item.title = updated.title
|
||||
item.updatedAt = updated.updatedAt
|
||||
} catch (exc: any) {
|
||||
notify(exc?.data?.detail || "重命名失败")
|
||||
}
|
||||
}
|
||||
|
||||
async function remove(item: SessionItem) {
|
||||
menuId.value = null
|
||||
if (!window.confirm(`确定删除会话「${item.title}」?不可恢复。`)) return
|
||||
try {
|
||||
await del(`/member/valuation/template-coach/sessions/${item.id}`, token.value)
|
||||
} catch (exc: any) {
|
||||
notify(exc?.data?.detail || "删除失败")
|
||||
return
|
||||
}
|
||||
sessions.value = sessions.value.filter((row) => row.id !== item.id)
|
||||
if (activeId.value === item.id) {
|
||||
if (sessions.value[0]) await openSession(sessions.value[0].id)
|
||||
else await createSession()
|
||||
}
|
||||
}
|
||||
|
||||
async function onFile(event: Event) {
|
||||
const input = event.target as HTMLInputElement
|
||||
const file = input.files?.[0]
|
||||
input.value = ""
|
||||
if (!file || !token.value) return
|
||||
if (pending.value.length >= 5) {
|
||||
notify("一次最多 5 个附件")
|
||||
return
|
||||
}
|
||||
const extension = file.name.includes(".") ? file.name.slice(file.name.lastIndexOf(".") + 1).toLowerCase() : ""
|
||||
if (extension === "doc" || extension === "ppt") {
|
||||
notify("请另存为 docx 或 pptx 后再上传")
|
||||
return
|
||||
}
|
||||
const previewUrl = file.type.startsWith("image/") ? URL.createObjectURL(file) : ""
|
||||
const data = new FormData()
|
||||
data.append("file", file)
|
||||
try {
|
||||
const saved = await upload<{ id: number; name: string }>("/member/valuation/template-coach/files", data, token.value)
|
||||
pending.value.push({ id: saved.id, name: saved.name, previewUrl })
|
||||
} catch (exc: any) {
|
||||
if (previewUrl) URL.revokeObjectURL(previewUrl)
|
||||
notify(exc?.data?.detail || "附件上传失败")
|
||||
}
|
||||
}
|
||||
|
||||
function removePending(id: number) {
|
||||
const item = pending.value.find((file) => file.id === id)
|
||||
if (item?.previewUrl) URL.revokeObjectURL(item.previewUrl)
|
||||
pending.value = pending.value.filter((file) => file.id !== id)
|
||||
}
|
||||
|
||||
async function send(preset?: string) {
|
||||
const query = (preset || draft.value).trim()
|
||||
const files = preset ? [] : pending.value.slice()
|
||||
if ((!query && !files.length) || sending.value) return
|
||||
sending.value = true
|
||||
draft.value = ""
|
||||
pending.value = preset ? pending.value : []
|
||||
messages.value.push({
|
||||
id: nextLocalId(),
|
||||
role: "user",
|
||||
content: query || "请结合附件整理模版。",
|
||||
thought: "",
|
||||
attachments: files.map((item) => item.name),
|
||||
})
|
||||
messages.value.push({ id: nextLocalId(), role: "assistant", content: "", thought: "", attachments: [], pending: true })
|
||||
const assistant = messages.value[messages.value.length - 1]
|
||||
await scrollToEnd()
|
||||
try {
|
||||
const response = await fetch(`${apiBase}/member/valuation/template-coach/messages`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: `Bearer ${token.value}`,
|
||||
"Content-Type": "application/json",
|
||||
Accept: "text/event-stream",
|
||||
},
|
||||
body: JSON.stringify({ query, fileIds: files.map((item) => item.id), sessionId: activeId.value }),
|
||||
})
|
||||
if (!response.ok || !response.body) throw new Error("暂时无法整理")
|
||||
const reader = response.body.getReader()
|
||||
const decoder = new TextDecoder()
|
||||
let buffer = ""
|
||||
while (true) {
|
||||
const step = await reader.read()
|
||||
if (step.done) break
|
||||
buffer += decoder.decode(step.value, { stream: true })
|
||||
const lines = buffer.split("\n")
|
||||
buffer = lines.pop() || ""
|
||||
for (const line of lines) {
|
||||
const event = parseSse(line)
|
||||
if (!event) continue
|
||||
if (event.type === "delta" && event.text) {
|
||||
assistant.pending = false
|
||||
assistant.content += event.text
|
||||
} else if (event.type === "replace" && event.text !== undefined) {
|
||||
assistant.pending = false
|
||||
assistant.content = event.text
|
||||
} else if (event.type === "thought" && event.text) {
|
||||
assistant.thought = event.text
|
||||
} else if (event.type === "saved" && event.messageId) {
|
||||
assistant.id = event.messageId
|
||||
assistant.kind = event.kind || "chat"
|
||||
assistant.draftFormat = event.draftFormat || ""
|
||||
assistant.draftName = event.draftName || ""
|
||||
assistant.pending = false
|
||||
} else if (event.type === "error") {
|
||||
assistant.pending = false
|
||||
assistant.content = assistant.content || event.message || "暂时无法整理"
|
||||
}
|
||||
await scrollToEnd()
|
||||
}
|
||||
}
|
||||
assistant.pending = false
|
||||
const current = sessions.value.find((item) => item.id === activeId.value)
|
||||
if (current) {
|
||||
if (current.title === "新会话") current.title = (query || files[0]?.name || "新会话").slice(0, 22)
|
||||
current.updatedAt = new Date().toISOString()
|
||||
sessions.value = [current, ...sessions.value.filter((item) => item.id !== current.id)]
|
||||
}
|
||||
} catch (exc: any) {
|
||||
assistant.pending = false
|
||||
assistant.content = assistant.content || exc?.message || "暂时无法整理"
|
||||
notify("整理失败,请稍后重试")
|
||||
} finally {
|
||||
sending.value = false
|
||||
await scrollToEnd()
|
||||
}
|
||||
}
|
||||
|
||||
function isDownloading(id: number) {
|
||||
return downloadingIds.value.includes(id)
|
||||
}
|
||||
|
||||
async function download(item: CoachMessage) {
|
||||
if (isDownloading(item.id)) return
|
||||
downloadingIds.value = [...downloadingIds.value, item.id]
|
||||
try {
|
||||
const response = await fetch(`${apiBase}/member/valuation/template-coach/messages/${item.id}/file`, {
|
||||
headers: { Authorization: `Bearer ${token.value}` },
|
||||
})
|
||||
if (!response.ok) {
|
||||
notify("模版下载失败")
|
||||
return
|
||||
}
|
||||
const blob = await response.blob()
|
||||
const url = URL.createObjectURL(blob)
|
||||
const link = document.createElement("a")
|
||||
link.href = url
|
||||
link.download = fileName(item)
|
||||
link.click()
|
||||
URL.revokeObjectURL(url)
|
||||
} catch {
|
||||
notify("模版下载失败")
|
||||
} finally {
|
||||
downloadingIds.value = downloadingIds.value.filter((id) => id !== item.id)
|
||||
}
|
||||
}
|
||||
|
||||
function nextLocalId() {
|
||||
localId += 1
|
||||
return localId
|
||||
}
|
||||
|
||||
onMounted(load)
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.mask { position: fixed; inset: 0; background: rgba(148, 183, 226, .35); display: grid; place-items: center; z-index: 80; }
|
||||
.workspace {
|
||||
width: min(1080px, calc(100% - 32px));
|
||||
height: min(760px, calc(100vh - 32px));
|
||||
display: grid;
|
||||
grid-template-columns: 260px minmax(0, 1fr);
|
||||
background: #f5f9ff;
|
||||
color: #1e3a5f;
|
||||
border: 1px solid #d6e4ff;
|
||||
border-radius: 14px;
|
||||
overflow: hidden;
|
||||
box-shadow: 0 18px 50px rgba(30, 58, 95, 0.16);
|
||||
}
|
||||
.side, .main { min-height: 0; }
|
||||
.side {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
border-right: 1px solid rgba(59, 130, 246, 0.18);
|
||||
background: #fff;
|
||||
}
|
||||
.side-head { padding: 14px; border-bottom: 1px solid rgba(59, 130, 246, 0.14); }
|
||||
.brand { display: flex; gap: 10px; align-items: center; margin-bottom: 12px; min-width: 0; }
|
||||
.logo { width: 40px; height: 40px; object-fit: contain; border-radius: 10px; border: 1px solid #d6e4ff; background: #fff; }
|
||||
.brand h2 { margin: 0; font-size: 18px; color: #1d4ed8; }
|
||||
.brand p, .account, .meta, .hint, .empty { margin: 0; color: #6b86a8; font-size: 12px; }
|
||||
.wide { width: 100%; }
|
||||
.session-list { flex: 1; overflow: auto; padding: 8px; }
|
||||
.session {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr auto;
|
||||
gap: 6px;
|
||||
align-items: start;
|
||||
padding: 10px;
|
||||
border-radius: 12px;
|
||||
border: 1px solid transparent;
|
||||
cursor: pointer;
|
||||
}
|
||||
.session.active { background: #e8f1ff; border-color: rgba(59, 130, 246, 0.36); }
|
||||
.session:hover { background: #f0f6ff; }
|
||||
.session-copy { min-width: 0; }
|
||||
.title {
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
line-height: 1.4;
|
||||
display: -webkit-box;
|
||||
-webkit-box-orient: vertical;
|
||||
-webkit-line-clamp: 2;
|
||||
overflow: hidden;
|
||||
white-space: normal;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.more-wrap { position: relative; }
|
||||
.more-btn {
|
||||
width: 28px; height: 28px; border: 0; border-radius: 50%; background: transparent; color: #64748b;
|
||||
font: inherit; font-size: 13px; cursor: pointer;
|
||||
}
|
||||
.more-btn:hover, .more-wrap.open .more-btn { background: #e8eef6; }
|
||||
.menu {
|
||||
position: absolute; top: 32px; right: 0; z-index: 5; min-width: 120px;
|
||||
padding: 6px; border-radius: 12px; background: #fff; border: 1px solid #e8eef5;
|
||||
box-shadow: 0 10px 28px rgba(30, 58, 95, 0.14);
|
||||
}
|
||||
.menu button {
|
||||
width: 100%; text-align: left; border: 0; background: transparent; border-radius: 8px; padding: 8px 10px;
|
||||
font: inherit; font-size: 13px; cursor: pointer;
|
||||
}
|
||||
.menu button:hover { background: #f3f5f8; }
|
||||
.menu .danger { color: #e5486a; }
|
||||
.side-foot { padding: 12px; border-top: 1px solid rgba(59, 130, 246, 0.14); display: grid; gap: 8px; }
|
||||
.user { display: flex; gap: 8px; align-items: center; min-width: 0; }
|
||||
.name { font-size: 13px; font-weight: 650; }
|
||||
.account { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; max-width: 170px; }
|
||||
.logout {
|
||||
height: 34px; border-radius: 10px; border: 1px solid #d7e3f4; background: #f7faff; color: #3b6ea5;
|
||||
font: inherit; font-size: 13px; cursor: pointer;
|
||||
}
|
||||
.main { position: relative; display: flex; flex-direction: column; }
|
||||
.thread { flex: 1; min-height: 0; overflow: auto; padding: 18px 18px 8px; display: flex; flex-direction: column; gap: 14px; }
|
||||
.empty { margin: auto; }
|
||||
.row { display: flex; gap: 10px; max-width: 820px; }
|
||||
.row.user { align-self: flex-end; flex-direction: row-reverse; }
|
||||
.avatar { width: 36px; height: 36px; border-radius: 50%; display: grid; place-items: center; flex: none; overflow: hidden; }
|
||||
.ai-avatar, .user-avatar, .profile-avatar { background: transparent; border: 0; }
|
||||
.ai-avatar img { width: 100%; height: 100%; object-fit: contain; }
|
||||
.user-avatar img { width: 24px; height: 24px; object-fit: contain; }
|
||||
.profile-avatar img { width: 100%; height: 100%; object-fit: cover; }
|
||||
.bubble {
|
||||
background: #fff; border: 1px solid rgba(59, 130, 246, 0.18); border-radius: 14px 14px 14px 4px;
|
||||
padding: 12px 14px; line-height: 1.65; font-size: 14px; max-width: min(640px, 100%);
|
||||
}
|
||||
.row.user .bubble { background: #eaf2ff; border-radius: 14px 14px 4px 14px; }
|
||||
.bubble p { margin: 0; white-space: pre-wrap; }
|
||||
.md :deep(p) { margin: 0 0 8px; white-space: normal; }
|
||||
.md :deep(p:last-child) { margin-bottom: 0; }
|
||||
.md :deep(h1),
|
||||
.md :deep(h2),
|
||||
.md :deep(h3),
|
||||
.md :deep(h4) { margin: 10px 0 6px; font-size: 15px; line-height: 1.45; }
|
||||
.md :deep(ul),
|
||||
.md :deep(ol) { margin: 0 0 8px; padding-left: 1.3em; }
|
||||
.md :deep(li) { margin: 2px 0; }
|
||||
.md :deep(li:last-child) { margin-bottom: 0; }
|
||||
.md :deep(strong) { font-weight: 650; }
|
||||
.md :deep(code) { padding: 0 4px; border-radius: 4px; background: #f3f7fd; font-size: 0.92em; }
|
||||
.md :deep(pre) { margin: 0 0 8px; padding: 8px 10px; overflow: auto; border-radius: 8px; background: #f3f7fd; }
|
||||
.md :deep(pre code) { padding: 0; background: transparent; }
|
||||
.md :deep(a) { color: #2563eb; }
|
||||
.md :deep(.table-wrap) { margin: 0 0 8px; overflow-x: auto; }
|
||||
.md :deep(table) { width: 100%; min-width: 560px; border-collapse: collapse; table-layout: fixed; font-size: 13px; }
|
||||
.md :deep(th),
|
||||
.md :deep(td) { border: 1px solid #d7e3f4; padding: 6px 8px; text-align: left; vertical-align: top; overflow-wrap: anywhere; }
|
||||
.md :deep(th) { background: #f3f7fd; font-weight: 650; }
|
||||
.thought { margin-bottom: 8px; border: 1px dashed rgba(59, 130, 246, 0.3); border-radius: 10px; background: #f5f9ff; padding: 8px 10px; }
|
||||
.thought summary { cursor: pointer; color: #2563eb; font-size: 12px; }
|
||||
.thought p { margin: 8px 0 0; color: #6b86a8; font-size: 12px; white-space: pre-wrap; }
|
||||
.suggest { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 10px; }
|
||||
.suggest button {
|
||||
border: 1px solid rgba(59, 130, 246, 0.3); background: #f8fbff; color: #2563eb; border-radius: 999px; padding: 8px 12px; text-align: left;
|
||||
font: inherit; font-size: 13px; cursor: pointer;
|
||||
}
|
||||
.suggest button:hover { background: #eef5ff; }
|
||||
.composer { border-top: 1px solid rgba(59, 130, 246, 0.16); padding: 10px 14px 12px; display: grid; gap: 8px; background: #f8fbff; }
|
||||
.hint-row { display: flex; justify-content: space-between; gap: 12px; align-items: center; flex-wrap: wrap; }
|
||||
.pill { border: 1px solid rgba(59, 130, 246, 0.22); background: #f0f6ff; color: #6b86a8; border-radius: 999px; padding: 6px 10px; font-size: 12px; flex: none; }
|
||||
.composer-row { display: grid; grid-template-columns: auto minmax(0, 1fr) auto; gap: 8px; align-items: center; }
|
||||
.composer textarea {
|
||||
resize: none; border: 1px solid rgba(59, 130, 246, 0.36); border-radius: 12px; padding: 10px 12px;
|
||||
font: inherit; color: #1e3a5f; background: #fff; min-height: 44px;
|
||||
}
|
||||
.primary, .icon-btn, .suggest button { font: inherit; font-size: 13px; }
|
||||
.primary, .icon-btn { cursor: pointer; }
|
||||
.primary { border: 0; border-radius: 10px; background: #3b82f6; color: #fff; height: 36px; padding: 0 14px; font-size: 13px; }
|
||||
.primary:hover { background: #2563eb; }
|
||||
.primary:disabled { opacity: 0.45; cursor: not-allowed; }
|
||||
.composer-row .primary {
|
||||
height: 40px;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
line-height: 1;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.icon-btn {
|
||||
width: 40px; height: 40px; border-radius: 10px; border: 1px solid #bfdbfe; background: #f0f7ff; color: #2563eb;
|
||||
display: grid; place-items: center;
|
||||
}
|
||||
.close { width: 32px; height: 32px; border-radius: 8px; }
|
||||
.icon-btn svg { width: 20px; height: 20px; }
|
||||
.thumb-grid { display: flex; flex-wrap: wrap; gap: 6px; margin: 0 0 6px; padding: 0; list-style: none; }
|
||||
.composer .thumb-grid { margin: 0; }
|
||||
.thumb-card {
|
||||
position: relative; width: 88px; display: flex; flex-direction: column; gap: 4px;
|
||||
padding: 5px; border: 1px solid #d7e3f4; border-radius: 8px; background: #fff;
|
||||
}
|
||||
button.thumb-card.download { margin-top: 8px; font: inherit; font-size: 12px; text-align: left; cursor: pointer; }
|
||||
button.thumb-card.download:disabled { cursor: progress; }
|
||||
.download-mask {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 4px;
|
||||
border-radius: inherit;
|
||||
background: rgba(255, 255, 255, 0.9);
|
||||
color: #2563eb;
|
||||
font-size: 12px;
|
||||
line-height: 1;
|
||||
}
|
||||
.thumb-preview {
|
||||
display: flex; align-items: center; justify-content: center; height: 48px; overflow: hidden;
|
||||
border-radius: 6px; background: #f3f7fd; border: 1px solid #e5eef8;
|
||||
}
|
||||
.thumb-preview img { width: 100%; height: 100%; object-fit: cover; }
|
||||
.thumb-file { display: grid; justify-items: center; gap: 0; color: #3b6ea5; }
|
||||
.thumb-file svg { width: 16px; height: 16px; }
|
||||
.thumb-file b { font-size: 10px; font-weight: 650; letter-spacing: 0.03em; }
|
||||
.thumb-name { font-size: 11px; line-height: 1.3; color: #1e3a5f; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.thumb-remove {
|
||||
position: absolute; top: 3px; right: 3px; width: 16px; height: 16px; padding: 0; border: 0; border-radius: 999px;
|
||||
background: rgba(15, 23, 42, 0.55); color: #fff; display: grid; place-items: center; cursor: pointer;
|
||||
}
|
||||
.thumb-remove svg { width: 10px; height: 10px; }
|
||||
.typing { display: inline-flex; gap: 4px; }
|
||||
.typing span { width: 6px; height: 6px; border-radius: 50%; background: #3b82f6; animation: blink 1s infinite; }
|
||||
.typing span:nth-child(2) { animation-delay: .15s; }
|
||||
.typing span:nth-child(3) { animation-delay: .3s; }
|
||||
.toast {
|
||||
position: absolute; right: 18px; bottom: 18px; background: #fff; border: 1px solid #93c5fd;
|
||||
border-radius: 10px; padding: 10px 14px; color: #9a3412; font-size: 13px;
|
||||
}
|
||||
.sr-only { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0, 0, 0, 0); }
|
||||
@keyframes blink { 0%, 80%, 100% { opacity: .25; } 40% { opacity: 1; } }
|
||||
@media (max-width: 860px) {
|
||||
.workspace { grid-template-columns: 1fr; width: calc(100% - 16px); height: calc(100vh - 16px); }
|
||||
.side { max-height: 280px; }
|
||||
.composer-row { grid-template-columns: auto minmax(0, 1fr); }
|
||||
.composer-row .primary { grid-column: auto; }
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) { .typing span { animation: none; } }
|
||||
</style>
|
||||
@@ -1,15 +1,36 @@
|
||||
<template>
|
||||
<section v-if="home.audiences.placeholder" class="cats">
|
||||
<p>{{ home.audiences.placeholder }}</p>
|
||||
</section>
|
||||
<section v-else class="cats" :class="{ rows: brand }" aria-label="服务对象入口">
|
||||
<div v-for="category in home.audiences.categories" :key="category.name" class="cat">
|
||||
<p v-if="home.audiences.placeholder && !hotLinks.length">{{ home.audiences.placeholder }}</p>
|
||||
<section
|
||||
v-else
|
||||
class="cats"
|
||||
:class="{ rows: brand }"
|
||||
:style="brand ? { '--entry-cols': String(columnCount) } : undefined"
|
||||
aria-label="服务对象入口"
|
||||
>
|
||||
<p v-if="home.audiences.placeholder">{{ home.audiences.placeholder }}</p>
|
||||
<template v-else>
|
||||
<div v-for="category in home.audiences.categories" :key="category.name" class="cat">
|
||||
<h3 class="with-mark">
|
||||
<TitleMark :name="category.name" />
|
||||
{{ category.name }}
|
||||
</h3>
|
||||
<a
|
||||
v-for="link in category.links"
|
||||
:key="link.label"
|
||||
:href="link.navigation === 'none' ? undefined : link.url"
|
||||
:target="link.navigation === 'newWindow' ? '_blank' : undefined"
|
||||
rel="noopener"
|
||||
@click="link.navigation === 'none' && $event.preventDefault()"
|
||||
>{{ link.label }}</a>
|
||||
</div>
|
||||
</template>
|
||||
<div v-if="hotLinks.length" class="cat">
|
||||
<h3 class="with-mark">
|
||||
<TitleMark :name="category.name" />
|
||||
{{ category.name }}
|
||||
<TitleMark name="在线服务" />
|
||||
在线服务
|
||||
</h3>
|
||||
<a
|
||||
v-for="link in category.links"
|
||||
v-for="link in hotLinks"
|
||||
:key="link.label"
|
||||
:href="link.navigation === 'none' ? undefined : link.url"
|
||||
:target="link.navigation === 'newWindow' ? '_blank' : undefined"
|
||||
@@ -25,4 +46,9 @@ import TitleMark from "./TitleMark.vue"
|
||||
|
||||
const props = defineProps<{ home: any }>()
|
||||
const brand = computed(() => props.home.templateName === "LOGO蓝")
|
||||
const hotLinks = computed(() => props.home.hotLinks?.links || [])
|
||||
const columnCount = computed(() => {
|
||||
const categories = props.home.audiences?.placeholder ? 0 : (props.home.audiences?.categories?.length || 0)
|
||||
return categories + (hotLinks.value.length ? 1 : 0)
|
||||
})
|
||||
</script>
|
||||
@@ -1,18 +0,0 @@
|
||||
<template>
|
||||
<p v-if="home.hotLinks.placeholder">{{ home.hotLinks.placeholder }}</p>
|
||||
<nav v-else :class="brand ? 'band' : 'hot'" aria-label="高频功能入口">
|
||||
<a
|
||||
v-for="link in home.hotLinks.links"
|
||||
:key="link.label"
|
||||
:href="link.navigation === 'none' ? undefined : link.url"
|
||||
:target="link.navigation === 'newWindow' ? '_blank' : undefined"
|
||||
rel="noopener"
|
||||
@click="link.navigation === 'none' && $event.preventDefault()"
|
||||
>{{ link.label }}</a>
|
||||
</nav>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
const props = defineProps<{ home: any }>()
|
||||
const brand = computed(() => props.home.templateName === "LOGO蓝")
|
||||
</script>
|
||||
@@ -107,11 +107,9 @@
|
||||
</section>
|
||||
<div class="side">
|
||||
<AudienceBlock :home="home" />
|
||||
<HotLinks :home="home" />
|
||||
</div>
|
||||
</section>
|
||||
<section v-else class="gate">
|
||||
<HotLinks :home="home" />
|
||||
<AudienceBlock :home="home" />
|
||||
</section>
|
||||
|
||||
@@ -119,21 +117,23 @@
|
||||
<section class="marquee" aria-label="荣誉滚动">
|
||||
<p v-if="home.honors.placeholder" class="list" style="padding: 14px">{{ home.honors.placeholder }}</p>
|
||||
<div v-else class="track" :style="trackStyle(home.honors.intervalSeconds)">
|
||||
<div
|
||||
<figure
|
||||
v-for="(item, index) in doubled(home.honors.items)"
|
||||
:key="`h${index}`"
|
||||
class="honor"
|
||||
:style="{ backgroundImage: `url(${item.imageUrl})` }"
|
||||
/>
|
||||
>
|
||||
<i :style="{ backgroundImage: `url(${item.imageUrl})` }" />
|
||||
<figcaption v-if="item.caption">{{ item.caption }}</figcaption>
|
||||
</figure>
|
||||
</div>
|
||||
</section>
|
||||
<h3 v-if="variant === 'brand'" class="rail with-mark"><TitleMark name="会员单位" />会员单位</h3>
|
||||
<section class="marquee" aria-label="会员单位">
|
||||
<p v-if="home.members.placeholder" class="list" style="padding: 14px">{{ home.members.placeholder }}</p>
|
||||
<div v-else class="track" :style="trackStyle(home.members.intervalSeconds)">
|
||||
<div v-else-if="memberLanes.length < 2" class="track" :style="trackStyle(home.members.intervalSeconds)">
|
||||
<component
|
||||
:is="item.navigation === 'newWindow' ? 'a' : 'span'"
|
||||
v-for="(item, index) in doubled(home.members.items)"
|
||||
v-for="(item, index) in doubled(memberLanes[0] || [])"
|
||||
:key="`m${index}`"
|
||||
class="member"
|
||||
:href="item.navigation === 'newWindow' ? item.url : undefined"
|
||||
@@ -144,6 +144,30 @@
|
||||
{{ item.name }}
|
||||
</component>
|
||||
</div>
|
||||
<div v-else class="member-rows">
|
||||
<div
|
||||
v-for="(lane, laneIndex) in memberLanes"
|
||||
:key="laneIndex"
|
||||
class="track"
|
||||
:class="{ stagger: laneIndex === 1 }"
|
||||
:style="trackStyle(home.members.intervalSeconds)"
|
||||
>
|
||||
<div v-for="(set, copy) in memberSets(lane)" :key="copy" class="member-set">
|
||||
<component
|
||||
:is="item.navigation === 'newWindow' ? 'a' : 'span'"
|
||||
v-for="(item, index) in set"
|
||||
:key="`m${laneIndex}-${copy}-${index}`"
|
||||
class="member"
|
||||
:href="item.navigation === 'newWindow' ? item.url : undefined"
|
||||
target="_blank"
|
||||
rel="noopener"
|
||||
>
|
||||
<i :style="{ backgroundImage: `url(${item.imageUrl})` }" />
|
||||
{{ item.name }}
|
||||
</component>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</slot>
|
||||
</div>
|
||||
@@ -225,7 +249,8 @@ const topMenu = computed(() => {
|
||||
homeItem,
|
||||
{ label: "组织概况", url: "/about", navigation: "sameWindow" },
|
||||
{ label: "继续教育", url: "/edu", navigation: "sameWindow" },
|
||||
...shortcuts,
|
||||
{ label: "会员服务", url: "/member", navigation: "sameWindow" },
|
||||
...shortcuts.filter((item: any) => item.label !== "会员服务"),
|
||||
{ label: "资质荣誉", url: "/honors", navigation: "sameWindow" },
|
||||
{ label: "机构名录", url: "/institutions", navigation: "sameWindow" },
|
||||
{ label: "行业党建", url: "/party", navigation: "sameWindow" },
|
||||
@@ -247,6 +272,7 @@ function isCurrentNav(url: string) {
|
||||
if (url === "/") return path === "/"
|
||||
if (url === "/about") return path === "/about" || path.startsWith("/about/")
|
||||
if (url === "/edu") return path === "/edu" || path.startsWith("/edu/")
|
||||
if (url === "/member") return path === "/member" || path.startsWith("/member/")
|
||||
if (url === "/party") return path === "/party" || path.startsWith("/party/")
|
||||
if (url === "/expert") return path === "/expert" || path.startsWith("/expert/")
|
||||
if (url === "/tech") return path === "/tech" || path.startsWith("/tech/")
|
||||
@@ -259,6 +285,21 @@ function isCurrentNav(url: string) {
|
||||
function doubled(items: any[]) {
|
||||
return [...items, ...items]
|
||||
}
|
||||
function memberSets(lane: any[]) {
|
||||
const count = lane.length
|
||||
if (!count) return [[], []]
|
||||
const repeats = Math.max(1, Math.ceil(1680 / (count * 236)))
|
||||
const set = Array.from({ length: repeats }, () => lane).flat()
|
||||
return [set, set]
|
||||
}
|
||||
const memberLanes = computed(() => {
|
||||
const items = props.home?.members?.items || []
|
||||
if (items.length < 6) return items.length ? [items] : []
|
||||
return [
|
||||
items.filter((_: any, index: number) => index % 2 === 0),
|
||||
items.filter((_: any, index: number) => index % 2 === 1),
|
||||
]
|
||||
})
|
||||
function trackStyle(seconds?: number) {
|
||||
return { animationDuration: `${Math.max(seconds || 8, 1) * 4}s` }
|
||||
}
|
||||
|
||||
@@ -29,6 +29,11 @@
|
||||
<path d="M4.5 19.5h15M6.2 19.5V9.2L12 5.2l5.8 4V19.5" />
|
||||
<path d="M10 19.5v-4.2h4V19.5M9.2 11.2h1.6M13.2 11.2h1.6M9.2 14.2h1.6M13.2 14.2h1.6" />
|
||||
</g>
|
||||
<g v-else-if="name === '在线服务'" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linejoin="round" stroke-linecap="round">
|
||||
<rect x="4.2" y="5" width="15.6" height="10.4" rx="1.6" />
|
||||
<path d="M8 19.2h8M12 15.4v3.8" />
|
||||
<path d="M8.2 10.2 10.4 12.2 15.6 7.6" />
|
||||
</g>
|
||||
<g v-else-if="name === '公众'" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round">
|
||||
<circle cx="8" cy="8.2" r="2.1" />
|
||||
<circle cx="15.6" cy="8.6" r="1.8" />
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
const TOKEN_KEY = "gsfdc_agent_token"
|
||||
let sessionWatch: number | null = null
|
||||
|
||||
type AgentProfile = {
|
||||
username: string
|
||||
@@ -71,12 +72,14 @@ export function useAgentAuth() {
|
||||
token.value = stored
|
||||
if (stored) await refreshProfile()
|
||||
ready.value = true
|
||||
if (token.value) watchSession()
|
||||
}
|
||||
|
||||
async function setSession(accessToken: string) {
|
||||
token.value = accessToken
|
||||
persist(accessToken)
|
||||
ready.value = true
|
||||
watchSession()
|
||||
await refreshProfile()
|
||||
}
|
||||
|
||||
@@ -87,6 +90,21 @@ export function useAgentAuth() {
|
||||
persist(null)
|
||||
}
|
||||
|
||||
function dropAgentSession(accessToken: string) {
|
||||
const stored = readStored()
|
||||
if (accessToken !== token.value && accessToken !== stored) return
|
||||
clearSession()
|
||||
}
|
||||
|
||||
function watchSession() {
|
||||
if (!import.meta.client || sessionWatch !== null) return
|
||||
const tick = () => {
|
||||
if (token.value) void refreshProfile()
|
||||
}
|
||||
sessionWatch = window.setInterval(tick, 4000)
|
||||
window.addEventListener("focus", tick)
|
||||
}
|
||||
|
||||
const isAuthed = computed(() => Boolean(token.value))
|
||||
|
||||
return {
|
||||
@@ -98,6 +116,7 @@ export function useAgentAuth() {
|
||||
ensure,
|
||||
setSession,
|
||||
clearSession,
|
||||
dropAgentSession,
|
||||
refreshProfile,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
export const MEMBER_SECTIONS = [
|
||||
{ key: "orgs", label: "会员机构", path: "/member/orgs" },
|
||||
{ key: "profile", label: "会员信息", path: "/member/profile" },
|
||||
{ key: "news", label: "会员资讯", path: "/member/news" },
|
||||
{ key: "trainings", label: "培训报名", path: "/member/trainings" },
|
||||
]
|
||||
@@ -1,4 +0,0 @@
|
||||
export const REPORT_SECTIONS = [
|
||||
{ key: "query", label: "报告查询", path: "/reports/query" },
|
||||
{ key: "review", label: "报告审核", path: "/reports/review" },
|
||||
] as const
|
||||
@@ -18,11 +18,20 @@ export function useSiteApi() {
|
||||
async function request<T>(path: string, opts: FetchOpts = {}) {
|
||||
const headers: Record<string, string> = {}
|
||||
if (opts.token) headers.Authorization = `Bearer ${opts.token}`
|
||||
return $fetch<T>(`${base}${path}`, {
|
||||
method: opts.method || (opts.body || opts.formData ? "POST" : "GET"),
|
||||
body: opts.formData || opts.body,
|
||||
headers,
|
||||
})
|
||||
try {
|
||||
return await $fetch<T>(`${base}${path}`, {
|
||||
method: opts.method || (opts.body || opts.formData ? "POST" : "GET"),
|
||||
body: opts.formData || opts.body,
|
||||
headers,
|
||||
})
|
||||
} catch (exc: any) {
|
||||
const status = Number(exc?.statusCode || exc?.status || exc?.response?.status || 0)
|
||||
if (status === 401 && opts.token) {
|
||||
const { dropAgentSession } = useAgentAuth()
|
||||
dropAgentSession(opts.token)
|
||||
}
|
||||
throw exc
|
||||
}
|
||||
}
|
||||
|
||||
function get<T>(path: string, token?: string | null) {
|
||||
|
||||
@@ -103,7 +103,9 @@
|
||||
v-if="item.kind === 'draft' && !item.pending"
|
||||
type="button"
|
||||
class="thumb-card download"
|
||||
:aria-label="`下载${draftFile(item)[1]}`"
|
||||
:disabled="isDownloading(item.id)"
|
||||
:aria-busy="isDownloading(item.id)"
|
||||
:aria-label="isDownloading(item.id) ? `正在下载${draftFile(item)[1]}` : `下载${draftFile(item)[1]}`"
|
||||
@click="downloadDraft(item.id)"
|
||||
>
|
||||
<span class="thumb-preview">
|
||||
@@ -118,6 +120,10 @@
|
||||
<span class="thumb-name" :title="draftFile(item)[1]">
|
||||
{{ draftFile(item)[1] }}
|
||||
</span>
|
||||
<span v-if="isDownloading(item.id)" class="download-mask">
|
||||
<span class="typing" aria-hidden="true"><span /><span /><span /></span>
|
||||
下载中
|
||||
</span>
|
||||
</button>
|
||||
<div v-else-if="item.pending" class="typing" aria-label="正在回答"><span /><span /><span /></div>
|
||||
<div v-if="showSuggestions(item)" class="suggest">
|
||||
@@ -258,6 +264,7 @@
|
||||
<input ref="templateInput" class="sr-only" type="file" accept=".docx,.pptx" @change="onTemplateFile" />
|
||||
</div>
|
||||
<div class="modal-actions">
|
||||
<button type="button" class="ghost" @click="coaching = true">用对话制作模版</button>
|
||||
<button type="submit" class="primary" :disabled="!templateName.trim() || !templateFileName">上传并启用</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -292,6 +299,13 @@
|
||||
<li>一次只能上传一个文件。大小不能超过系统里配置的上传上限,超出会被拒绝。</li>
|
||||
<li>「模版名称」是列表和选择框里看到的名字,和文件名可以不同。名称请能看出用途,例如「住宅估价说明」「设备估价汇报」。</li>
|
||||
</ul>
|
||||
<h4>用对话制作模版</h4>
|
||||
<ul>
|
||||
<li>「用对话制作模版」打开估价模版智能体。它是估价智能体的辅助,专门准备模版,不回答具体估价问题,也不直接生成估价文稿。</li>
|
||||
<li>对话方式和估价智能体一样:可以连续追问,也可以上传附件。历史文稿请用 docx 或 pptx;pdf、表格和图片可以当作参考。旧版 doc、ppt 请先另存。</li>
|
||||
<li>说清楚要保留的章节,以及做成 Word 还是 PPT。满意后下载到本地,可以再改文字,然后回到上面的表单自己上传。</li>
|
||||
<li>对话不会把文件直接放进模版列表。</li>
|
||||
</ul>
|
||||
<h4>系统怎么使用模版</h4>
|
||||
<ul>
|
||||
<li>上传时只读取文件里的文字,整理成章节提纲或幻灯片提纲。字体、颜色、页眉页脚样式、页码、图片、图表、形状、动画和切换都不会保留。</li>
|
||||
@@ -335,11 +349,13 @@
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<TemplateCoach v-if="coaching" @close="coaching = false" />
|
||||
<p v-if="error" class="toast" role="status">{{ error }}</p>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import TemplateCoach from "../../components/expert/TemplateCoach.vue"
|
||||
import { renderAnswerMarkdown } from "../../utils/answerMarkdown"
|
||||
type SessionItem = { id: number; title: string; updatedAt: string }
|
||||
type Suggestion = { id: number; text: string; enabled: boolean }
|
||||
@@ -384,9 +400,11 @@ const web = ref(false)
|
||||
const WEB_PREF_KEY = "gsfdc_agent_web"
|
||||
const fileInput = ref<HTMLInputElement | null>(null)
|
||||
const sending = ref(false)
|
||||
const downloadingIds = ref<number[]>([])
|
||||
const menuId = ref<number | null>(null)
|
||||
const managing = ref(false)
|
||||
const managingTemplates = ref(false)
|
||||
const coaching = ref(false)
|
||||
const picking = ref(false)
|
||||
const suggestionDraft = ref("")
|
||||
const editingId = ref<number | null>(null)
|
||||
@@ -805,25 +823,36 @@ async function runDraft(chosenId: number | null) {
|
||||
}
|
||||
}
|
||||
|
||||
function isDownloading(id: number) {
|
||||
return downloadingIds.value.includes(id)
|
||||
}
|
||||
|
||||
async function downloadDraft(messageId: number) {
|
||||
if (!activeId.value || !token.value) return
|
||||
if (!activeId.value || !token.value || isDownloading(messageId)) return
|
||||
downloadingIds.value = [...downloadingIds.value, messageId]
|
||||
const message = messages.value.find((item) => item.id === messageId)
|
||||
const format = message?.draftFormat && draftFiles[message.draftFormat] ? message.draftFormat : "docx"
|
||||
const response = await fetch(
|
||||
`${apiBase}/member/valuation/sessions/${activeId.value}/messages/${messageId}/${format}`,
|
||||
{ headers: { Authorization: `Bearer ${token.value}` } },
|
||||
)
|
||||
if (!response.ok) {
|
||||
try {
|
||||
const response = await fetch(
|
||||
`${apiBase}/member/valuation/sessions/${activeId.value}/messages/${messageId}/${format}`,
|
||||
{ headers: { Authorization: `Bearer ${token.value}` } },
|
||||
)
|
||||
if (!response.ok) {
|
||||
notify("文稿下载失败")
|
||||
return
|
||||
}
|
||||
const blob = await response.blob()
|
||||
const url = URL.createObjectURL(blob)
|
||||
const link = document.createElement("a")
|
||||
link.href = url
|
||||
link.download = draftFile({ draftFormat: format, draftName: message?.draftName })[1]
|
||||
link.click()
|
||||
URL.revokeObjectURL(url)
|
||||
} catch {
|
||||
notify("文稿下载失败")
|
||||
return
|
||||
} finally {
|
||||
downloadingIds.value = downloadingIds.value.filter((id) => id !== messageId)
|
||||
}
|
||||
const blob = await response.blob()
|
||||
const url = URL.createObjectURL(blob)
|
||||
const link = document.createElement("a")
|
||||
link.href = url
|
||||
link.download = draftFile({ draftFormat: format, draftName: message?.draftName })[1]
|
||||
link.click()
|
||||
URL.revokeObjectURL(url)
|
||||
}
|
||||
|
||||
async function openTemplates() {
|
||||
@@ -1019,6 +1048,7 @@ onBeforeUnmount(() => document.removeEventListener("click", closeMenu))
|
||||
.brand p, .account, .meta, .hint, .empty { margin: 0; color: #6b86a8; font-size: 12px; }
|
||||
.primary, .ghost, .logout, .more-btn, .menu button, .suggest button {
|
||||
font: inherit;
|
||||
font-size: 13px;
|
||||
cursor: pointer;
|
||||
}
|
||||
.primary {
|
||||
@@ -1074,7 +1104,7 @@ onBeforeUnmount(() => document.removeEventListener("click", closeMenu))
|
||||
.menu .danger { color: #e5486a; }
|
||||
.side-foot { padding: 12px; border-top: 1px solid rgba(59, 130, 246, 0.14); display: grid; gap: 8px; }
|
||||
.side-manage { display: grid; grid-template-columns: 1.4fr 1fr; gap: 6px; }
|
||||
.side-manage .ghost { width: 100%; height: 30px; padding: 0 6px; font-size: 12px; white-space: nowrap; }
|
||||
.side-manage .ghost { width: 100%; height: 30px; padding: 0 6px; font-size: 13px; white-space: nowrap; }
|
||||
.user { display: flex; gap: 8px; align-items: center; min-width: 0; }
|
||||
.name { font-size: 13px; font-weight: 650; }
|
||||
.account { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; max-width: 170px; }
|
||||
@@ -1144,9 +1174,25 @@ onBeforeUnmount(() => document.removeEventListener("click", closeMenu))
|
||||
button.thumb-card.download {
|
||||
margin-top: 8px;
|
||||
font: inherit;
|
||||
font-size: 12px;
|
||||
text-align: left;
|
||||
cursor: pointer;
|
||||
}
|
||||
button.thumb-card.download:disabled { cursor: progress; }
|
||||
.download-mask {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 4px;
|
||||
border-radius: inherit;
|
||||
background: rgba(255, 255, 255, 0.9);
|
||||
color: #2563eb;
|
||||
font-size: 12px;
|
||||
line-height: 1;
|
||||
}
|
||||
.composer textarea {
|
||||
resize: none; border: 1px solid rgba(59, 130, 246, 0.36); border-radius: 12px; padding: 10px 12px;
|
||||
font: inherit; color: #1e3a5f; background: #fff; min-height: 44px;
|
||||
@@ -1330,7 +1376,7 @@ button.thumb-card.download {
|
||||
.modal form, .modal-actions { display: flex; gap: 8px; }
|
||||
.pick-actions { justify-content: flex-end; }
|
||||
.pick-actions .ghost,
|
||||
.pick-actions .primary { height: 30px; padding: 0 10px; font-size: 12px; }
|
||||
.pick-actions .primary { height: 30px; padding: 0 10px; font-size: 13px; }
|
||||
.modal input, .modal select { flex: 1; border: 1px solid #d6e4ff; border-radius: 10px; padding: 8px 10px; font: inherit; color: #1e3a5f; background: #fff; }
|
||||
.field { display: grid; gap: 6px; margin: 12px 0; font-size: 13px; color: #1e3a5f; }
|
||||
.toast { position: fixed; right: 18px; bottom: 18px; background: #fff; border: 1px solid #93c5fd; border-radius: 10px; padding: 10px 14px; }
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
<template>
|
||||
<SiteLoading v-if="!home" hint="正在读取内容" />
|
||||
<SiteHome v-else :home="home" :logo-url="logoUrl">
|
||||
<p class="crumb">首页 / {{ crumb }}</p>
|
||||
<div class="layout">
|
||||
<nav class="side-nav" aria-label="会员服务子导航">
|
||||
<NuxtLink
|
||||
v-for="section in MEMBER_SECTIONS"
|
||||
:key="section.key"
|
||||
:to="section.path"
|
||||
:aria-current="section.key === activeKey ? 'page' : undefined"
|
||||
>{{ section.label }}</NuxtLink>
|
||||
</nav>
|
||||
<div class="main-panel">
|
||||
<NuxtPage />
|
||||
</div>
|
||||
</div>
|
||||
</SiteHome>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { MEMBER_SECTIONS } from "~/composables/useMemberNav"
|
||||
|
||||
definePageMeta({ layout: false })
|
||||
|
||||
const route = useRoute()
|
||||
const { home, logoUrl, ensureChrome } = useSiteChrome()
|
||||
|
||||
const activeKey = computed(() => {
|
||||
const path = route.path
|
||||
if (path.startsWith("/member/profile")) return "profile"
|
||||
if (path.startsWith("/member/news")) return "news"
|
||||
if (path.startsWith("/member/trainings")) return "trainings"
|
||||
return "orgs"
|
||||
})
|
||||
|
||||
const crumb = computed(() => {
|
||||
const section = MEMBER_SECTIONS.find((item) => item.key === activeKey.value)
|
||||
return `会员服务 / ${section?.label || "会员机构"}`
|
||||
})
|
||||
|
||||
await ensureChrome()
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.crumb {
|
||||
margin: 28px 0 16px;
|
||||
font-size: 13px;
|
||||
color: var(--muted, #5b6b85);
|
||||
}
|
||||
.layout {
|
||||
display: grid;
|
||||
grid-template-columns: 220px minmax(0, 1fr);
|
||||
gap: 20px;
|
||||
margin: 0 0 40px;
|
||||
}
|
||||
.side-nav {
|
||||
align-self: start;
|
||||
padding: 12px 0;
|
||||
background: var(--surface, #fff);
|
||||
border: 1px solid var(--line, #d6e4ff);
|
||||
border-radius: 14px;
|
||||
}
|
||||
.side-nav a {
|
||||
display: block;
|
||||
padding: 10px 16px;
|
||||
font-size: 14px;
|
||||
color: var(--muted, #5b6b85);
|
||||
border-left: 3px solid transparent;
|
||||
text-decoration: none;
|
||||
}
|
||||
.side-nav a[aria-current="page"] {
|
||||
color: var(--c, #1677ff);
|
||||
font-weight: 600;
|
||||
background: var(--chip, #f7faff);
|
||||
border-left-color: var(--c, #1677ff);
|
||||
}
|
||||
.main-panel {
|
||||
background: var(--surface, #fff);
|
||||
border: 1px solid var(--line, #d6e4ff);
|
||||
border-radius: 14px;
|
||||
padding: 22px 24px 28px;
|
||||
min-height: 320px;
|
||||
}
|
||||
@media (max-width: 860px) {
|
||||
.layout { grid-template-columns: 1fr; }
|
||||
.side-nav {
|
||||
display: flex;
|
||||
flex-wrap: nowrap;
|
||||
gap: 0;
|
||||
padding: 0;
|
||||
overflow-x: auto;
|
||||
-webkit-overflow-scrolling: touch;
|
||||
}
|
||||
.side-nav a {
|
||||
flex: none;
|
||||
white-space: nowrap;
|
||||
border-left: 0;
|
||||
border-bottom: 2px solid transparent;
|
||||
}
|
||||
.side-nav a[aria-current="page"] {
|
||||
border-bottom-color: var(--c, #1677ff);
|
||||
background: transparent;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,3 @@
|
||||
<script setup lang="ts">
|
||||
await navigateTo("/member/orgs", { replace: true })
|
||||
</script>
|
||||
@@ -0,0 +1,3 @@
|
||||
<template>
|
||||
<AboutArticleList title="会员资讯" category="member_notices" show-cover />
|
||||
</template>
|
||||
@@ -0,0 +1,64 @@
|
||||
<template>
|
||||
<div>
|
||||
<h2 class="page-title">会员机构</h2>
|
||||
<p v-if="loading" class="hint">列表加载中…</p>
|
||||
<p v-else-if="placeholder" class="placeholder">{{ placeholder }}</p>
|
||||
<ul v-else class="cards">
|
||||
<li v-for="(item, index) in items" :key="`${item.name}-${index}`">
|
||||
<a :href="item.url" target="_blank" rel="noopener">
|
||||
<img :src="item.imageUrl" :alt="item.name" />
|
||||
<span>{{ item.name }}</span>
|
||||
</a>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
const { get } = useSiteApi()
|
||||
|
||||
const loading = ref(true)
|
||||
const placeholder = ref("")
|
||||
const items = ref<{ name: string; url: string; imageUrl: string }[]>([])
|
||||
|
||||
try {
|
||||
const body = await get<any>("/membership/orgs")
|
||||
placeholder.value = body?.placeholder || ""
|
||||
items.value = body?.items || []
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.page-title { margin: 0 0 18px; font-size: 22px; font-weight: 650; letter-spacing: 0.08em; }
|
||||
.placeholder, .hint {
|
||||
margin: 0;
|
||||
padding: 48px 20px;
|
||||
text-align: center;
|
||||
color: var(--muted, #5b6b85);
|
||||
font-size: 15px;
|
||||
}
|
||||
.placeholder { border: 1px dashed var(--line, #d6e4ff); }
|
||||
.cards {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
|
||||
gap: 16px;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
list-style: none;
|
||||
}
|
||||
.cards a {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
height: 100%;
|
||||
color: inherit;
|
||||
text-decoration: none;
|
||||
border: 1px solid var(--line, #d6e4ff);
|
||||
border-radius: 12px;
|
||||
overflow: hidden;
|
||||
background: var(--chip, #f7faff);
|
||||
}
|
||||
.cards img { display: block; width: 100%; height: 120px; object-fit: contain; background: #fff; }
|
||||
.cards span { display: block; padding: 12px 10px 14px; font-size: 14px; font-weight: 600; text-align: center; }
|
||||
</style>
|
||||
@@ -0,0 +1,103 @@
|
||||
<template>
|
||||
<div>
|
||||
<h2 class="page-title">会员信息</h2>
|
||||
<p v-if="!ready" class="hint">正在确认登录状态…</p>
|
||||
<div v-else-if="!isAuthed" class="gate">
|
||||
<p>协会会员档案需登录后查看。账号由协会工作人员开通,并与门户登录邮箱是同一个。</p>
|
||||
<NuxtLink class="btn" :to="loginTo">登录</NuxtLink>
|
||||
</div>
|
||||
<p v-else-if="loading" class="hint">正在读取会员信息…</p>
|
||||
<div v-else-if="!profile" class="gate">
|
||||
<p>当前账号还没有协会会员档案。如需开通,请联系协会。</p>
|
||||
<p class="muted">登录邮箱:{{ email }}</p>
|
||||
</div>
|
||||
<dl v-else class="sheet">
|
||||
<div><dt>会员类型</dt><dd>{{ profile.kindLabel }}</dd></div>
|
||||
<div><dt>名称</dt><dd>{{ profile.displayName || "—" }}</dd></div>
|
||||
<div><dt>会员编号</dt><dd>{{ profile.memberNo || "—" }}</dd></div>
|
||||
<div><dt>会员状态</dt><dd>{{ profile.membershipStatusLabel }}</dd></div>
|
||||
<div><dt>会费</dt><dd>{{ profile.feeStatusLabel }}</dd></div>
|
||||
<div><dt>入会日期</dt><dd>{{ profile.joinedOn || "—" }}</dd></div>
|
||||
<div><dt>到期日</dt><dd>{{ profile.expiresOn || "—" }}</dd></div>
|
||||
<div><dt>登录邮箱</dt><dd>{{ profile.email }}</dd></div>
|
||||
<div><dt>手机号</dt><dd>{{ profile.mobile || "—" }}</dd></div>
|
||||
<div><dt>所在地区</dt><dd>{{ profile.region || "—" }}</dd></div>
|
||||
<div><dt>通讯地址</dt><dd>{{ profile.address || "—" }}</dd></div>
|
||||
<template v-if="profile.kind === 'individual'">
|
||||
<div><dt>性别</dt><dd>{{ profile.genderLabel || "—" }}</dd></div>
|
||||
<div><dt>身份证号</dt><dd>{{ profile.idCard || "—" }}</dd></div>
|
||||
<div><dt>工作单位</dt><dd>{{ profile.employer || "—" }}</dd></div>
|
||||
<div><dt>职务</dt><dd>{{ profile.position || "—" }}</dd></div>
|
||||
<div><dt>学历 / 专业</dt><dd>{{ profile.education || "—" }} / {{ profile.major || "—" }}</dd></div>
|
||||
<div><dt>职称</dt><dd>{{ profile.jobTitle || "—" }}</dd></div>
|
||||
<div><dt>注册证号</dt><dd>{{ profile.appraiserRegNo || "—" }}</dd></div>
|
||||
<div><dt>资格证号</dt><dd>{{ profile.qualificationNo || "—" }}</dd></div>
|
||||
<div><dt>注册有效期</dt><dd>{{ profile.regValidUntil || "—" }}</dd></div>
|
||||
</template>
|
||||
<template v-else>
|
||||
<div><dt>信用代码</dt><dd>{{ profile.creditCode || "—" }}</dd></div>
|
||||
<div><dt>资质等级</dt><dd>{{ profile.qualificationLevel || "—" }}</dd></div>
|
||||
<div><dt>备案编号</dt><dd>{{ profile.filingNo || "—" }}</dd></div>
|
||||
<div><dt>法定代表人</dt><dd>{{ profile.legalPerson || "—" }}</dd></div>
|
||||
<div><dt>办公地址</dt><dd>{{ profile.officeAddress || "—" }}</dd></div>
|
||||
<div><dt>联系人</dt><dd>{{ profile.contactName || "—" }} {{ profile.contactPosition }}</dd></div>
|
||||
<div><dt>联系人手机</dt><dd>{{ profile.contactMobile || "—" }}</dd></div>
|
||||
<div><dt>联系人邮箱</dt><dd>{{ profile.contactEmail || "—" }}</dd></div>
|
||||
</template>
|
||||
<div v-if="profile.remark"><dt>备注</dt><dd>{{ profile.remark }}</dd></div>
|
||||
</dl>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
const route = useRoute()
|
||||
const { get } = useSiteApi()
|
||||
const { token, email, ready, isAuthed, ensure } = useMemberAuth()
|
||||
|
||||
const loading = ref(false)
|
||||
const profile = ref<any>(null)
|
||||
const loginTo = computed(() => ({ path: "/expert/login", query: { redirect: route.fullPath } }))
|
||||
|
||||
async function load() {
|
||||
if (!token.value) return
|
||||
loading.value = true
|
||||
try {
|
||||
const body = await get<{ profile: any }>("/membership/profile", token.value)
|
||||
profile.value = body.profile
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
await ensure()
|
||||
if (isAuthed.value) await load()
|
||||
})
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.page-title { margin: 0 0 18px; font-size: 22px; font-weight: 650; letter-spacing: 0.08em; }
|
||||
.hint, .gate p { color: var(--muted, #5b6b85); font-size: 14px; }
|
||||
.gate { padding: 12px 0 8px; }
|
||||
.muted { margin-top: 8px; }
|
||||
.btn {
|
||||
display: inline-block;
|
||||
margin-top: 8px;
|
||||
padding: 8px 16px;
|
||||
border-radius: 8px;
|
||||
background: var(--c, #1677ff);
|
||||
color: #fff;
|
||||
text-decoration: none;
|
||||
}
|
||||
.sheet { margin: 0; }
|
||||
.sheet div {
|
||||
display: grid;
|
||||
grid-template-columns: 120px minmax(0, 1fr);
|
||||
gap: 8px;
|
||||
padding: 8px 0;
|
||||
border-bottom: 1px solid var(--line, #d6e4ff);
|
||||
font-size: 14px;
|
||||
}
|
||||
.sheet dt { color: var(--muted, #5b6b85); }
|
||||
.sheet dd { margin: 0; }
|
||||
</style>
|
||||
@@ -0,0 +1,185 @@
|
||||
<template>
|
||||
<div>
|
||||
<p v-if="loading" class="hint">正在读取公告…</p>
|
||||
<p v-else-if="missing" class="placeholder">培训公告不存在或尚未发布</p>
|
||||
<template v-else-if="event">
|
||||
<h2 class="page-title">{{ event.title }}</h2>
|
||||
<p class="meta">
|
||||
{{ event.startsOn || "时间待定" }}<template v-if="event.endsOn"> 至 {{ event.endsOn }}</template>
|
||||
<template v-if="event.place"> · {{ event.place }}</template>
|
||||
· {{ event.quota == null ? "名额不限" : `剩余 ${event.remaining} 名` }}
|
||||
</p>
|
||||
<div v-if="event.bodyHtml" class="body" v-html="event.bodyHtml" />
|
||||
<section v-if="event.payeeName || event.bankAccount" class="pay">
|
||||
<h3>转账说明</h3>
|
||||
<p v-if="event.transferNote">{{ event.transferNote }}</p>
|
||||
<p v-if="event.payeeName">账户名称:{{ event.payeeName }}</p>
|
||||
<p v-if="event.bankName">开户行:{{ event.bankName }}</p>
|
||||
<p v-if="event.bankAccount">账号:{{ event.bankAccount }}</p>
|
||||
<p v-if="event.lodgingNote">食宿标准:{{ event.lodgingNote }}</p>
|
||||
</section>
|
||||
|
||||
<section v-if="!ready" class="hint">正在确认登录状态…</section>
|
||||
<section v-else-if="!isAuthed" class="gate">
|
||||
<p>报名需要使用协会开通的门户账号登录。</p>
|
||||
<NuxtLink class="btn" :to="loginTo">登录后报名</NuxtLink>
|
||||
</section>
|
||||
<section v-else-if="mine" class="done">
|
||||
<h3>我的报名</h3>
|
||||
<p>{{ mine.personName }} · {{ mine.orgName }} · {{ mine.lodgingLabel }}</p>
|
||||
<p>用餐:{{ mine.dine ? (mine.mealDates || []).join("、") || "是" : "否" }}</p>
|
||||
</section>
|
||||
<form v-else class="form" @submit.prevent="submit">
|
||||
<h3>填写报名</h3>
|
||||
<div class="grid">
|
||||
<label>所在地区 *<input v-model="form.region" required></label>
|
||||
<label>单位名称 *<input v-model="form.orgName" required></label>
|
||||
<label>姓名 *<input v-model="form.personName" required></label>
|
||||
<label>性别 *
|
||||
<span class="choices">
|
||||
<label><input v-model="form.gender" type="radio" value="male"> 男</label>
|
||||
<label><input v-model="form.gender" type="radio" value="female"> 女</label>
|
||||
</span>
|
||||
</label>
|
||||
<label>职务 *<input v-model="form.position" required></label>
|
||||
<label>身份证号 *<input v-model="form.idCard" required></label>
|
||||
<label>联系电话 *<input v-model="form.mobile" required maxlength="11"></label>
|
||||
<label>估价师注册证号 *<input v-model="form.appraiserRegNo" required maxlength="10" placeholder="10 位数字"></label>
|
||||
<label>邮箱 *<input v-model="form.email" type="email" required></label>
|
||||
<label>住宿 *
|
||||
<span class="choices">
|
||||
<label><input v-model="form.lodging" type="radio" value="association"> 协会代订</label>
|
||||
<label><input v-model="form.lodging" type="radio" value="self"> 自理</label>
|
||||
</span>
|
||||
</label>
|
||||
</div>
|
||||
<div v-if="form.lodging === 'association'" class="rooms">
|
||||
<label><input v-model="form.roomStandard" type="checkbox"> 标间</label>
|
||||
<label v-if="form.roomStandard">间数 <input v-model.number="form.standardCount" type="number" min="1" max="99"></label>
|
||||
<label><input v-model="form.roomSingle" type="checkbox"> 单间</label>
|
||||
<label v-if="form.roomSingle">间数 <input v-model.number="form.singleCount" type="number" min="1" max="99"></label>
|
||||
</div>
|
||||
<div class="meal">
|
||||
<span>是否用餐{{ event.mealNote ? `(${event.mealNote})` : "" }} *</span>
|
||||
<label><input v-model="form.dine" type="radio" :value="true"> 是</label>
|
||||
<label><input v-model="form.dine" type="radio" :value="false"> 否</label>
|
||||
</div>
|
||||
<div v-if="form.dine" class="meal-dates">
|
||||
<p>用餐日期(可多选)</p>
|
||||
<label v-for="day in event.mealDates" :key="day">
|
||||
<input v-model="form.mealDates" type="checkbox" :value="day"> {{ day }}
|
||||
</label>
|
||||
<p v-if="!event.mealDates?.length" class="hint">本场未设置用餐日期</p>
|
||||
</div>
|
||||
<p v-if="error" class="error">{{ error }}</p>
|
||||
<button class="btn" type="submit" :disabled="busy">提交报名</button>
|
||||
</form>
|
||||
</template>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
const route = useRoute()
|
||||
const { get, post } = useSiteApi()
|
||||
const { token, email, ready, isAuthed, ensure } = useMemberAuth()
|
||||
|
||||
const loading = ref(true)
|
||||
const missing = ref(false)
|
||||
const busy = ref(false)
|
||||
const error = ref("")
|
||||
const event = ref<any>(null)
|
||||
const mine = ref<any>(null)
|
||||
const loginTo = computed(() => ({ path: "/expert/login", query: { redirect: route.fullPath } }))
|
||||
|
||||
const form = reactive({
|
||||
region: "",
|
||||
orgName: "",
|
||||
personName: "",
|
||||
gender: "male",
|
||||
position: "",
|
||||
idCard: "",
|
||||
mobile: "",
|
||||
appraiserRegNo: "",
|
||||
email: "",
|
||||
lodging: "self",
|
||||
roomStandard: false,
|
||||
roomSingle: false,
|
||||
standardCount: 1,
|
||||
singleCount: 1,
|
||||
dine: false,
|
||||
mealDates: [] as string[],
|
||||
})
|
||||
|
||||
const eventId = computed(() => String(route.params.id || ""))
|
||||
|
||||
async function loadMine() {
|
||||
if (!token.value || !event.value) return
|
||||
const body = await get<any>("/membership/registrations", token.value)
|
||||
mine.value = (body?.items || []).find((item: any) => String(item.eventId) === eventId.value) || null
|
||||
}
|
||||
|
||||
try {
|
||||
event.value = await get<any>(`/membership/events/${eventId.value}`)
|
||||
} catch {
|
||||
missing.value = true
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
await ensure()
|
||||
if (email.value) form.email = email.value
|
||||
await loadMine()
|
||||
})
|
||||
|
||||
async function submit() {
|
||||
error.value = ""
|
||||
busy.value = true
|
||||
try {
|
||||
const saved = await post<any>(
|
||||
`/membership/events/${eventId.value}/registrations`,
|
||||
{ ...form, mealDates: form.dine ? form.mealDates : [] },
|
||||
token.value,
|
||||
)
|
||||
mine.value = { ...saved, eventId: Number(eventId.value) }
|
||||
if (event.value && event.value.remaining != null) event.value.remaining = Math.max(event.value.remaining - 1, 0)
|
||||
} catch (exc: any) {
|
||||
error.value = exc?.data?.detail || exc?.message || "报名失败"
|
||||
} finally {
|
||||
busy.value = false
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.page-title { margin: 0 0 8px; font-size: 22px; font-weight: 650; }
|
||||
.meta, .hint, .placeholder { color: var(--muted, #5b6b85); font-size: 14px; }
|
||||
.body :deep(p) { line-height: 1.7; }
|
||||
.pay, .done, .form, .gate { margin-top: 20px; padding-top: 16px; border-top: 1px solid var(--line, #d6e4ff); }
|
||||
.pay p, .done p { margin: 4px 0; font-size: 14px; }
|
||||
.grid { display: grid; grid-template-columns: 1fr 1fr; gap: 12px 16px; }
|
||||
label { display: flex; flex-direction: column; gap: 6px; font-size: 13px; color: var(--muted, #5b6b85); }
|
||||
input[type="text"], input[type="email"], input[type="number"], input:not([type]) {
|
||||
padding: 8px 10px;
|
||||
border: 1px solid var(--line, #d6e4ff);
|
||||
border-radius: 8px;
|
||||
font: inherit;
|
||||
color: var(--text, #0b1f3a);
|
||||
}
|
||||
.choices, .rooms, .meal, .meal-dates { display: flex; flex-wrap: wrap; gap: 12px; align-items: center; margin-top: 12px; }
|
||||
.rooms label, .meal label, .meal-dates label, .choices label { flex-direction: row; align-items: center; color: var(--text, #0b1f3a); }
|
||||
.btn {
|
||||
margin-top: 16px;
|
||||
border: 0;
|
||||
border-radius: 8px;
|
||||
padding: 8px 16px;
|
||||
background: var(--c, #1677ff);
|
||||
color: #fff;
|
||||
text-decoration: none;
|
||||
cursor: pointer;
|
||||
}
|
||||
.error { color: #b91c1c; font-size: 13px; }
|
||||
@media (max-width: 720px) {
|
||||
.grid { grid-template-columns: 1fr; }
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,70 @@
|
||||
<template>
|
||||
<div>
|
||||
<h2 class="page-title">培训报名</h2>
|
||||
<p v-if="loading" class="hint">列表加载中…</p>
|
||||
<p v-else-if="!items.length" class="placeholder">暂无培训报名</p>
|
||||
<ul v-else class="list">
|
||||
<li v-for="item in items" :key="item.id">
|
||||
<NuxtLink :to="`/member/trainings/${item.id}`">
|
||||
<strong>{{ item.title }}</strong>
|
||||
<span>{{ item.startsOn || "时间待定" }}<template v-if="item.place"> · {{ item.place }}</template></span>
|
||||
<em>{{ item.quota == null ? "名额不限" : `剩余 ${item.remaining} 名` }}</em>
|
||||
</NuxtLink>
|
||||
</li>
|
||||
</ul>
|
||||
<section v-if="ready && isAuthed" class="mine">
|
||||
<h3>我的报名</h3>
|
||||
<p v-if="!mine.length" class="hint">还没有报名记录</p>
|
||||
<ul v-else>
|
||||
<li v-for="item in mine" :key="item.id">
|
||||
<NuxtLink :to="`/member/trainings/${item.eventId}`">{{ item.eventTitle }}</NuxtLink>
|
||||
<span>{{ item.personName }} · {{ item.dine ? (item.mealDates || []).join("、") || "用餐" : "不用餐" }}</span>
|
||||
</li>
|
||||
</ul>
|
||||
</section>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
const { get } = useSiteApi()
|
||||
const { token, ready, isAuthed, ensure } = useMemberAuth()
|
||||
|
||||
const loading = ref(true)
|
||||
const items = ref<any[]>([])
|
||||
const mine = ref<any[]>([])
|
||||
|
||||
try {
|
||||
const body = await get<any>("/membership/events")
|
||||
items.value = body?.items || []
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
await ensure()
|
||||
if (!token.value) return
|
||||
const body = await get<any>("/membership/registrations", token.value)
|
||||
mine.value = body?.items || []
|
||||
})
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.page-title { margin: 0 0 18px; font-size: 22px; font-weight: 650; letter-spacing: 0.08em; }
|
||||
.hint, .placeholder { color: var(--muted, #5b6b85); font-size: 14px; }
|
||||
.placeholder { margin: 0; padding: 48px 20px; text-align: center; border: 1px dashed var(--line, #d6e4ff); }
|
||||
.list, .mine ul { list-style: none; margin: 0; padding: 0; }
|
||||
.list a, .mine li {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px 16px;
|
||||
align-items: baseline;
|
||||
padding: 12px 0;
|
||||
border-bottom: 1px solid var(--line, #d6e4ff);
|
||||
color: inherit;
|
||||
text-decoration: none;
|
||||
}
|
||||
.list strong { font-size: 16px; }
|
||||
.list span, .list em, .mine span { color: var(--muted, #5b6b85); font-size: 13px; font-style: normal; }
|
||||
.mine { margin-top: 28px; }
|
||||
.mine h3 { margin: 0 0 8px; font-size: 16px; }
|
||||
</style>
|
||||
@@ -1,38 +1,18 @@
|
||||
<template>
|
||||
<SiteLoading v-if="!home" hint="正在读取内容" />
|
||||
<SiteHome v-else :home="home" :logo-url="logoUrl">
|
||||
<p class="crumb">首页 / {{ crumb }}</p>
|
||||
<div class="layout">
|
||||
<nav class="side-nav" aria-label="报告核验">
|
||||
<NuxtLink
|
||||
v-for="section in REPORT_SECTIONS"
|
||||
:key="section.key"
|
||||
:to="section.path"
|
||||
:aria-current="section.key === activeKey ? 'page' : undefined"
|
||||
>{{ section.label }}</NuxtLink>
|
||||
</nav>
|
||||
<div class="main-panel" :class="{ 'is-chat': activeKey === 'review' }">
|
||||
<NuxtPage />
|
||||
</div>
|
||||
<p class="crumb">首页 / 报告核验 / 报告查询</p>
|
||||
<div class="main-panel">
|
||||
<NuxtPage />
|
||||
</div>
|
||||
</SiteHome>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { REPORT_SECTIONS } from "~/composables/useReportNav"
|
||||
|
||||
definePageMeta({ layout: false })
|
||||
|
||||
const route = useRoute()
|
||||
const { home, logoUrl, ensureChrome } = useSiteChrome()
|
||||
|
||||
const activeKey = computed(() => (route.path.startsWith("/reports/review") ? "review" : "query"))
|
||||
|
||||
const crumb = computed(() => {
|
||||
const section = REPORT_SECTIONS.find((item) => item.key === activeKey.value)
|
||||
return `报告核验 / ${section?.label || "报告查询"}`
|
||||
})
|
||||
|
||||
await ensureChrome()
|
||||
</script>
|
||||
|
||||
@@ -42,63 +22,12 @@ await ensureChrome()
|
||||
font-size: 13px;
|
||||
color: var(--muted, #5b6b85);
|
||||
}
|
||||
.layout {
|
||||
display: grid;
|
||||
grid-template-columns: 220px minmax(0, 1fr);
|
||||
gap: 20px;
|
||||
margin: 0 0 40px;
|
||||
}
|
||||
.side-nav {
|
||||
align-self: start;
|
||||
padding: 12px 0;
|
||||
background: var(--surface, #fff);
|
||||
border: 1px solid var(--line, #d6e4ff);
|
||||
border-radius: 14px;
|
||||
}
|
||||
.side-nav a {
|
||||
display: block;
|
||||
padding: 10px 16px;
|
||||
font-size: 14px;
|
||||
color: var(--muted, #5b6b85);
|
||||
border-left: 3px solid transparent;
|
||||
text-decoration: none;
|
||||
}
|
||||
.side-nav a[aria-current="page"] {
|
||||
color: var(--c, #1677ff);
|
||||
font-weight: 600;
|
||||
background: var(--chip, #f7faff);
|
||||
border-left-color: var(--c, #1677ff);
|
||||
}
|
||||
.main-panel {
|
||||
background: var(--surface, #fff);
|
||||
border: 1px solid var(--line, #d6e4ff);
|
||||
border-radius: 14px;
|
||||
padding: 22px 24px 28px;
|
||||
min-height: 320px;
|
||||
}
|
||||
.main-panel.is-chat {
|
||||
padding: 0;
|
||||
overflow: hidden;
|
||||
min-height: 640px;
|
||||
}
|
||||
@media (max-width: 860px) {
|
||||
.layout { grid-template-columns: 1fr; }
|
||||
.side-nav {
|
||||
display: flex;
|
||||
flex-wrap: nowrap;
|
||||
gap: 0;
|
||||
padding: 0;
|
||||
overflow-x: auto;
|
||||
}
|
||||
.side-nav a {
|
||||
flex: none;
|
||||
white-space: nowrap;
|
||||
border-left: 0;
|
||||
border-bottom: 2px solid transparent;
|
||||
}
|
||||
.side-nav a[aria-current="page"] {
|
||||
border-bottom-color: var(--c, #1677ff);
|
||||
background: transparent;
|
||||
}
|
||||
margin: 0 0 40px;
|
||||
}
|
||||
</style>
|
||||
@@ -1,222 +1,3 @@
|
||||
<template>
|
||||
<section class="chat" aria-label="报告审核">
|
||||
<header class="chat-head">
|
||||
<div class="brand">
|
||||
<span class="mark" aria-hidden="true">审</span>
|
||||
<div>
|
||||
<h2>报告审核</h2>
|
||||
<p>选择报告文件并提问。当前为演示,不会保存,也不会生成审核结论。</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="head-actions">
|
||||
<span class="status">演示 · 尚未开通</span>
|
||||
<button type="button" class="text-btn" @click="resetChat">清空对话</button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div ref="scroller" class="thread" role="log" aria-live="polite">
|
||||
<article v-for="item in messages" :key="item.id" class="row" :class="item.role">
|
||||
<span v-if="item.role === 'assistant'" class="avatar" aria-hidden="true">协</span>
|
||||
<div class="bubble"><p>{{ item.text }}</p></div>
|
||||
</article>
|
||||
<div v-if="showSuggestions" class="suggestions">
|
||||
<p>可以先试这些问题</p>
|
||||
<div>
|
||||
<button v-for="item in SUGGESTIONS" :key="item" type="button" @click="send(item)">{{ item }}</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<form class="composer" @submit.prevent="send()">
|
||||
<div class="file-row">
|
||||
<label class="file-btn">
|
||||
选择文件
|
||||
<input type="file" :disabled="replying" @change="onFile">
|
||||
</label>
|
||||
<span v-if="fileName" class="file-name">{{ fileName }}</span>
|
||||
<button v-if="fileName" type="button" class="text-btn" @click="clearFile">移除</button>
|
||||
</div>
|
||||
<label class="sr-only" for="review-draft">输入问题</label>
|
||||
<textarea
|
||||
id="review-draft"
|
||||
ref="draftEl"
|
||||
v-model="draft"
|
||||
rows="1"
|
||||
maxlength="500"
|
||||
placeholder="例如:建筑面积前后是否一致?"
|
||||
@input="resizeDraft"
|
||||
@keydown.enter.exact.prevent="send()"
|
||||
/>
|
||||
<button type="submit" :disabled="!canSend">提交</button>
|
||||
<p class="composer-note">提交后只提示功能尚未开通。文件和问题都留在这台浏览器里,不会上传。</p>
|
||||
</form>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
const WELCOME = "您好。可以选择一份报告文件,再提出想核对的问题。当前为演示,功能尚未开通,不会保存内容,也不会生成审核结论。"
|
||||
const NOTICE = "功能尚未开通。提交内容不会被保存,也不会生成审核结论。"
|
||||
const SUGGESTIONS = [
|
||||
"报告中的建筑面积前后是否一致?",
|
||||
"估价时点与报告日期是否一致?",
|
||||
"文字里有没有明显错别字?",
|
||||
]
|
||||
|
||||
type ChatMessage = { id: number; role: "assistant" | "user"; text: string }
|
||||
|
||||
const messages = ref<ChatMessage[]>([{ id: 1, role: "assistant", text: WELCOME }])
|
||||
const draft = ref("")
|
||||
const fileName = ref("")
|
||||
const replying = ref(false)
|
||||
const scroller = ref<HTMLElement | null>(null)
|
||||
const draftEl = ref<HTMLTextAreaElement | null>(null)
|
||||
const fileEl = ref<HTMLInputElement | null>(null)
|
||||
let seq = 1
|
||||
|
||||
const showSuggestions = computed(() => messages.value.length === 1 && !replying.value)
|
||||
const canSend = computed(() => draft.value.trim().length > 0 && !replying.value)
|
||||
|
||||
function nextId() {
|
||||
seq += 1
|
||||
return seq
|
||||
}
|
||||
|
||||
async function scrollToEnd() {
|
||||
await nextTick()
|
||||
const el = scroller.value
|
||||
if (el) el.scrollTop = el.scrollHeight
|
||||
}
|
||||
|
||||
function resizeDraft() {
|
||||
const el = draftEl.value
|
||||
if (!el) return
|
||||
el.style.height = "auto"
|
||||
el.style.height = `${Math.min(el.scrollHeight, 120)}px`
|
||||
}
|
||||
|
||||
function onFile(event: Event) {
|
||||
const input = event.target as HTMLInputElement
|
||||
fileEl.value = input
|
||||
fileName.value = input.files?.[0]?.name || ""
|
||||
}
|
||||
|
||||
function clearFile() {
|
||||
fileName.value = ""
|
||||
if (fileEl.value) fileEl.value.value = ""
|
||||
}
|
||||
|
||||
async function send(text?: string) {
|
||||
const content = (text ?? draft.value).trim()
|
||||
if (!content || replying.value) return
|
||||
const attached = fileName.value
|
||||
draft.value = ""
|
||||
clearFile()
|
||||
await nextTick()
|
||||
resizeDraft()
|
||||
const line = attached ? `${content}\n附件:${attached}` : content
|
||||
messages.value.push({ id: nextId(), role: "user", text: line })
|
||||
messages.value.push({ id: nextId(), role: "assistant", text: NOTICE })
|
||||
await scrollToEnd()
|
||||
}
|
||||
|
||||
async function resetChat() {
|
||||
replying.value = false
|
||||
draft.value = ""
|
||||
clearFile()
|
||||
messages.value = [{ id: nextId(), role: "assistant", text: WELCOME }]
|
||||
await nextTick()
|
||||
resizeDraft()
|
||||
await scrollToEnd()
|
||||
}
|
||||
await navigateTo("/reports/query", { replace: true })
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.chat {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-height: 640px;
|
||||
height: min(720px, calc(100vh - 220px));
|
||||
}
|
||||
.chat-head {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 16px;
|
||||
padding: 18px 22px 14px;
|
||||
border-bottom: 1px solid var(--line, #d6e4ff);
|
||||
}
|
||||
.brand { display: flex; align-items: center; gap: 12px; min-width: 0; }
|
||||
.mark {
|
||||
display: grid; place-items: center; width: 40px; height: 40px; flex: none;
|
||||
color: #fff; background: var(--c, #1677ff); border-radius: 12px; font-weight: 650;
|
||||
}
|
||||
.chat-head h2 { margin: 0; font-size: 18px; font-weight: 650; letter-spacing: 0.06em; }
|
||||
.chat-head p { margin: 4px 0 0; font-size: 13px; color: var(--muted, #5b6b85); }
|
||||
.head-actions { display: flex; flex-direction: column; align-items: flex-end; gap: 8px; flex: none; }
|
||||
.status {
|
||||
padding: 4px 10px; border-radius: 999px; font-size: 12px;
|
||||
background: color-mix(in srgb, var(--c, #1677ff) 10%, var(--surface, #fff));
|
||||
color: var(--c, #1677ff);
|
||||
}
|
||||
.text-btn {
|
||||
appearance: none; border: 0; background: transparent; padding: 0;
|
||||
color: var(--muted, #5b6b85); font: inherit; font-size: 13px; cursor: pointer;
|
||||
}
|
||||
.thread { flex: 1; min-height: 0; overflow-y: auto; padding: 22px 22px 8px; }
|
||||
.row { display: flex; align-items: flex-start; gap: 10px; margin-bottom: 16px; }
|
||||
.row.user { justify-content: flex-end; }
|
||||
.avatar {
|
||||
display: grid; place-items: center; width: 32px; height: 32px; flex: none; border-radius: 50%;
|
||||
background: color-mix(in srgb, var(--c, #1677ff) 14%, var(--surface, #fff));
|
||||
color: var(--c, #1677ff); font-size: 13px; font-weight: 650;
|
||||
}
|
||||
.bubble {
|
||||
max-width: min(78%, 560px); padding: 12px 14px;
|
||||
border-radius: 4px 14px 14px 14px;
|
||||
background: color-mix(in srgb, var(--c, #1677ff) 7%, var(--surface, #fff));
|
||||
border: 1px solid var(--line, #d6e4ff);
|
||||
}
|
||||
.bubble p { margin: 0; font-size: 14px; line-height: 1.7; white-space: pre-wrap; overflow-wrap: anywhere; }
|
||||
.row.user .bubble {
|
||||
border-radius: 14px 4px 14px 14px; background: var(--c, #1677ff); border-color: var(--c, #1677ff); color: #fff;
|
||||
}
|
||||
.suggestions { margin: 4px 0 18px 42px; }
|
||||
.suggestions p { margin: 0 0 8px; font-size: 12px; color: var(--muted, #5b6b85); }
|
||||
.suggestions div { display: flex; flex-wrap: wrap; gap: 8px; }
|
||||
.suggestions button {
|
||||
appearance: none; max-width: 100%; padding: 8px 12px; border: 1px solid var(--line, #d6e4ff);
|
||||
border-radius: 999px; background: var(--surface, #fff); color: var(--text, #0b1f3a);
|
||||
font: inherit; font-size: 13px; text-align: left; cursor: pointer;
|
||||
}
|
||||
.composer {
|
||||
display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 10px 12px;
|
||||
padding: 12px 22px 16px; border-top: 1px solid var(--line, #d6e4ff);
|
||||
}
|
||||
.file-row { grid-column: 1 / -1; display: flex; flex-wrap: wrap; align-items: center; gap: 8px; }
|
||||
.file-btn {
|
||||
position: relative; overflow: hidden; padding: 6px 12px; border-radius: 999px;
|
||||
border: 1px solid var(--line, #d6e4ff); font-size: 13px; cursor: pointer;
|
||||
}
|
||||
.file-btn input { position: absolute; inset: 0; opacity: 0; cursor: pointer; }
|
||||
.file-name { font-size: 13px; color: var(--muted, #5b6b85); }
|
||||
.composer textarea {
|
||||
width: 100%; min-height: 44px; max-height: 120px; resize: none; padding: 11px 12px;
|
||||
border: 1px solid var(--line, #d6e4ff); border-radius: 12px; background: var(--surface, #fff);
|
||||
color: var(--text, #0b1f3a); font: inherit; font-size: 14px; line-height: 1.5;
|
||||
}
|
||||
.composer button[type="submit"] {
|
||||
align-self: end; height: 44px; min-width: 76px; padding: 0 16px; border: 0; border-radius: 12px;
|
||||
background: var(--c, #1677ff); color: #fff; font: inherit; font-size: 14px; cursor: pointer;
|
||||
}
|
||||
.composer button[type="submit"]:disabled { opacity: 0.45; cursor: not-allowed; }
|
||||
.composer-note { grid-column: 1 / -1; margin: 0; font-size: 12px; line-height: 1.5; color: var(--muted, #5b6b85); }
|
||||
.sr-only {
|
||||
position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden;
|
||||
clip: rect(0, 0, 0, 0); white-space: nowrap; border: 0;
|
||||
}
|
||||
@media (max-width: 860px) {
|
||||
.chat { height: auto; min-height: 560px; }
|
||||
.chat-head, .thread, .composer { padding-left: 16px; padding-right: 16px; }
|
||||
.suggestions { margin-left: 0; }
|
||||
}
|
||||
</style>
|
||||
+1
-1
@@ -42,7 +42,7 @@ server/
|
||||
|
||||
机构名录不要单独造一套与会员无关的机构主数据。报告查询只对照报告备案,不要做文件验真、核验码或报告审核的保存接口,见 `docs/adr/0010-report-query-is-filing-lookup.md`。数据挖掘、智能估价、中房学和住建厅的数据对接,不要建客户端或同步任务。
|
||||
|
||||
投诉时限、专家回复时限放配置,不写死。行业自律的投诉、警示案例、诚信档案和结果公示见 `docs/adr/0012-industry-discipline-articles-and-complaint-code.md`。
|
||||
投诉时限、专家回复时限放配置,不写死。行业自律的投诉、警示案例、诚信档案和结果公示见 `docs/adr/0012-industry-discipline-articles-and-complaint-code.md`。会员服务见 `docs/adr/0013-member-service-is-four-modules.md`:中房学和住建厅只存外链,协会会员档案同步门户邮箱账号,培训报名的用餐日期按每场公告配置。
|
||||
|
||||
## 接口约定
|
||||
|
||||
|
||||
@@ -121,6 +121,7 @@ class ComplianceWrite(BaseModel):
|
||||
|
||||
class HonorItemWrite(BaseModel):
|
||||
imageFileId: int
|
||||
caption: str = ""
|
||||
sortOrder: int = 0
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,289 @@
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, status
|
||||
from pydantic import BaseModel, Field
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.core.deps import require_staff
|
||||
from app.db import get_db
|
||||
from app.models.membership import (
|
||||
admin_org_links,
|
||||
create_event,
|
||||
create_profile,
|
||||
create_registration,
|
||||
delete_event,
|
||||
delete_profile,
|
||||
delete_registration,
|
||||
list_events,
|
||||
list_profiles,
|
||||
list_registrations,
|
||||
read_event,
|
||||
read_profile,
|
||||
read_registration,
|
||||
save_org_links,
|
||||
update_event,
|
||||
update_profile,
|
||||
update_registration,
|
||||
)
|
||||
from app.models.member import SiteMember
|
||||
from app.services.email_code import normalize_email
|
||||
from app.services.password import DEFAULT_MEMBER_PASSWORD, hash_password, validate_member_password
|
||||
|
||||
router = APIRouter(dependencies=[Depends(require_staff)])
|
||||
|
||||
|
||||
class OrgLinkWrite(BaseModel):
|
||||
name: str = ""
|
||||
url: str = ""
|
||||
imageFileId: int | None = None
|
||||
sortOrder: int = 0
|
||||
|
||||
|
||||
class OrgLinksWrite(BaseModel):
|
||||
items: list[OrgLinkWrite] = Field(default_factory=list)
|
||||
|
||||
|
||||
class ProfileWrite(BaseModel):
|
||||
email: str = ""
|
||||
password: str | None = None
|
||||
kind: str = "individual"
|
||||
memberNo: str = ""
|
||||
membershipStatus: str = "active"
|
||||
joinedOn: str = ""
|
||||
expiresOn: str = ""
|
||||
feeStatus: str = "unpaid"
|
||||
mobile: str = ""
|
||||
region: str = ""
|
||||
address: str = ""
|
||||
postalCode: str = ""
|
||||
remark: str = ""
|
||||
personName: str = ""
|
||||
gender: str = ""
|
||||
birthDate: str = ""
|
||||
idCard: str = ""
|
||||
education: str = ""
|
||||
major: str = ""
|
||||
jobTitle: str = ""
|
||||
practiceYears: int | None = None
|
||||
employer: str = ""
|
||||
position: str = ""
|
||||
appraiserRegNo: str = ""
|
||||
qualificationNo: str = ""
|
||||
regValidUntil: str = ""
|
||||
photoFileId: int | None = None
|
||||
orgName: str = ""
|
||||
creditCode: str = ""
|
||||
qualificationLevel: str = ""
|
||||
filingNo: str = ""
|
||||
legalPerson: str = ""
|
||||
contactName: str = ""
|
||||
contactPosition: str = ""
|
||||
contactMobile: str = ""
|
||||
contactEmail: str = ""
|
||||
officeAddress: str = ""
|
||||
|
||||
|
||||
class EventWrite(BaseModel):
|
||||
title: str = ""
|
||||
place: str = ""
|
||||
startsOn: str = ""
|
||||
endsOn: str = ""
|
||||
quota: int | None = None
|
||||
bodyHtml: str = ""
|
||||
published: bool = False
|
||||
mealNote: str = ""
|
||||
mealDates: list[str] = Field(default_factory=list)
|
||||
payeeName: str = ""
|
||||
bankName: str = ""
|
||||
bankAccount: str = ""
|
||||
transferNote: str = ""
|
||||
lodgingNote: str = ""
|
||||
|
||||
|
||||
class RegistrationWrite(BaseModel):
|
||||
region: str = ""
|
||||
orgName: str = ""
|
||||
personName: str = ""
|
||||
gender: str = ""
|
||||
position: str = ""
|
||||
idCard: str = ""
|
||||
mobile: str = ""
|
||||
appraiserRegNo: str = ""
|
||||
email: str = ""
|
||||
lodging: str = "self"
|
||||
roomStandard: bool = False
|
||||
roomSingle: bool = False
|
||||
standardCount: int = 0
|
||||
singleCount: int = 0
|
||||
dine: bool = False
|
||||
mealDates: list[str] = Field(default_factory=list)
|
||||
|
||||
|
||||
def _bad(exc: Exception) -> None:
|
||||
if isinstance(exc, LookupError):
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)) from exc
|
||||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc)) from exc
|
||||
|
||||
|
||||
def _password(value: str | None, *, default_if_blank: bool) -> str | None:
|
||||
password = (value or "").strip()
|
||||
if not password:
|
||||
if not default_if_blank:
|
||||
return None
|
||||
password = DEFAULT_MEMBER_PASSWORD
|
||||
validate_member_password(password)
|
||||
return hash_password(password)
|
||||
|
||||
|
||||
def _is_new_portal_account(db: Session, email: str) -> bool:
|
||||
normalized = normalize_email(email or "")
|
||||
if not normalized:
|
||||
return True
|
||||
found = db.scalar(select(SiteMember.id).where(SiteMember.email == normalized))
|
||||
return found is None
|
||||
|
||||
|
||||
@router.get("/membership/orgs")
|
||||
def read_orgs(db: Session = Depends(get_db)) -> dict:
|
||||
return admin_org_links(db)
|
||||
|
||||
|
||||
@router.put("/membership/orgs")
|
||||
def write_orgs(body: OrgLinksWrite, db: Session = Depends(get_db)) -> dict:
|
||||
try:
|
||||
save_org_links(db, [item.model_dump() for item in body.items])
|
||||
except ValueError as exc:
|
||||
_bad(exc)
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@router.get("/membership/profiles")
|
||||
def read_profiles(
|
||||
current: int = Query(default=1),
|
||||
size: int = Query(default=10),
|
||||
keyword: str = Query(default=""),
|
||||
db: Session = Depends(get_db),
|
||||
) -> dict:
|
||||
return list_profiles(db, current=current, size=size, keyword=keyword)
|
||||
|
||||
|
||||
@router.post("/membership/profiles")
|
||||
def add_profile(body: ProfileWrite, db: Session = Depends(get_db)) -> dict:
|
||||
try:
|
||||
return create_profile(
|
||||
db,
|
||||
body.model_dump(),
|
||||
_password(body.password, default_if_blank=_is_new_portal_account(db, body.email)),
|
||||
)
|
||||
except (ValueError, LookupError) as exc:
|
||||
_bad(exc)
|
||||
|
||||
|
||||
@router.get("/membership/profiles/{profile_id}")
|
||||
def get_profile(profile_id: int, db: Session = Depends(get_db)) -> dict:
|
||||
try:
|
||||
return read_profile(db, profile_id, reveal=True)
|
||||
except LookupError as exc:
|
||||
_bad(exc)
|
||||
|
||||
|
||||
@router.put("/membership/profiles/{profile_id}")
|
||||
def edit_profile(profile_id: int, body: ProfileWrite, db: Session = Depends(get_db)) -> dict:
|
||||
try:
|
||||
return update_profile(db, profile_id, body.model_dump(), _password(body.password, default_if_blank=False))
|
||||
except (ValueError, LookupError) as exc:
|
||||
_bad(exc)
|
||||
|
||||
|
||||
@router.delete("/membership/profiles/{profile_id}")
|
||||
def remove_profile(profile_id: int, db: Session = Depends(get_db)) -> dict:
|
||||
try:
|
||||
delete_profile(db, profile_id)
|
||||
except LookupError as exc:
|
||||
_bad(exc)
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@router.get("/membership/events")
|
||||
def read_events(db: Session = Depends(get_db)) -> dict:
|
||||
return list_events(db, published_only=False)
|
||||
|
||||
|
||||
@router.post("/membership/events")
|
||||
def add_event(body: EventWrite, db: Session = Depends(get_db)) -> dict:
|
||||
try:
|
||||
return create_event(db, body.model_dump())
|
||||
except ValueError as exc:
|
||||
_bad(exc)
|
||||
|
||||
|
||||
@router.get("/membership/events/{event_id}")
|
||||
def get_event(event_id: int, db: Session = Depends(get_db)) -> dict:
|
||||
try:
|
||||
return read_event(db, event_id, published_only=False)
|
||||
except LookupError as exc:
|
||||
_bad(exc)
|
||||
|
||||
|
||||
@router.put("/membership/events/{event_id}")
|
||||
def edit_event(event_id: int, body: EventWrite, db: Session = Depends(get_db)) -> dict:
|
||||
try:
|
||||
return update_event(db, event_id, body.model_dump())
|
||||
except (ValueError, LookupError) as exc:
|
||||
_bad(exc)
|
||||
|
||||
|
||||
@router.delete("/membership/events/{event_id}")
|
||||
def remove_event(event_id: int, db: Session = Depends(get_db)) -> dict:
|
||||
try:
|
||||
delete_event(db, event_id)
|
||||
except LookupError as exc:
|
||||
_bad(exc)
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@router.get("/membership/events/{event_id}/registrations")
|
||||
def read_registrations(event_id: int, db: Session = Depends(get_db)) -> dict:
|
||||
try:
|
||||
return list_registrations(db, event_id, reveal=False)
|
||||
except LookupError as exc:
|
||||
_bad(exc)
|
||||
|
||||
|
||||
@router.post("/membership/events/{event_id}/registrations")
|
||||
def add_registration(event_id: int, body: RegistrationWrite, db: Session = Depends(get_db)) -> dict:
|
||||
try:
|
||||
return create_registration(
|
||||
db,
|
||||
event_id,
|
||||
body.model_dump(),
|
||||
site_member_id=None,
|
||||
enforce_quota=False,
|
||||
published_only=False,
|
||||
)
|
||||
except (ValueError, LookupError) as exc:
|
||||
_bad(exc)
|
||||
|
||||
|
||||
@router.get("/membership/registrations/{registration_id}")
|
||||
def get_registration(registration_id: int, db: Session = Depends(get_db)) -> dict:
|
||||
try:
|
||||
return read_registration(db, registration_id)
|
||||
except LookupError as exc:
|
||||
_bad(exc)
|
||||
|
||||
|
||||
@router.put("/membership/registrations/{registration_id}")
|
||||
def edit_registration(registration_id: int, body: RegistrationWrite, db: Session = Depends(get_db)) -> dict:
|
||||
try:
|
||||
return update_registration(db, registration_id, body.model_dump())
|
||||
except (ValueError, LookupError) as exc:
|
||||
_bad(exc)
|
||||
|
||||
|
||||
@router.delete("/membership/registrations/{registration_id}")
|
||||
def remove_registration(registration_id: int, db: Session = Depends(get_db)) -> dict:
|
||||
try:
|
||||
delete_registration(db, registration_id)
|
||||
except LookupError as exc:
|
||||
_bad(exc)
|
||||
return {"ok": True}
|
||||
@@ -113,7 +113,7 @@ def issue_agent_session(actor_id: int = Depends(_actor_id), db: Session = Depend
|
||||
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")
|
||||
token = create_access_token(f"s:{user.id}", "agent", version=int(user.credential_epoch or 0))
|
||||
return {
|
||||
"accessToken": token,
|
||||
"tokenType": "agent",
|
||||
|
||||
@@ -12,7 +12,7 @@ from app.models.agent_user import (
|
||||
)
|
||||
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.models.rbac import AdminUser, bump_admin_credentials
|
||||
from app.services.email_code import is_valid_email, normalize_email
|
||||
from app.services.password import hash_password, validate_password
|
||||
|
||||
@@ -144,6 +144,7 @@ def _write_builtin(member_key: str, body: SiteMemberUpdate, db: Session) -> dict
|
||||
if password:
|
||||
validate_password(password)
|
||||
admin.password_hash = hash_password(password)
|
||||
bump_admin_credentials(admin)
|
||||
admin.display_name = display_name
|
||||
admin.status = status_value
|
||||
admin.updated_at = datetime.now(timezone.utc)
|
||||
|
||||
@@ -3,6 +3,7 @@ from fastapi import APIRouter
|
||||
from app.api.admin.about import router as admin_about_router
|
||||
from app.api.admin.discipline import router as admin_discipline_router
|
||||
from app.api.admin.edu import router as admin_edu_router
|
||||
from app.api.admin.membership import router as admin_membership_router
|
||||
from app.api.admin.content import router as content_router
|
||||
from app.api.admin.expert import router as admin_expert_router
|
||||
from app.api.admin.uploaded_cases import router as admin_uploaded_cases_router
|
||||
@@ -19,6 +20,7 @@ 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
|
||||
from app.api.site.membership import router as site_membership_router
|
||||
from app.api.site.auth import router as site_auth_router
|
||||
from app.api.site.legal import router as site_legal_router
|
||||
from app.api.site.member import router as member_router
|
||||
@@ -26,6 +28,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.template_coach import router as site_template_coach_router
|
||||
from app.api.site.valuation import router as site_valuation_router
|
||||
|
||||
api_router = APIRouter()
|
||||
@@ -36,10 +39,12 @@ api_router.include_router(site_reports_router, prefix="/api/site")
|
||||
api_router.include_router(site_about_router, prefix="/api/site")
|
||||
api_router.include_router(site_discipline_router, prefix="/api/site")
|
||||
api_router.include_router(site_edu_router, prefix="/api/site")
|
||||
api_router.include_router(site_membership_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(site_template_coach_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")
|
||||
@@ -50,6 +55,7 @@ api_router.include_router(admin_reports_router, prefix="/api/admin")
|
||||
api_router.include_router(admin_about_router, prefix="/api/admin")
|
||||
api_router.include_router(admin_discipline_router, prefix="/api/admin")
|
||||
api_router.include_router(admin_edu_router, prefix="/api/admin")
|
||||
api_router.include_router(admin_membership_router, prefix="/api/admin")
|
||||
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")
|
||||
|
||||
@@ -7,7 +7,7 @@ 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.agent_user import find_login_account, load_agent_actor, presented_credential_version
|
||||
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 (
|
||||
@@ -143,7 +143,7 @@ def agent_login(body: AgentLoginRequest, db: Session = Depends(get_db)) -> dict:
|
||||
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")
|
||||
token = create_access_token(subject, "agent", version=int(getattr(user, "credential_epoch", 0) or 0))
|
||||
return {
|
||||
"accessToken": token,
|
||||
"tokenType": "agent",
|
||||
@@ -155,7 +155,11 @@ def agent_login(body: AgentLoginRequest, db: Session = Depends(get_db)) -> dict:
|
||||
@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 ""))
|
||||
actor = load_agent_actor(
|
||||
db,
|
||||
str(principal.get("sub") or ""),
|
||||
credential_version=presented_credential_version(principal),
|
||||
)
|
||||
except LookupError as exc:
|
||||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="登录已失效") from exc
|
||||
return {
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from pydantic import BaseModel, Field
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.core.deps import require_member
|
||||
from app.db import get_db
|
||||
from app.models.member import get_member_by_id
|
||||
from app.models.membership import (
|
||||
create_registration,
|
||||
list_events,
|
||||
member_registrations,
|
||||
profile_for_member,
|
||||
public_org_links,
|
||||
read_event,
|
||||
)
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
class RegistrationWrite(BaseModel):
|
||||
region: str = ""
|
||||
orgName: str = ""
|
||||
personName: str = ""
|
||||
gender: str = ""
|
||||
position: str = ""
|
||||
idCard: str = ""
|
||||
mobile: str = ""
|
||||
appraiserRegNo: str = ""
|
||||
email: str = ""
|
||||
lodging: str = "self"
|
||||
roomStandard: bool = False
|
||||
roomSingle: bool = False
|
||||
standardCount: int = 0
|
||||
singleCount: int = 0
|
||||
dine: bool = False
|
||||
mealDates: list[str] = Field(default_factory=list)
|
||||
|
||||
|
||||
def _member_id(principal: dict) -> int:
|
||||
try:
|
||||
return int(principal["sub"])
|
||||
except (TypeError, ValueError, KeyError) as exc:
|
||||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="登录已失效") from exc
|
||||
|
||||
|
||||
def _active_member(db: Session, principal: dict):
|
||||
member = get_member_by_id(db, _member_id(principal))
|
||||
if member is None or member.status != "active":
|
||||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="登录已失效")
|
||||
return member
|
||||
|
||||
|
||||
@router.get("/membership/orgs")
|
||||
def read_orgs(db: Session = Depends(get_db)) -> dict:
|
||||
return public_org_links(db)
|
||||
|
||||
|
||||
@router.get("/membership/profile")
|
||||
def read_own_profile(
|
||||
principal: dict = Depends(require_member),
|
||||
db: Session = Depends(get_db),
|
||||
) -> dict:
|
||||
member = _active_member(db, principal)
|
||||
return {"profile": profile_for_member(db, member.id)}
|
||||
|
||||
|
||||
@router.get("/membership/events")
|
||||
def read_events(db: Session = Depends(get_db)) -> dict:
|
||||
return list_events(db, published_only=True)
|
||||
|
||||
|
||||
@router.get("/membership/events/{event_id}")
|
||||
def read_one_event(event_id: int, db: Session = Depends(get_db)) -> dict:
|
||||
try:
|
||||
return read_event(db, event_id, published_only=True)
|
||||
except LookupError as exc:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)) from exc
|
||||
|
||||
|
||||
@router.post("/membership/events/{event_id}/registrations")
|
||||
def submit_registration(
|
||||
event_id: int,
|
||||
body: RegistrationWrite,
|
||||
principal: dict = Depends(require_member),
|
||||
db: Session = Depends(get_db),
|
||||
) -> dict:
|
||||
member = _active_member(db, principal)
|
||||
try:
|
||||
return create_registration(
|
||||
db,
|
||||
event_id,
|
||||
body.model_dump(),
|
||||
site_member_id=member.id,
|
||||
enforce_quota=True,
|
||||
published_only=True,
|
||||
)
|
||||
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.get("/membership/registrations")
|
||||
def read_own_registrations(
|
||||
principal: dict = Depends(require_member),
|
||||
db: Session = Depends(get_db),
|
||||
) -> dict:
|
||||
member = _active_member(db, principal)
|
||||
return member_registrations(db, member.id)
|
||||
@@ -0,0 +1,500 @@
|
||||
"""估价模版智能体。只为智能体管理员准备可下载的模版,不写入模版列表。"""
|
||||
|
||||
import json
|
||||
from urllib.parse import quote
|
||||
|
||||
from fastapi import APIRouter, Depends, File, HTTPException, UploadFile, status
|
||||
from fastapi.responses import Response, StreamingResponse
|
||||
from pydantic import BaseModel, Field
|
||||
from sqlalchemy import delete, select
|
||||
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, presented_credential_version
|
||||
from app.models.content import read_upload_limit
|
||||
from app.models.valuation import COACH_WELCOME, ValuationCoachMessage, ValuationCoachSession, ValuationFile, _now
|
||||
from app.services.dify_chat import DifyChatError, DifyNotConfigured, iter_dify_chat, upload_dify_file
|
||||
from app.services.storage import make_object_key, read_object, safe_filename, upload_object
|
||||
from app.services.template_coach import (
|
||||
Outline,
|
||||
build_template_file,
|
||||
finish_model_answer,
|
||||
parse_outline_block,
|
||||
plan_turn,
|
||||
summary,
|
||||
)
|
||||
from app.services.valuation import owned_files
|
||||
from app.services.valuation_context import ALLOWED_EXTENSIONS, IMAGE_EXTENSIONS, MAX_FILES, extract_excerpt, file_kind
|
||||
|
||||
router = APIRouter(dependencies=[Depends(require_agent)])
|
||||
|
||||
COACH_EXTENSIONS = ALLOWED_EXTENSIONS | {"pptx"}
|
||||
_CONTENT_TYPES = {
|
||||
"docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
||||
"pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation",
|
||||
"pdf": "application/pdf",
|
||||
"txt": "text/plain",
|
||||
"md": "text/markdown",
|
||||
"xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
"xls": "application/vnd.ms-excel",
|
||||
"csv": "text/csv",
|
||||
"jpg": "image/jpeg",
|
||||
"jpeg": "image/jpeg",
|
||||
"png": "image/png",
|
||||
"webp": "image/webp",
|
||||
}
|
||||
|
||||
|
||||
class CoachMessageIn(BaseModel):
|
||||
query: str = Field(default="", max_length=2000)
|
||||
fileIds: list[int] = Field(default_factory=list, max_length=MAX_FILES)
|
||||
sessionId: int | None = None
|
||||
|
||||
|
||||
class SessionRename(BaseModel):
|
||||
title: str = Field(min_length=1, max_length=40)
|
||||
|
||||
|
||||
def _actor(db: Session, principal: dict) -> AgentActor:
|
||||
try:
|
||||
return load_agent_actor(
|
||||
db,
|
||||
str(principal.get("sub") or ""),
|
||||
credential_version=presented_credential_version(principal),
|
||||
)
|
||||
except LookupError as exc:
|
||||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="登录已失效") from exc
|
||||
|
||||
|
||||
def _require_manager(db: Session, principal: dict) -> AgentActor:
|
||||
actor = _actor(db, principal)
|
||||
if not actor.can_manage:
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="仅管理员可制作模版")
|
||||
return actor
|
||||
|
||||
|
||||
def _sse(payload: dict) -> str:
|
||||
return f"data: {json.dumps(payload, ensure_ascii=False)}\n\n"
|
||||
|
||||
|
||||
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)
|
||||
|
||||
|
||||
def _session_rows(db: Session, owner: str) -> list[ValuationCoachSession]:
|
||||
return list(
|
||||
db.scalars(
|
||||
select(ValuationCoachSession)
|
||||
.where(ValuationCoachSession.owner_key == owner)
|
||||
.order_by(ValuationCoachSession.updated_at.desc(), ValuationCoachSession.id.desc())
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def _remember_title(db: Session, row: ValuationCoachSession) -> str:
|
||||
title = (row.title or "").strip() or "新会话"
|
||||
if title != "新会话":
|
||||
return title
|
||||
first = db.scalar(
|
||||
select(ValuationCoachMessage.content)
|
||||
.where(ValuationCoachMessage.session_id == row.id, ValuationCoachMessage.role == "user")
|
||||
.order_by(ValuationCoachMessage.created_at, ValuationCoachMessage.id)
|
||||
.limit(1)
|
||||
)
|
||||
text = (first or "").strip()
|
||||
if not text:
|
||||
row.title = "新会话"
|
||||
return row.title
|
||||
row.title = text[:22]
|
||||
return row.title
|
||||
|
||||
|
||||
def _session_payload(db: Session, row: ValuationCoachSession) -> dict:
|
||||
return {
|
||||
"id": row.id,
|
||||
"title": _remember_title(db, row),
|
||||
"updatedAt": row.updated_at.isoformat(timespec="seconds"),
|
||||
}
|
||||
|
||||
|
||||
def _create_session(db: Session, owner: str) -> ValuationCoachSession:
|
||||
now = _now()
|
||||
row = ValuationCoachSession(owner_key=owner, title="新会话", created_at=now, updated_at=now)
|
||||
db.add(row)
|
||||
db.flush()
|
||||
db.add(
|
||||
ValuationCoachMessage(
|
||||
session_id=row.id,
|
||||
role="assistant",
|
||||
content=COACH_WELCOME,
|
||||
thought="",
|
||||
attachments="[]",
|
||||
kind="chat",
|
||||
created_at=now,
|
||||
)
|
||||
)
|
||||
db.commit()
|
||||
db.refresh(row)
|
||||
return row
|
||||
|
||||
|
||||
def _session(db: Session, owner: str) -> ValuationCoachSession:
|
||||
rows = _session_rows(db, owner)
|
||||
if rows:
|
||||
return rows[0]
|
||||
return _create_session(db, owner)
|
||||
|
||||
|
||||
def _owned_session(db: Session, owner: str, session_id: int) -> ValuationCoachSession | None:
|
||||
row = db.get(ValuationCoachSession, session_id)
|
||||
if row is None or row.owner_key != owner:
|
||||
return None
|
||||
return row
|
||||
|
||||
|
||||
def _messages(db: Session, session_id: int) -> list[dict]:
|
||||
rows = db.scalars(
|
||||
select(ValuationCoachMessage)
|
||||
.where(ValuationCoachMessage.session_id == session_id)
|
||||
.order_by(ValuationCoachMessage.created_at, ValuationCoachMessage.id)
|
||||
)
|
||||
return [_message_payload(row) for row in rows]
|
||||
|
||||
|
||||
def _message_payload(row: ValuationCoachMessage) -> dict:
|
||||
try:
|
||||
attachments = json.loads(row.attachments or "[]")
|
||||
except json.JSONDecodeError:
|
||||
attachments = []
|
||||
if not isinstance(attachments, list):
|
||||
attachments = []
|
||||
return {
|
||||
"id": row.id,
|
||||
"role": row.role,
|
||||
"content": row.content or "",
|
||||
"thought": row.thought or "",
|
||||
"attachments": [str(item) for item in attachments if str(item).strip()],
|
||||
"kind": row.kind or "chat",
|
||||
"draftFormat": row.draft_format if row.kind == "template" else "",
|
||||
"draftName": (row.draft_name or "").strip() if row.kind == "template" else "",
|
||||
"createdAt": row.created_at.isoformat(timespec="seconds"),
|
||||
}
|
||||
|
||||
|
||||
def _stored_outline(session: ValuationCoachSession) -> Outline | None:
|
||||
if not (session.outline_text or "").strip():
|
||||
return None
|
||||
parsed = parse_outline_block(session.outline_text)
|
||||
if parsed is None or not parsed.sections:
|
||||
return None
|
||||
return parsed
|
||||
|
||||
|
||||
def _remember(session: ValuationCoachSession, outline: Outline | None, source_text: str) -> None:
|
||||
session.source_text = source_text or ""
|
||||
if outline is not None and not outline.sections:
|
||||
session.outline_name = ""
|
||||
session.outline_format = ""
|
||||
session.outline_text = ""
|
||||
elif outline and outline.sections:
|
||||
session.outline_name = outline.name[:80]
|
||||
session.outline_format = outline.format
|
||||
session.outline_text = outline.render()
|
||||
session.updated_at = _now()
|
||||
|
||||
|
||||
def _coach_state(db: Session, owner: str, session: ValuationCoachSession) -> dict:
|
||||
rows = _session_rows(db, owner)
|
||||
payloads = [_session_payload(db, row) for row in rows]
|
||||
db.commit()
|
||||
return {"sessionId": session.id, "sessions": payloads, "items": _messages(db, session.id)}
|
||||
|
||||
|
||||
@router.get("/template-coach")
|
||||
def open_coach(principal: dict = Depends(require_agent), db: Session = Depends(get_db)) -> dict:
|
||||
actor = _require_manager(db, principal)
|
||||
session = _session(db, actor.key)
|
||||
return _coach_state(db, actor.key, session)
|
||||
|
||||
|
||||
@router.post("/template-coach/sessions", status_code=status.HTTP_201_CREATED)
|
||||
def new_coach_session(principal: dict = Depends(require_agent), db: Session = Depends(get_db)) -> dict:
|
||||
actor = _require_manager(db, principal)
|
||||
session = _create_session(db, actor.key)
|
||||
return _coach_state(db, actor.key, session)
|
||||
|
||||
|
||||
@router.get("/template-coach/sessions/{session_id}")
|
||||
def open_coach_session(
|
||||
session_id: int,
|
||||
principal: dict = Depends(require_agent),
|
||||
db: Session = Depends(get_db),
|
||||
) -> dict:
|
||||
actor = _require_manager(db, principal)
|
||||
session = _owned_session(db, actor.key, session_id)
|
||||
if session is None:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="会话不存在")
|
||||
return _coach_state(db, actor.key, session)
|
||||
|
||||
|
||||
@router.patch("/template-coach/sessions/{session_id}")
|
||||
def rename_coach_session(
|
||||
session_id: int,
|
||||
body: SessionRename,
|
||||
principal: dict = Depends(require_agent),
|
||||
db: Session = Depends(get_db),
|
||||
) -> dict:
|
||||
actor = _require_manager(db, principal)
|
||||
session = _owned_session(db, actor.key, session_id)
|
||||
if session is None:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="会话不存在")
|
||||
title = body.title.strip()[:40]
|
||||
if not title:
|
||||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="请填写会话名称")
|
||||
session.title = title
|
||||
session.updated_at = _now()
|
||||
db.commit()
|
||||
db.refresh(session)
|
||||
return _session_payload(db, session)
|
||||
|
||||
|
||||
@router.delete("/template-coach/sessions/{session_id}", status_code=status.HTTP_204_NO_CONTENT)
|
||||
def remove_coach_session(
|
||||
session_id: int,
|
||||
principal: dict = Depends(require_agent),
|
||||
db: Session = Depends(get_db),
|
||||
) -> None:
|
||||
actor = _require_manager(db, principal)
|
||||
session = _owned_session(db, actor.key, session_id)
|
||||
if session is None:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="会话不存在")
|
||||
db.execute(delete(ValuationCoachMessage).where(ValuationCoachMessage.session_id == session.id))
|
||||
db.delete(session)
|
||||
db.commit()
|
||||
|
||||
|
||||
@router.post("/template-coach/reset")
|
||||
def reset_coach(principal: dict = Depends(require_agent), db: Session = Depends(get_db)) -> dict:
|
||||
"""保留旧会话,另开一段新的。"""
|
||||
actor = _require_manager(db, principal)
|
||||
session = _create_session(db, actor.key)
|
||||
return _coach_state(db, actor.key, session)
|
||||
|
||||
|
||||
@router.post("/template-coach/files", status_code=status.HTTP_201_CREATED)
|
||||
def upload_coach_file(
|
||||
file: UploadFile = File(...),
|
||||
principal: dict = Depends(require_agent),
|
||||
db: Session = Depends(get_db),
|
||||
) -> dict:
|
||||
actor = _require_manager(db, principal)
|
||||
filename = safe_filename(file.filename or "")
|
||||
extension = filename.rsplit(".", 1)[-1].lower() if "." in filename else ""
|
||||
if extension in {"doc", "ppt"}:
|
||||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="请另存为 docx 或 pptx 后再上传")
|
||||
if extension not in COACH_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 = _CONTENT_TYPES.get(extension, "application/octet-stream")
|
||||
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("/template-coach/messages")
|
||||
def coach_message(
|
||||
body: CoachMessageIn,
|
||||
principal: dict = Depends(require_agent),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
actor = _require_manager(db, principal)
|
||||
if body.sessionId:
|
||||
session = _owned_session(db, actor.key, body.sessionId)
|
||||
if session is None:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="会话不存在")
|
||||
else:
|
||||
session = _session(db, actor.key)
|
||||
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="请输入要求或上传附件")
|
||||
excerpts: list[tuple[str, str, str]] = []
|
||||
for item in files:
|
||||
try:
|
||||
content = read_object("private", item.object_key)
|
||||
except Exception as exc:
|
||||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="附件读取失败") from exc
|
||||
excerpts.append((item.filename, item.extension, extract_excerpt(item.extension, content, limit=8000)))
|
||||
plan = plan_turn(
|
||||
message=query,
|
||||
outline=_stored_outline(session),
|
||||
source_text=session.source_text or "",
|
||||
excerpts=excerpts,
|
||||
)
|
||||
file_names = [item.filename for item in files]
|
||||
now = _now()
|
||||
title_source = query or (file_names[0] if file_names else "")
|
||||
if (session.title or "新会话") == "新会话" and title_source:
|
||||
session.title = title_source[:22]
|
||||
session.updated_at = now
|
||||
db.add(
|
||||
ValuationCoachMessage(
|
||||
session_id=session.id,
|
||||
role="user",
|
||||
content=query or "请结合附件整理模版。",
|
||||
thought="",
|
||||
attachments=json.dumps(file_names, ensure_ascii=False),
|
||||
kind="chat",
|
||||
created_at=now,
|
||||
)
|
||||
)
|
||||
db.commit()
|
||||
owner = actor.key
|
||||
session_id = session.id
|
||||
user_key = owner
|
||||
|
||||
def generate():
|
||||
reply = plan.reply
|
||||
outline = plan.outline
|
||||
thought = ""
|
||||
if plan.mode == "local":
|
||||
if reply:
|
||||
yield _sse({"type": "delta", "text": reply})
|
||||
else:
|
||||
reply, outline, thought = yield from _stream_model(plan, files, user_key)
|
||||
saved = _save_assistant(db, owner, session_id, plan.source_text, reply, outline, thought)
|
||||
if saved is None:
|
||||
yield _sse({"type": "error", "message": "提纲已整理,但没能保存,请稍后重试"})
|
||||
return
|
||||
yield _sse(
|
||||
{
|
||||
"type": "saved",
|
||||
"messageId": saved.id,
|
||||
"kind": saved.kind,
|
||||
"draftFormat": saved.draft_format if saved.kind == "template" else "",
|
||||
"draftName": saved.draft_name if saved.kind == "template" else "",
|
||||
}
|
||||
)
|
||||
|
||||
return StreamingResponse(generate(), media_type="text/event-stream")
|
||||
|
||||
|
||||
def _stream_model(plan, files: list[ValuationFile], user_key: str):
|
||||
dify_files = []
|
||||
raw: list[str] = []
|
||||
thought = ""
|
||||
try:
|
||||
for item in files:
|
||||
if item.extension not in IMAGE_EXTENSIONS and item.extension not in {"pdf", "docx", "pptx", "txt", "md"}:
|
||||
continue
|
||||
content = read_object("private", item.object_key)
|
||||
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,
|
||||
}
|
||||
)
|
||||
for event in iter_dify_chat(query=plan.prompt, conversation_id="", user=user_key, files=dify_files or None):
|
||||
if event["type"] == "delta":
|
||||
raw.append(event["text"])
|
||||
elif event["type"] == "replace":
|
||||
raw = [event["text"]]
|
||||
elif event["type"] == "thought" and event.get("text"):
|
||||
thought = event["text"]
|
||||
yield _sse({"type": "thought", "text": thought})
|
||||
except (DifyNotConfigured, DifyChatError):
|
||||
if plan.fallback and plan.fallback.sections:
|
||||
reply = summary(plan.fallback, lead="暂时连不上估价智能体,我按已有材料")
|
||||
yield _sse({"type": "replace", "text": reply})
|
||||
return reply, plan.fallback, thought
|
||||
reply = "暂时连不上估价智能体,没能整理出新提纲。可以换个说法,或上传 docx、pptx 后重试。"
|
||||
yield _sse({"type": "replace", "text": reply})
|
||||
return reply, None, thought
|
||||
reply, outline = finish_model_answer("".join(raw), fallback=plan.fallback)
|
||||
if reply:
|
||||
yield _sse({"type": "delta", "text": reply})
|
||||
return reply, outline if outline and outline.sections else None, thought
|
||||
|
||||
|
||||
def _save_assistant(db, owner: str, session_id: int, source_text: str, reply: str, outline: Outline | None, thought: str):
|
||||
session = _owned_session(db, owner, session_id)
|
||||
if session is None:
|
||||
return None
|
||||
try:
|
||||
_remember(session, outline, source_text)
|
||||
ready = outline is not None and bool(outline.sections)
|
||||
row = ValuationCoachMessage(
|
||||
session_id=session.id,
|
||||
role="assistant",
|
||||
content=reply or "没能整理出模版提纲。",
|
||||
thought=thought or "",
|
||||
attachments="[]",
|
||||
kind="template" if ready else "chat",
|
||||
draft_format=outline.format if ready else "",
|
||||
draft_name=outline.name[:80] if ready else "",
|
||||
outline=outline.render() if ready else "",
|
||||
created_at=_now(),
|
||||
)
|
||||
db.add(row)
|
||||
db.commit()
|
||||
db.refresh(row)
|
||||
return row
|
||||
except Exception:
|
||||
db.rollback()
|
||||
return None
|
||||
|
||||
|
||||
@router.get("/template-coach/messages/{message_id}/file")
|
||||
def download_coach_template(
|
||||
message_id: int,
|
||||
principal: dict = Depends(require_agent),
|
||||
db: Session = Depends(get_db),
|
||||
) -> Response:
|
||||
actor = _require_manager(db, principal)
|
||||
row = db.get(ValuationCoachMessage, message_id)
|
||||
session = _owned_session(db, actor.key, row.session_id) if row is not None else None
|
||||
if row is None or session is None or row.role != "assistant" or row.kind != "template":
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="模版文件不存在")
|
||||
outline = parse_outline_block(row.outline or "")
|
||||
if outline is None or not outline.sections:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="模版文件不存在")
|
||||
content, media_type, filename = build_template_file(outline)
|
||||
return Response(
|
||||
content=content,
|
||||
media_type=media_type,
|
||||
headers={"Content-Disposition": f"attachment; filename*=UTF-8''{quote(filename)}"},
|
||||
)
|
||||
@@ -9,7 +9,7 @@ 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.agent_user import AgentActor, load_agent_actor, presented_credential_version
|
||||
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
|
||||
@@ -84,7 +84,11 @@ class SuggestionWrite(BaseModel):
|
||||
|
||||
def _actor(db: Session, principal: dict) -> AgentActor:
|
||||
try:
|
||||
return load_agent_actor(db, str(principal.get("sub") or ""))
|
||||
return load_agent_actor(
|
||||
db,
|
||||
str(principal.get("sub") or ""),
|
||||
credential_version=presented_credential_version(principal),
|
||||
)
|
||||
except LookupError as exc:
|
||||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="登录已失效") from exc
|
||||
|
||||
|
||||
@@ -965,6 +965,48 @@ def ensure_edu_menu(db: Session) -> None:
|
||||
db.flush()
|
||||
|
||||
|
||||
def ensure_membership_menu(db: Session) -> None:
|
||||
menu = _ensure_resource(
|
||||
db,
|
||||
parent_id=None,
|
||||
resource_type="menu",
|
||||
name="MemberService",
|
||||
title="会员服务",
|
||||
path="/member",
|
||||
component="/member",
|
||||
icon="ri:vip-crown-line",
|
||||
permission="",
|
||||
sort=5,
|
||||
visible=True,
|
||||
)
|
||||
button = _ensure_resource(
|
||||
db,
|
||||
parent_id=menu.id,
|
||||
resource_type="button",
|
||||
name="membership:edit",
|
||||
title="保存",
|
||||
path="",
|
||||
component="",
|
||||
icon="",
|
||||
permission="membership:edit",
|
||||
sort=1,
|
||||
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):
|
||||
if resource_id not in linked:
|
||||
db.add(AdminRoleResource(role_id=role.id, resource_id=resource_id))
|
||||
db.flush()
|
||||
|
||||
|
||||
def ensure_tech_menu(db: Session) -> None:
|
||||
tech = _ensure_resource(
|
||||
db,
|
||||
@@ -1223,6 +1265,9 @@ def seed_superuser(db: Session, username: str, password: str) -> None:
|
||||
db.flush()
|
||||
else:
|
||||
user.password_hash = password_hash
|
||||
from app.models.rbac import bump_admin_credentials
|
||||
|
||||
bump_admin_credentials(user)
|
||||
user.status = "active"
|
||||
user.failed_login_count = 0
|
||||
user.locked_until = None
|
||||
@@ -1271,6 +1316,9 @@ def main() -> int:
|
||||
db = SessionLocal()
|
||||
ensure_site_defaults(db)
|
||||
seed_ip_blacklist(db)
|
||||
from app.models.rbac import ensure_admin_credential_column
|
||||
|
||||
ensure_admin_credential_column(db)
|
||||
seed_superuser(db, username, password)
|
||||
db.commit()
|
||||
except RuntimeError as exc:
|
||||
|
||||
@@ -353,8 +353,7 @@ def seed() -> None:
|
||||
db,
|
||||
[
|
||||
{"key": "reportQuery", "label": "报告查询", "url": "/reports/query", "visible": True, "sortOrder": 0},
|
||||
{"key": "reportReview", "label": "报告审核", "url": "/reports/review", "visible": True, "sortOrder": 1},
|
||||
{"key": "complaint", "label": "投诉举报", "url": "/discipline", "visible": True, "sortOrder": 2},
|
||||
{"key": "complaint", "label": "投诉举报", "url": "/discipline", "visible": True, "sortOrder": 1},
|
||||
],
|
||||
)
|
||||
save_menu(
|
||||
|
||||
@@ -0,0 +1,297 @@
|
||||
"""写入会员服务演示数据,供本地查看。
|
||||
|
||||
同名外链、同标题资讯、同名会议和同一登录邮箱已存在则跳过。
|
||||
演示账号口令写在本命令里,只用于本地库,不是生产口令。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import struct
|
||||
import zlib
|
||||
from html import escape
|
||||
|
||||
from sqlalchemy import func, select
|
||||
|
||||
from app.db import Base, SessionLocal, get_engine
|
||||
from app.models.content import AdminFile
|
||||
from app.models.home import HomeArticle, create_article
|
||||
from app.models.member import SiteMember
|
||||
from app.models.membership import (
|
||||
AssociationProfile,
|
||||
MemberOrgLink,
|
||||
TrainingEvent,
|
||||
TrainingRegistration,
|
||||
create_profile,
|
||||
create_registration,
|
||||
save_org_links,
|
||||
)
|
||||
from app.services.password import hash_password
|
||||
from app.services.storage import ensure_buckets, make_object_key, upload_object
|
||||
|
||||
DEMO_PASSWORD = "Member123"
|
||||
INDIVIDUAL_EMAIL = "member.zhang@example.com"
|
||||
ORGANIZATION_EMAIL = "member.org@example.com"
|
||||
|
||||
|
||||
def _png(width: int, height: int, rgb: tuple[int, int, int]) -> bytes:
|
||||
def chunk(tag: bytes, data: bytes) -> bytes:
|
||||
return struct.pack(">I", len(data)) + tag + data + struct.pack(">I", zlib.crc32(tag + data) & 0xFFFFFFFF)
|
||||
|
||||
raw = b"".join(b"\x00" + bytes(rgb) * width for _ in range(height))
|
||||
return (
|
||||
b"\x89PNG\r\n\x1a\n"
|
||||
+ chunk(b"IHDR", struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0))
|
||||
+ chunk(b"IDAT", zlib.compress(raw))
|
||||
+ chunk(b"IEND", b"")
|
||||
)
|
||||
|
||||
|
||||
def _store_png(db, filename: str, rgb: tuple[int, int, int]) -> AdminFile:
|
||||
row = db.scalar(select(AdminFile).where(AdminFile.bucket == "public", AdminFile.filename == filename))
|
||||
if row is not None:
|
||||
return row
|
||||
data = _png(640, 360, rgb)
|
||||
key = make_object_key(filename)
|
||||
upload_object("public", key, data, "image/png")
|
||||
row = AdminFile(
|
||||
bucket="public",
|
||||
object_key=key,
|
||||
filename=filename,
|
||||
content_type="image/png",
|
||||
size=len(data),
|
||||
created_by=None,
|
||||
)
|
||||
db.add(row)
|
||||
db.commit()
|
||||
db.refresh(row)
|
||||
return row
|
||||
|
||||
|
||||
def _paragraphs(lines: list[str]) -> str:
|
||||
return "".join(f"<p>{escape(line)}</p>" for line in lines)
|
||||
|
||||
|
||||
def _seed_orgs(db) -> int:
|
||||
if db.scalar(select(func.count()).select_from(MemberOrgLink)) :
|
||||
return 0
|
||||
cards = [
|
||||
("中国房地产估价师与房地产经纪人学会", "https://www.cirea.org.cn/", "member-org-cirea.png", (12, 74, 150)),
|
||||
("甘肃省住房和城乡建设厅", "http://zjt.gansu.gov.cn/", "member-org-gansu-zjt.png", (14, 116, 144)),
|
||||
("住房和城乡建设部", "https://www.mohurd.gov.cn/", "member-org-mohurd.png", (22, 101, 52)),
|
||||
]
|
||||
items = []
|
||||
for index, (name, url, filename, color) in enumerate(cards, start=1):
|
||||
image = _store_png(db, filename, color)
|
||||
items.append({"name": name, "url": url, "imageFileId": image.id, "sortOrder": index})
|
||||
save_org_links(db, items)
|
||||
return len(items)
|
||||
|
||||
|
||||
def _seed_notices(db) -> int:
|
||||
samples = [
|
||||
(
|
||||
"协会章程(演示)",
|
||||
"2026-01-15T08:00:00",
|
||||
["本条为本地演示数据,正式文本以协会发布的章程为准。", "章程说明协会宗旨、会员权利与义务、组织机构和议事规则。"],
|
||||
),
|
||||
(
|
||||
"单位会员管理办法(演示)",
|
||||
"2026-02-10T08:00:00",
|
||||
["本条为本地演示数据。", "单位会员的入会、变更、年检和退会,按本办法办理。", "咨询电话:0931-8126195。"],
|
||||
),
|
||||
(
|
||||
"会费管理办法(演示)",
|
||||
"2026-02-20T08:00:00",
|
||||
["本条为本地演示数据。", "会费标准、缴纳时间和减免情形以最新办法为准。"],
|
||||
),
|
||||
]
|
||||
added = 0
|
||||
for title, published_at, lines in samples:
|
||||
exists = db.scalar(
|
||||
select(HomeArticle.id).where(HomeArticle.category == "member_notices", HomeArticle.title == title)
|
||||
)
|
||||
if exists is not None:
|
||||
continue
|
||||
create_article(
|
||||
db,
|
||||
{
|
||||
"category": "member_notices",
|
||||
"title": title,
|
||||
"publishedAt": published_at,
|
||||
"published": True,
|
||||
"bodyHtml": _paragraphs(lines),
|
||||
"attachmentFileIds": [],
|
||||
},
|
||||
)
|
||||
added += 1
|
||||
return added
|
||||
|
||||
|
||||
def _ensure_profile(db, payload: dict) -> None:
|
||||
email = payload["email"]
|
||||
account = db.scalar(select(SiteMember).where(SiteMember.email == email))
|
||||
if account is not None and db.scalar(
|
||||
select(AssociationProfile.id).where(AssociationProfile.site_member_id == account.id)
|
||||
):
|
||||
return
|
||||
create_profile(db, payload, hash_password(DEMO_PASSWORD))
|
||||
|
||||
|
||||
def _seed_profiles(db) -> None:
|
||||
_ensure_profile(
|
||||
db,
|
||||
{
|
||||
"email": INDIVIDUAL_EMAIL,
|
||||
"kind": "individual",
|
||||
"memberNo": "GS-P-2026-001",
|
||||
"membershipStatus": "active",
|
||||
"joinedOn": "2024-03-01",
|
||||
"expiresOn": "2027-03-01",
|
||||
"feeStatus": "paid",
|
||||
"mobile": "13800001111",
|
||||
"region": "甘肃省兰州市城关区",
|
||||
"address": "张掖路63号",
|
||||
"postalCode": "730030",
|
||||
"personName": "张伟",
|
||||
"gender": "male",
|
||||
"birthDate": "1988-05-16",
|
||||
"idCard": "620102198805161234",
|
||||
"education": "本科",
|
||||
"major": "工程管理",
|
||||
"jobTitle": "房地产估价师",
|
||||
"practiceYears": 12,
|
||||
"employer": "兰州示例房地产估价有限公司",
|
||||
"position": "估价师",
|
||||
"appraiserRegNo": "6201028812",
|
||||
"qualificationNo": "GS20140088",
|
||||
"regValidUntil": "2028-06-30",
|
||||
"remark": "本地演示个人会员",
|
||||
},
|
||||
)
|
||||
_ensure_profile(
|
||||
db,
|
||||
{
|
||||
"email": ORGANIZATION_EMAIL,
|
||||
"kind": "organization",
|
||||
"memberNo": "GS-O-2026-018",
|
||||
"membershipStatus": "active",
|
||||
"joinedOn": "2019-06-18",
|
||||
"expiresOn": "2026-12-31",
|
||||
"feeStatus": "unpaid",
|
||||
"mobile": "13900002222",
|
||||
"region": "甘肃省兰州市七里河区",
|
||||
"address": "西津西路100号",
|
||||
"postalCode": "730050",
|
||||
"orgName": "兰州示例房地产估价有限公司",
|
||||
"creditCode": "91620100MA1234567X",
|
||||
"qualificationLevel": "二级",
|
||||
"filingNo": "甘估备20190018",
|
||||
"legalPerson": "赵敏",
|
||||
"officeAddress": "兰州市七里河区西津西路100号",
|
||||
"contactName": "赵敏",
|
||||
"contactPosition": "总经理",
|
||||
"contactMobile": "13900002222",
|
||||
"contactEmail": ORGANIZATION_EMAIL,
|
||||
"remark": "本地演示机构会员",
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def _seed_training(db) -> str:
|
||||
title = "2026年房地产估价业务培训会(演示)"
|
||||
event = db.scalar(select(TrainingEvent).where(TrainingEvent.title == title))
|
||||
if event is None:
|
||||
from app.models.membership import create_event
|
||||
|
||||
created = create_event(
|
||||
db,
|
||||
{
|
||||
"title": title,
|
||||
"place": "兰州市城关区",
|
||||
"startsOn": "2026-07-29",
|
||||
"endsOn": "2026-07-31",
|
||||
"quota": 40,
|
||||
"published": True,
|
||||
"mealNote": "午餐自助餐80元/位",
|
||||
"mealDates": ["7月29日", "7月30日", "7月31日"],
|
||||
"payeeName": "甘肃省房地产价格评估行业协会",
|
||||
"bankName": "招商银行兰州中央广场支行",
|
||||
"bankAccount": "931904878610818",
|
||||
"transferNote": "转账备注请写单位简称、参会人姓名、房间和用餐数量",
|
||||
"lodgingNote": "酒店食宿标准详见本场会议通知。",
|
||||
"bodyHtml": _paragraphs(
|
||||
[
|
||||
"本条为本地演示数据。",
|
||||
"会议时间:2026年7月29日至7月31日。",
|
||||
"用餐日期可多选:7月29日、7月30日、7月31日。",
|
||||
"住宿可选协会代订或自理。",
|
||||
]
|
||||
),
|
||||
},
|
||||
)
|
||||
event_id = created["id"]
|
||||
else:
|
||||
event_id = event.id
|
||||
account = db.scalar(select(SiteMember).where(SiteMember.email == INDIVIDUAL_EMAIL))
|
||||
if account is None:
|
||||
return "培训公告已在,个人会员账号不存在,未写报名"
|
||||
exists = db.scalar(
|
||||
select(TrainingRegistration.id).where(
|
||||
TrainingRegistration.event_id == event_id,
|
||||
TrainingRegistration.email == INDIVIDUAL_EMAIL,
|
||||
)
|
||||
)
|
||||
if exists is None:
|
||||
create_registration(
|
||||
db,
|
||||
event_id,
|
||||
{
|
||||
"region": "甘肃省兰州市城关区",
|
||||
"orgName": "兰州示例房地产估价有限公司",
|
||||
"personName": "张伟",
|
||||
"gender": "male",
|
||||
"position": "估价师",
|
||||
"idCard": "620102198805161234",
|
||||
"mobile": "13800001111",
|
||||
"appraiserRegNo": "6201028812",
|
||||
"email": INDIVIDUAL_EMAIL,
|
||||
"lodging": "association",
|
||||
"roomStandard": True,
|
||||
"standardCount": 1,
|
||||
"dine": True,
|
||||
"mealDates": ["7月29日", "7月30日"],
|
||||
},
|
||||
site_member_id=account.id,
|
||||
enforce_quota=False,
|
||||
published_only=False,
|
||||
)
|
||||
return "已写培训公告,并为张伟报名两天用餐"
|
||||
return "培训公告和张伟的报名已在,跳过"
|
||||
|
||||
|
||||
def seed() -> None:
|
||||
import app.models.content # noqa: F401
|
||||
import app.models.home # noqa: F401
|
||||
import app.models.member # noqa: F401
|
||||
import app.models.membership # noqa: F401
|
||||
|
||||
ensure_buckets()
|
||||
engine = get_engine()
|
||||
Base.metadata.create_all(bind=engine)
|
||||
SessionLocal.configure(bind=engine)
|
||||
db = SessionLocal()
|
||||
try:
|
||||
orgs = _seed_orgs(db)
|
||||
notices = _seed_notices(db)
|
||||
_seed_profiles(db)
|
||||
training = _seed_training(db)
|
||||
print(f"会员机构:新增 {orgs} 条。")
|
||||
print(f"会员资讯:新增 {notices} 条。")
|
||||
print(f"会员账号:{INDIVIDUAL_EMAIL} 、{ORGANIZATION_EMAIL}")
|
||||
print(training)
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
seed()
|
||||
@@ -9,7 +9,7 @@ from app.core.config import get_settings
|
||||
TokenType = Literal["staff", "member", "agent"]
|
||||
|
||||
|
||||
def create_access_token(subject: str, token_type: TokenType) -> str:
|
||||
def create_access_token(subject: str, token_type: TokenType, *, version: int | None = None) -> str:
|
||||
settings = get_settings()
|
||||
if len(settings.jwt_secret) < 32:
|
||||
raise HTTPException(
|
||||
@@ -21,8 +21,10 @@ def create_access_token(subject: str, token_type: TokenType) -> str:
|
||||
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}
|
||||
now = datetime.now(timezone.utc)
|
||||
payload = {"sub": subject, "typ": token_type, "exp": now + timedelta(minutes=minutes), "iat": now}
|
||||
if version is not None:
|
||||
payload["ver"] = int(version)
|
||||
return jwt.encode(payload, settings.jwt_secret, algorithm="HS256")
|
||||
|
||||
|
||||
|
||||
+10
-3
@@ -22,6 +22,7 @@ def prepare_runtime() -> None:
|
||||
import app.models.expert # noqa: F401
|
||||
import app.models.agent_user # noqa: F401
|
||||
import app.models.member # noqa: F401
|
||||
import app.models.membership # noqa: F401
|
||||
import app.models.uploaded_case # noqa: F401
|
||||
import app.models.rbac # noqa: F401
|
||||
import app.models.security # noqa: F401
|
||||
@@ -31,6 +32,7 @@ def prepare_runtime() -> None:
|
||||
from app.models.home import (
|
||||
ensure_article_body_capacity,
|
||||
ensure_home_templates,
|
||||
ensure_honor_caption,
|
||||
ensure_hot_link_slots,
|
||||
retire_removed_shortcut_keys,
|
||||
)
|
||||
@@ -42,8 +44,14 @@ def prepare_runtime() -> None:
|
||||
SessionLocal.configure(bind=engine)
|
||||
db = SessionLocal()
|
||||
try:
|
||||
from app.models.member import ensure_member_columns
|
||||
from app.models.rbac import ensure_admin_credential_column
|
||||
|
||||
ensure_member_columns(db)
|
||||
ensure_admin_credential_column(db)
|
||||
ensure_site_defaults(db)
|
||||
ensure_home_templates(db)
|
||||
ensure_honor_caption(db)
|
||||
ensure_hot_link_slots(db)
|
||||
retire_removed_shortcut_keys(db)
|
||||
ensure_article_body_capacity(db)
|
||||
@@ -65,6 +73,7 @@ def prepare_runtime() -> None:
|
||||
ensure_report_menu,
|
||||
ensure_discipline_menu,
|
||||
ensure_edu_menu,
|
||||
ensure_membership_menu,
|
||||
ensure_agent_user_menu,
|
||||
ensure_site_member_menu,
|
||||
ensure_system_menu_order,
|
||||
@@ -81,6 +90,7 @@ def prepare_runtime() -> None:
|
||||
ensure_discipline_menu(db)
|
||||
ensure_tech_menu(db)
|
||||
ensure_edu_menu(db)
|
||||
ensure_membership_menu(db)
|
||||
ensure_ai_agent_menu(db)
|
||||
ensure_site_member_menu(db)
|
||||
ensure_agent_user_menu(db)
|
||||
@@ -91,9 +101,6 @@ def prepare_runtime() -> None:
|
||||
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()
|
||||
|
||||
@@ -10,7 +10,7 @@ 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
|
||||
from app.models.rbac import AdminRole, AdminUser, AdminUserRole, bump_admin_credentials
|
||||
|
||||
AGENT_ADMIN_ROLE_CODE = "R_AGENT_ADMIN"
|
||||
AGENT_ADMIN_ROLE_NAME = "智能体管理员"
|
||||
@@ -275,6 +275,7 @@ def update_agent_record(
|
||||
admin.status = status_text
|
||||
if password_hash:
|
||||
admin.password_hash = password_hash
|
||||
bump_admin_credentials(admin)
|
||||
admin.updated_at = datetime.now(timezone.utc)
|
||||
db.commit()
|
||||
db.refresh(admin)
|
||||
@@ -347,7 +348,17 @@ def staff_can_manage(db, user_id: int) -> bool:
|
||||
return found is not None
|
||||
|
||||
|
||||
def load_agent_actor(db, subject: str) -> AgentActor:
|
||||
def presented_credential_version(principal: dict) -> int:
|
||||
raw = principal.get("ver") if isinstance(principal, dict) else None
|
||||
if raw is None:
|
||||
return 0
|
||||
try:
|
||||
return int(raw)
|
||||
except (TypeError, ValueError):
|
||||
return -1
|
||||
|
||||
|
||||
def load_agent_actor(db, subject: str, *, credential_version: int = 0) -> AgentActor:
|
||||
if subject.startswith("s:"):
|
||||
try:
|
||||
user_id = int(subject[2:])
|
||||
@@ -356,6 +367,11 @@ def load_agent_actor(db, subject: str) -> AgentActor:
|
||||
user = db.get(AdminUser, user_id)
|
||||
if user is None or user.status != "active":
|
||||
raise LookupError("登录已失效")
|
||||
if int(user.credential_epoch or 0) != int(credential_version):
|
||||
raise LookupError("登录已失效")
|
||||
linked = linked_admin_user(db)
|
||||
if linked is not None and linked.id == user.id and not admin_agent_enabled(db):
|
||||
raise LookupError("登录已失效")
|
||||
return AgentActor(
|
||||
key=subject,
|
||||
username=user.username,
|
||||
@@ -372,6 +388,8 @@ def load_agent_actor(db, subject: str) -> AgentActor:
|
||||
row = get_member_by_id(db, user_id)
|
||||
if row is None or row.status != "active" or not row.agent_enabled:
|
||||
raise LookupError("登录已失效")
|
||||
if int(row.credential_epoch or 0) != int(credential_version):
|
||||
raise LookupError("登录已失效")
|
||||
return AgentActor(
|
||||
key=subject,
|
||||
username=row.email,
|
||||
|
||||
@@ -24,7 +24,7 @@ EMPTY_REGIONS = {
|
||||
"policies": "政策法规整理中",
|
||||
"dashboard": "数据看板整理中",
|
||||
"audiences": "估价师、机构与公众入口即将开放",
|
||||
"hotLinks": "报告查询、报告审核与投诉举报入口即将开放",
|
||||
"hotLinks": "报告查询与投诉举报入口即将开放",
|
||||
"honors": "协会荣誉与资质整理中",
|
||||
"members": "会员单位名录整理中",
|
||||
"compliance": "隐私政策、使用条款与网站声明整理中",
|
||||
@@ -39,6 +39,7 @@ EMPTY_REGIONS = {
|
||||
"policy_analyses": "暂无政策分析",
|
||||
"case_library": "暂无案例库",
|
||||
"edu_notices": "暂无教育公告",
|
||||
"member_notices": "暂无会员资讯",
|
||||
"warning_cases": "暂无警示案例",
|
||||
"integrity_records": "暂无诚信档案",
|
||||
"discipline_results": "暂无结果公示",
|
||||
@@ -46,12 +47,10 @@ EMPTY_REGIONS = {
|
||||
|
||||
HOT_LINK_SLOTS = (
|
||||
("reportQuery", "报告查询", "/reports/query"),
|
||||
("reportReview", "报告审核", "/reports/review"),
|
||||
("complaint", "投诉举报", "/discipline"),
|
||||
)
|
||||
FIXED_HOT_URLS = {
|
||||
"reportQuery": "/reports/query",
|
||||
"reportReview": "/reports/review",
|
||||
}
|
||||
HOT_LINK_KEYS = {key for key, _label, _url in HOT_LINK_SLOTS}
|
||||
|
||||
@@ -93,6 +92,7 @@ COLUMN_ARTICLE_CATEGORIES = (
|
||||
"policy_analyses",
|
||||
"case_library",
|
||||
"edu_notices",
|
||||
"member_notices",
|
||||
"warning_cases",
|
||||
"integrity_records",
|
||||
"discipline_results",
|
||||
@@ -226,6 +226,7 @@ class HomeHonor(Base):
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
||||
image_file_id: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
caption: Mapped[str] = mapped_column(String(80), nullable=False, default="")
|
||||
sort_order: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
|
||||
|
||||
|
||||
@@ -920,9 +921,10 @@ def _public_hot_links(db) -> dict:
|
||||
.where(HomeHotLink.visible.is_(True))
|
||||
.order_by(HomeHotLink.sort_order.asc(), HomeHotLink.id.asc())
|
||||
).all()
|
||||
if not rows:
|
||||
links = [_public_hot_link(row) for row in rows if row.key in HOT_LINK_KEYS]
|
||||
if not links:
|
||||
return {"placeholder": EMPTY_REGIONS["hotLinks"]}
|
||||
return {"links": [_public_hot_link(row) for row in rows]}
|
||||
return {"links": links}
|
||||
|
||||
|
||||
def _shortcut_menu(db) -> dict:
|
||||
@@ -959,13 +961,13 @@ def save_audiences(db, categories: list[dict]) -> None:
|
||||
|
||||
def save_hot_links(db, links: list[dict]) -> None:
|
||||
if len(links) != len(HOT_LINK_SLOTS):
|
||||
raise ValueError("高频功能必须是报告查询、报告审核和投诉举报")
|
||||
raise ValueError("高频功能必须是报告查询和投诉举报")
|
||||
seen: set[str] = set()
|
||||
prepared: list[HomeHotLink] = []
|
||||
for link in links:
|
||||
key = link.get("key")
|
||||
if key not in HOT_LINK_KEYS or key in seen:
|
||||
raise ValueError("高频功能必须是报告查询、报告审核和投诉举报")
|
||||
raise ValueError("高频功能必须是报告查询和投诉举报")
|
||||
seen.add(key)
|
||||
url = FIXED_HOT_URLS.get(key)
|
||||
if url is None:
|
||||
@@ -1069,6 +1071,30 @@ def _store_interval(db, kind: str, seconds: int) -> None:
|
||||
row.interval_seconds = seconds
|
||||
|
||||
|
||||
def ensure_honor_caption(db) -> None:
|
||||
bind = db.get_bind()
|
||||
if bind.dialect.name != "mysql":
|
||||
return
|
||||
from sqlalchemy import inspect
|
||||
|
||||
columns = {column["name"] for column in inspect(bind).get_columns("home_honor")}
|
||||
if "caption" in columns:
|
||||
return
|
||||
db.execute(text("ALTER TABLE home_honor ADD COLUMN caption VARCHAR(80) NOT NULL DEFAULT ''"))
|
||||
db.commit()
|
||||
|
||||
|
||||
def _honor_caption(value) -> str:
|
||||
if value is None:
|
||||
return ""
|
||||
if not isinstance(value, str):
|
||||
raise ValueError("荣誉说明不正确")
|
||||
caption = value.strip()
|
||||
if len(caption) > 24:
|
||||
raise ValueError("荣誉说明不能超过24个字")
|
||||
return caption
|
||||
|
||||
|
||||
def _public_honors(db) -> dict:
|
||||
from app.services.storage import public_object_url
|
||||
|
||||
@@ -1078,7 +1104,11 @@ def _public_honors(db) -> dict:
|
||||
image = _public_file(db, row.image_file_id)
|
||||
if image is None:
|
||||
continue
|
||||
items.append({"imageUrl": public_object_url(image.object_key)})
|
||||
item = {"imageUrl": public_object_url(image.object_key)}
|
||||
caption = (row.caption or "").strip()
|
||||
if caption:
|
||||
item["caption"] = caption
|
||||
items.append(item)
|
||||
if not items:
|
||||
return {"placeholder": EMPTY_REGIONS["honors"]}
|
||||
setting = db.get(HomeMarquee, "honors")
|
||||
@@ -1115,6 +1145,7 @@ def save_honors(db, interval_seconds: int, items: list[dict]) -> None:
|
||||
prepared = [
|
||||
HomeHonor(
|
||||
image_file_id=_image_id(db, item.get("imageFileId"), "荣誉图片必须是已上传的公开图片"),
|
||||
caption=_honor_caption(item.get("caption")),
|
||||
sort_order=_sort_order(item),
|
||||
)
|
||||
for item in items
|
||||
@@ -1590,6 +1621,7 @@ def admin_home_view(db) -> dict:
|
||||
{
|
||||
"imageFileId": _editor_image(db, row.image_file_id)[0],
|
||||
"imageUrl": _editor_image(db, row.image_file_id)[1],
|
||||
"caption": row.caption or "",
|
||||
"sortOrder": row.sort_order,
|
||||
}
|
||||
for row in honors
|
||||
|
||||
@@ -26,6 +26,7 @@ class SiteMember(Base):
|
||||
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)
|
||||
credential_epoch: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default="0")
|
||||
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)
|
||||
@@ -57,8 +58,13 @@ def create_member(db, *, email: str, password_hash: str, privacy_accepted_at: da
|
||||
return row
|
||||
|
||||
|
||||
def bump_member_credentials(member: SiteMember) -> None:
|
||||
member.credential_epoch = int(member.credential_epoch or 0) + 1
|
||||
|
||||
|
||||
def set_member_password(db, member: SiteMember, password_hash: str) -> None:
|
||||
member.password_hash = password_hash
|
||||
bump_member_credentials(member)
|
||||
member.updated_at = _now()
|
||||
db.commit()
|
||||
|
||||
@@ -73,6 +79,11 @@ def ensure_member_columns(db) -> None:
|
||||
text("ALTER TABLE site_member ADD COLUMN agent_enabled TINYINT(1) NOT NULL DEFAULT 0")
|
||||
)
|
||||
db.commit()
|
||||
if "credential_epoch" not in names:
|
||||
db.execute(
|
||||
text("ALTER TABLE site_member ADD COLUMN credential_epoch INT NOT NULL DEFAULT 0")
|
||||
)
|
||||
db.commit()
|
||||
|
||||
|
||||
def _iso(value: datetime | None) -> str | None:
|
||||
@@ -156,6 +167,7 @@ def update_member(
|
||||
row.agent_enabled = bool(agent_enabled)
|
||||
if password_hash:
|
||||
row.password_hash = password_hash
|
||||
bump_member_credentials(row)
|
||||
row.updated_at = _now()
|
||||
db.commit()
|
||||
db.refresh(row)
|
||||
|
||||
@@ -0,0 +1,954 @@
|
||||
"""会员服务:外链卡片、协会会员档案、培训报名。"""
|
||||
|
||||
import json
|
||||
import re
|
||||
from datetime import date, datetime, timezone
|
||||
|
||||
from sqlalchemy import Boolean, DateTime, Integer, String, Text, delete, func, select
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from app.db import Base
|
||||
|
||||
ORG_LINK_EMPTY = "暂无会员机构"
|
||||
KINDS = ("individual", "organization")
|
||||
KIND_LABELS = {"individual": "个人会员", "organization": "机构会员"}
|
||||
MEMBERSHIP_STATUSES = ("active", "suspended", "withdrawn")
|
||||
MEMBERSHIP_STATUS_LABELS = {"active": "正常", "suspended": "暂停", "withdrawn": "退会"}
|
||||
FEE_STATUSES = ("paid", "unpaid", "waived")
|
||||
FEE_LABELS = {"paid": "已缴", "unpaid": "未缴", "waived": "免缴"}
|
||||
GENDERS = ("male", "female")
|
||||
GENDER_LABELS = {"male": "男", "female": "女"}
|
||||
LODGING = ("association", "self")
|
||||
_DATE = re.compile(r"^\d{4}-\d{2}-\d{2}$")
|
||||
_MOBILE = re.compile(r"^1\d{10}$")
|
||||
_ID_CARD = re.compile(r"^(?:\d{15}|\d{17}[\dX])$")
|
||||
_REG_NO = re.compile(r"^\d{10}$")
|
||||
_CREDIT = re.compile(r"[0-9A-Z]{18}")
|
||||
|
||||
|
||||
def _mysql_args() -> dict:
|
||||
return {"mysql_charset": "utf8mb4", "mysql_collate": "utf8mb4_unicode_ci"}
|
||||
|
||||
|
||||
def _now() -> datetime:
|
||||
return datetime.now(timezone.utc).replace(tzinfo=None)
|
||||
|
||||
|
||||
class MemberOrgLink(Base):
|
||||
__tablename__ = "member_org_link"
|
||||
__table_args__ = _mysql_args()
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
||||
name: Mapped[str] = mapped_column(String(200), nullable=False)
|
||||
url: Mapped[str] = mapped_column(Text, nullable=False, default="")
|
||||
image_file_id: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
sort_order: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
|
||||
|
||||
|
||||
class AssociationProfile(Base):
|
||||
__tablename__ = "association_profile"
|
||||
__table_args__ = _mysql_args()
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
||||
site_member_id: Mapped[int] = mapped_column(Integer, nullable=False, unique=True, index=True)
|
||||
kind: Mapped[str] = mapped_column(String(16), nullable=False)
|
||||
member_no: Mapped[str] = mapped_column(String(40), nullable=False, default="")
|
||||
membership_status: Mapped[str] = mapped_column(String(16), nullable=False, default="active")
|
||||
joined_on: Mapped[str] = mapped_column(String(10), nullable=False, default="")
|
||||
expires_on: Mapped[str] = mapped_column(String(10), nullable=False, default="")
|
||||
fee_status: Mapped[str] = mapped_column(String(16), nullable=False, default="unpaid")
|
||||
mobile_cipher: Mapped[str] = mapped_column(Text, nullable=False, default="")
|
||||
region: Mapped[str] = mapped_column(String(80), nullable=False, default="")
|
||||
address: Mapped[str] = mapped_column(String(200), nullable=False, default="")
|
||||
postal_code: Mapped[str] = mapped_column(String(10), nullable=False, default="")
|
||||
remark: Mapped[str] = mapped_column(Text, nullable=False, default="")
|
||||
person_name: Mapped[str] = mapped_column(String(40), nullable=False, default="")
|
||||
gender: Mapped[str] = mapped_column(String(8), nullable=False, default="")
|
||||
birth_date: Mapped[str] = mapped_column(String(10), nullable=False, default="")
|
||||
id_card_cipher: Mapped[str] = mapped_column(Text, nullable=False, default="")
|
||||
education: Mapped[str] = mapped_column(String(40), nullable=False, default="")
|
||||
major: Mapped[str] = mapped_column(String(40), nullable=False, default="")
|
||||
job_title: Mapped[str] = mapped_column(String(40), nullable=False, default="")
|
||||
practice_years: Mapped[int | None] = mapped_column(Integer, nullable=True)
|
||||
employer: Mapped[str] = mapped_column(String(200), nullable=False, default="")
|
||||
position: Mapped[str] = mapped_column(String(80), nullable=False, default="")
|
||||
appraiser_reg_no: Mapped[str] = mapped_column(String(32), nullable=False, default="")
|
||||
qualification_no: Mapped[str] = mapped_column(String(32), nullable=False, default="")
|
||||
reg_valid_until: Mapped[str] = mapped_column(String(10), nullable=False, default="")
|
||||
photo_file_id: Mapped[int | None] = mapped_column(Integer, nullable=True)
|
||||
org_name: Mapped[str] = mapped_column(String(200), nullable=False, default="")
|
||||
credit_code: Mapped[str] = mapped_column(String(32), nullable=False, default="")
|
||||
qualification_level: Mapped[str] = mapped_column(String(40), nullable=False, default="")
|
||||
filing_no: Mapped[str] = mapped_column(String(40), nullable=False, default="")
|
||||
legal_person: Mapped[str] = mapped_column(String(40), nullable=False, default="")
|
||||
contact_name: Mapped[str] = mapped_column(String(40), nullable=False, default="")
|
||||
contact_position: Mapped[str] = mapped_column(String(40), nullable=False, default="")
|
||||
contact_mobile_cipher: Mapped[str] = mapped_column(Text, nullable=False, default="")
|
||||
contact_email: Mapped[str] = mapped_column(String(191), nullable=False, default="")
|
||||
office_address: Mapped[str] = mapped_column(String(200), 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 TrainingEvent(Base):
|
||||
__tablename__ = "training_event"
|
||||
__table_args__ = _mysql_args()
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
||||
title: Mapped[str] = mapped_column(String(200), nullable=False)
|
||||
place: Mapped[str] = mapped_column(String(200), nullable=False, default="")
|
||||
starts_on: Mapped[str] = mapped_column(String(10), nullable=False, default="")
|
||||
ends_on: Mapped[str] = mapped_column(String(10), nullable=False, default="")
|
||||
quota: Mapped[int | None] = mapped_column(Integer, nullable=True)
|
||||
body_html: Mapped[str] = mapped_column(Text, nullable=False, default="")
|
||||
published: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)
|
||||
meal_note: Mapped[str] = mapped_column(String(80), nullable=False, default="")
|
||||
meal_dates: Mapped[str] = mapped_column(Text, nullable=False, default="[]")
|
||||
payee_name: Mapped[str] = mapped_column(String(80), nullable=False, default="")
|
||||
bank_name: Mapped[str] = mapped_column(String(80), nullable=False, default="")
|
||||
bank_account: Mapped[str] = mapped_column(String(40), nullable=False, default="")
|
||||
transfer_note: Mapped[str] = mapped_column(String(200), nullable=False, default="")
|
||||
lodging_note: Mapped[str] = mapped_column(Text, 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 TrainingRegistration(Base):
|
||||
__tablename__ = "training_registration"
|
||||
__table_args__ = _mysql_args()
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
||||
event_id: Mapped[int] = mapped_column(Integer, nullable=False, index=True)
|
||||
site_member_id: Mapped[int | None] = mapped_column(Integer, nullable=True, index=True)
|
||||
region: Mapped[str] = mapped_column(String(80), nullable=False, default="")
|
||||
org_name: Mapped[str] = mapped_column(String(200), nullable=False, default="")
|
||||
person_name: Mapped[str] = mapped_column(String(40), nullable=False, default="")
|
||||
gender: Mapped[str] = mapped_column(String(8), nullable=False, default="")
|
||||
position: Mapped[str] = mapped_column(String(80), nullable=False, default="")
|
||||
id_card_cipher: Mapped[str] = mapped_column(Text, nullable=False, default="")
|
||||
mobile_cipher: Mapped[str] = mapped_column(Text, nullable=False, default="")
|
||||
appraiser_reg_no: Mapped[str] = mapped_column(String(32), nullable=False, default="")
|
||||
email: Mapped[str] = mapped_column(String(191), nullable=False, default="")
|
||||
lodging: Mapped[str] = mapped_column(String(16), nullable=False, default="self")
|
||||
room_standard: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)
|
||||
room_single: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)
|
||||
standard_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
|
||||
single_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
|
||||
dine: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)
|
||||
meal_dates: Mapped[str] = mapped_column(Text, 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)
|
||||
|
||||
|
||||
def _optional(value, label: str, limit: int) -> str:
|
||||
text = "" if value is None else str(value)
|
||||
text = " ".join(text.replace("\r", " ").replace("\n", " ").split())
|
||||
if len(text) > limit:
|
||||
raise ValueError(f"{label}过长")
|
||||
return text
|
||||
|
||||
|
||||
def _required(value, label: str, limit: int) -> str:
|
||||
text = _optional(value, label, limit)
|
||||
if not text:
|
||||
raise ValueError(f"请填写{label}")
|
||||
return text
|
||||
|
||||
|
||||
def _choice(value, allowed: tuple[str, ...], label: str) -> str:
|
||||
text = _optional(value, label, 32)
|
||||
if text not in allowed:
|
||||
raise ValueError(f"{label}不正确")
|
||||
return text
|
||||
|
||||
|
||||
def _date_text(value, label: str) -> str:
|
||||
text = _optional(value, label, 10)
|
||||
if not text:
|
||||
return ""
|
||||
if not _DATE.fullmatch(text):
|
||||
raise ValueError(f"{label}请使用年-月-日")
|
||||
try:
|
||||
date.fromisoformat(text)
|
||||
except ValueError as exc:
|
||||
raise ValueError(f"{label}不正确") from exc
|
||||
return text
|
||||
|
||||
|
||||
def _mobile(value, *, required: bool) -> str:
|
||||
text = re.sub(r"[\s-]", "", "" if value is None else str(value))
|
||||
if not text:
|
||||
if required:
|
||||
raise ValueError("请填写联系电话")
|
||||
return ""
|
||||
if not _MOBILE.fullmatch(text):
|
||||
raise ValueError("请填写有效的手机号")
|
||||
return text
|
||||
|
||||
|
||||
def _id_card(value, *, required: bool) -> str:
|
||||
text = re.sub(r"\s+", "", "" if value is None else str(value)).upper()
|
||||
if not text:
|
||||
if required:
|
||||
raise ValueError("请填写身份证号")
|
||||
return ""
|
||||
if not _ID_CARD.fullmatch(text):
|
||||
raise ValueError("身份证号不正确")
|
||||
return text
|
||||
|
||||
|
||||
def _reg_no(value, *, required: bool) -> str:
|
||||
text = re.sub(r"\s+", "", "" if value is None else str(value))
|
||||
if not text:
|
||||
if required:
|
||||
raise ValueError("请填写估价师注册证号")
|
||||
return ""
|
||||
if not _REG_NO.fullmatch(text):
|
||||
raise ValueError("估价师注册证号需为10位数字")
|
||||
return text
|
||||
|
||||
|
||||
def _credit(value) -> str:
|
||||
text = re.sub(r"\s+", "", "" if value is None else str(value)).upper()
|
||||
if not text:
|
||||
return ""
|
||||
if not _CREDIT.fullmatch(text):
|
||||
raise ValueError("统一社会信用代码不正确")
|
||||
return text
|
||||
|
||||
|
||||
def _years(value) -> int | None:
|
||||
if value is None or value == "":
|
||||
return None
|
||||
if isinstance(value, bool) or not isinstance(value, int) or value < 0 or value > 80:
|
||||
raise ValueError("从业年限不正确")
|
||||
return value
|
||||
|
||||
|
||||
def _quota(value) -> int | None:
|
||||
if value is None or value == "":
|
||||
return None
|
||||
if isinstance(value, bool) or not isinstance(value, int) or value < 1 or value > 10000:
|
||||
raise ValueError("名额不正确")
|
||||
return value
|
||||
|
||||
|
||||
def _count(value, label: str) -> int:
|
||||
if value is None or value == "":
|
||||
return 0
|
||||
if isinstance(value, bool) or not isinstance(value, int) or value < 0 or value > 99:
|
||||
raise ValueError(f"{label}不正确")
|
||||
return value
|
||||
|
||||
|
||||
def _event_dates(values) -> list[str]:
|
||||
if values is None:
|
||||
values = []
|
||||
if not isinstance(values, list):
|
||||
raise ValueError("用餐日期不正确")
|
||||
if len(values) > 31:
|
||||
raise ValueError("用餐日期过多")
|
||||
seen: list[str] = []
|
||||
for item in values:
|
||||
text = _optional(item, "用餐日期", 40)
|
||||
if not text:
|
||||
continue
|
||||
if text in seen:
|
||||
raise ValueError("用餐日期不能重复")
|
||||
seen.append(text)
|
||||
return seen
|
||||
|
||||
|
||||
def _selected_dates(values, allowed: list[str], dine: bool) -> list[str]:
|
||||
if values is None:
|
||||
values = []
|
||||
if not isinstance(values, list):
|
||||
raise ValueError("用餐日期不正确")
|
||||
picked: list[str] = []
|
||||
for item in values:
|
||||
text = _optional(item, "用餐日期", 40)
|
||||
if not text:
|
||||
continue
|
||||
if text not in allowed:
|
||||
raise ValueError("请从本场公告的用餐日期中选择")
|
||||
if text not in picked:
|
||||
picked.append(text)
|
||||
if not dine:
|
||||
if picked:
|
||||
raise ValueError("不用餐时不要选择用餐日期")
|
||||
return []
|
||||
if allowed and not picked:
|
||||
raise ValueError("请选择用餐日期")
|
||||
if not allowed and picked:
|
||||
raise ValueError("本场未设置用餐日期")
|
||||
return picked
|
||||
|
||||
|
||||
def _load_dates(raw: str) -> list[str]:
|
||||
try:
|
||||
parsed = json.loads(raw or "[]")
|
||||
except json.JSONDecodeError:
|
||||
return []
|
||||
if not isinstance(parsed, list):
|
||||
return []
|
||||
return [str(item) for item in parsed if str(item).strip()]
|
||||
|
||||
|
||||
def _dump_dates(values: list[str]) -> str:
|
||||
return json.dumps(values, ensure_ascii=False)
|
||||
|
||||
|
||||
def _encrypt(value: str) -> str:
|
||||
from app.core.field_crypto import encrypt_text
|
||||
|
||||
return encrypt_text(value) if value else ""
|
||||
|
||||
|
||||
def _decrypt(value: str) -> str:
|
||||
from app.core.field_crypto import decrypt_text
|
||||
|
||||
return decrypt_text(value) if value else ""
|
||||
|
||||
|
||||
def _mask_mobile(value: str) -> str:
|
||||
from app.core.masking import mask_mobile
|
||||
|
||||
return mask_mobile(value)
|
||||
|
||||
|
||||
def _mask_id(value: str) -> str:
|
||||
from app.core.masking import mask_id_card
|
||||
|
||||
return mask_id_card(value)
|
||||
|
||||
|
||||
def _public_image(db, file_id):
|
||||
from app.models.content import AdminFile
|
||||
|
||||
if isinstance(file_id, bool) or not isinstance(file_id, int) or file_id <= 0:
|
||||
return None
|
||||
row = db.get(AdminFile, file_id)
|
||||
if row is None or row.bucket != "public":
|
||||
return None
|
||||
return row
|
||||
|
||||
|
||||
def _image_url(db, file_id: int | None) -> str:
|
||||
from app.services.storage import public_object_url
|
||||
|
||||
row = _public_image(db, file_id)
|
||||
if row is None:
|
||||
return ""
|
||||
return public_object_url(row.object_key)
|
||||
|
||||
|
||||
def _link_url(value) -> str:
|
||||
text = _optional(value, "网址", 2048)
|
||||
if not text.lower().startswith(("http://", "https://")):
|
||||
raise ValueError("网址不正确")
|
||||
return text
|
||||
|
||||
|
||||
def _sort_order(item: dict) -> int:
|
||||
value = item.get("sortOrder", 0)
|
||||
if isinstance(value, bool) or not isinstance(value, int) or value < 0 or value > 9999:
|
||||
raise ValueError("顺序不正确")
|
||||
return value
|
||||
|
||||
|
||||
def _filter_html(db, html: str) -> str:
|
||||
from app.core.config import get_settings
|
||||
from app.models.content import AdminFile
|
||||
from app.services.html_filter import filter_html
|
||||
|
||||
keys = list(db.scalars(select(AdminFile.object_key).where(AdminFile.bucket == "public")))
|
||||
return filter_html(html or "", list(keys), get_settings().minio_base_url)
|
||||
|
||||
|
||||
def public_org_links(db) -> dict:
|
||||
rows = db.scalars(
|
||||
select(MemberOrgLink).order_by(MemberOrgLink.sort_order.asc(), MemberOrgLink.id.asc())
|
||||
).all()
|
||||
items = []
|
||||
for row in rows:
|
||||
image_url = _image_url(db, row.image_file_id)
|
||||
if not image_url:
|
||||
continue
|
||||
items.append(
|
||||
{
|
||||
"name": row.name,
|
||||
"url": row.url,
|
||||
"navigation": "newWindow",
|
||||
"imageUrl": image_url,
|
||||
}
|
||||
)
|
||||
if not items:
|
||||
return {"placeholder": ORG_LINK_EMPTY}
|
||||
return {"items": items}
|
||||
|
||||
|
||||
def admin_org_links(db) -> dict:
|
||||
rows = db.scalars(
|
||||
select(MemberOrgLink).order_by(MemberOrgLink.sort_order.asc(), MemberOrgLink.id.asc())
|
||||
).all()
|
||||
items = []
|
||||
for row in rows:
|
||||
image = _public_image(db, row.image_file_id)
|
||||
items.append(
|
||||
{
|
||||
"name": row.name,
|
||||
"url": row.url,
|
||||
"imageFileId": image.id if image else None,
|
||||
"imageUrl": _image_url(db, image.id if image else None),
|
||||
"sortOrder": row.sort_order,
|
||||
}
|
||||
)
|
||||
return {"items": items}
|
||||
|
||||
|
||||
def save_org_links(db, items: list[dict]) -> None:
|
||||
prepared = []
|
||||
for item in items:
|
||||
name = _required(item.get("name"), "名称", 200)
|
||||
image = _public_image(db, item.get("imageFileId"))
|
||||
if image is None:
|
||||
raise ValueError("会员机构图片必须是已上传的公开图片")
|
||||
prepared.append(
|
||||
MemberOrgLink(
|
||||
name=name,
|
||||
url=_link_url(item.get("url")),
|
||||
image_file_id=image.id,
|
||||
sort_order=_sort_order(item),
|
||||
)
|
||||
)
|
||||
db.execute(delete(MemberOrgLink))
|
||||
db.add_all(prepared)
|
||||
db.commit()
|
||||
|
||||
|
||||
def _email(value) -> str:
|
||||
from app.services.email_code import is_valid_email, normalize_email
|
||||
|
||||
email = normalize_email("" if value is None else str(value))
|
||||
if not is_valid_email(email):
|
||||
raise ValueError("登录邮箱格式不正确")
|
||||
return email
|
||||
|
||||
|
||||
def _optional_email(value, label: str) -> str:
|
||||
from app.services.email_code import is_valid_email, normalize_email
|
||||
|
||||
email = normalize_email("" if value is None else str(value))
|
||||
if not email:
|
||||
return ""
|
||||
if not is_valid_email(email):
|
||||
raise ValueError(f"{label}格式不正确")
|
||||
return email
|
||||
|
||||
|
||||
def _apply_profile(db, row: AssociationProfile, payload: dict) -> None:
|
||||
kind = _choice(payload.get("kind"), KINDS, "会员类型")
|
||||
row.kind = kind
|
||||
row.member_no = _optional(payload.get("memberNo"), "会员编号", 40)
|
||||
row.membership_status = _choice(payload.get("membershipStatus"), MEMBERSHIP_STATUSES, "会员状态")
|
||||
row.joined_on = _date_text(payload.get("joinedOn"), "入会日期")
|
||||
row.expires_on = _date_text(payload.get("expiresOn"), "到期日")
|
||||
row.fee_status = _choice(payload.get("feeStatus"), FEE_STATUSES, "会费状态")
|
||||
row.mobile_cipher = _encrypt(_mobile(payload.get("mobile"), required=False))
|
||||
row.region = _optional(payload.get("region"), "所在地区", 80)
|
||||
row.address = _optional(payload.get("address"), "通讯地址", 200)
|
||||
row.postal_code = _optional(payload.get("postalCode"), "邮编", 10)
|
||||
row.remark = _optional(payload.get("remark"), "备注", 500)
|
||||
row.person_name = _optional(payload.get("personName"), "姓名", 40)
|
||||
gender = _optional(payload.get("gender"), "性别", 8)
|
||||
if gender and gender not in GENDERS:
|
||||
raise ValueError("性别不正确")
|
||||
row.gender = gender
|
||||
row.birth_date = _date_text(payload.get("birthDate"), "出生日期")
|
||||
row.id_card_cipher = _encrypt(_id_card(payload.get("idCard"), required=False))
|
||||
row.education = _optional(payload.get("education"), "学历", 40)
|
||||
row.major = _optional(payload.get("major"), "专业", 40)
|
||||
row.job_title = _optional(payload.get("jobTitle"), "职称", 40)
|
||||
row.practice_years = _years(payload.get("practiceYears"))
|
||||
row.employer = _optional(payload.get("employer"), "工作单位", 200)
|
||||
row.position = _optional(payload.get("position"), "职务", 80)
|
||||
row.appraiser_reg_no = _reg_no(payload.get("appraiserRegNo"), required=False)
|
||||
row.qualification_no = _optional(payload.get("qualificationNo"), "资格证号", 32)
|
||||
row.reg_valid_until = _date_text(payload.get("regValidUntil"), "注册有效期")
|
||||
photo = payload.get("photoFileId")
|
||||
if photo in (None, ""):
|
||||
row.photo_file_id = None
|
||||
else:
|
||||
image = _public_image(db, photo)
|
||||
if image is None:
|
||||
raise ValueError("照片必须是已上传的公开图片")
|
||||
row.photo_file_id = image.id
|
||||
row.org_name = _optional(payload.get("orgName"), "单位全称", 200)
|
||||
row.credit_code = _credit(payload.get("creditCode"))
|
||||
row.qualification_level = _optional(payload.get("qualificationLevel"), "资质等级", 40)
|
||||
row.filing_no = _optional(payload.get("filingNo"), "备案编号", 40)
|
||||
row.legal_person = _optional(payload.get("legalPerson"), "法定代表人", 40)
|
||||
row.contact_name = _optional(payload.get("contactName"), "联系人姓名", 40)
|
||||
row.contact_position = _optional(payload.get("contactPosition"), "联系人职务", 40)
|
||||
row.contact_mobile_cipher = _encrypt(_mobile(payload.get("contactMobile"), required=False))
|
||||
row.contact_email = _optional_email(payload.get("contactEmail"), "联系人邮箱")
|
||||
row.office_address = _optional(payload.get("officeAddress"), "办公地址", 200)
|
||||
if kind == "individual" and not row.person_name:
|
||||
raise ValueError("请填写姓名")
|
||||
if kind == "organization" and not row.org_name:
|
||||
raise ValueError("请填写单位全称")
|
||||
|
||||
|
||||
def _display_name(row: AssociationProfile) -> str:
|
||||
if row.kind == "organization":
|
||||
return row.org_name
|
||||
return row.person_name
|
||||
|
||||
|
||||
def _profile_body(db, row: AssociationProfile, account, *, reveal: bool) -> dict:
|
||||
mobile = _decrypt(row.mobile_cipher)
|
||||
id_card = _decrypt(row.id_card_cipher)
|
||||
contact_mobile = _decrypt(row.contact_mobile_cipher)
|
||||
if not reveal:
|
||||
mobile = _mask_mobile(mobile)
|
||||
id_card = _mask_id(id_card)
|
||||
contact_mobile = _mask_mobile(contact_mobile)
|
||||
return {
|
||||
"id": row.id,
|
||||
"email": account.email if account else "",
|
||||
"accountStatus": account.status if account else "",
|
||||
"kind": row.kind,
|
||||
"kindLabel": KIND_LABELS.get(row.kind, row.kind),
|
||||
"memberNo": row.member_no,
|
||||
"membershipStatus": row.membership_status,
|
||||
"membershipStatusLabel": MEMBERSHIP_STATUS_LABELS.get(row.membership_status, row.membership_status),
|
||||
"joinedOn": row.joined_on,
|
||||
"expiresOn": row.expires_on,
|
||||
"feeStatus": row.fee_status,
|
||||
"feeStatusLabel": FEE_LABELS.get(row.fee_status, row.fee_status),
|
||||
"mobile": mobile,
|
||||
"region": row.region,
|
||||
"address": row.address,
|
||||
"postalCode": row.postal_code,
|
||||
"remark": row.remark,
|
||||
"personName": row.person_name,
|
||||
"gender": row.gender,
|
||||
"genderLabel": GENDER_LABELS.get(row.gender, ""),
|
||||
"birthDate": row.birth_date,
|
||||
"idCard": id_card,
|
||||
"education": row.education,
|
||||
"major": row.major,
|
||||
"jobTitle": row.job_title,
|
||||
"practiceYears": row.practice_years,
|
||||
"employer": row.employer,
|
||||
"position": row.position,
|
||||
"appraiserRegNo": row.appraiser_reg_no,
|
||||
"qualificationNo": row.qualification_no,
|
||||
"regValidUntil": row.reg_valid_until,
|
||||
"photoFileId": row.photo_file_id,
|
||||
"photoUrl": _image_url(db, row.photo_file_id),
|
||||
"orgName": row.org_name,
|
||||
"creditCode": row.credit_code,
|
||||
"qualificationLevel": row.qualification_level,
|
||||
"filingNo": row.filing_no,
|
||||
"legalPerson": row.legal_person,
|
||||
"contactName": row.contact_name,
|
||||
"contactPosition": row.contact_position,
|
||||
"contactMobile": contact_mobile,
|
||||
"contactEmail": row.contact_email,
|
||||
"officeAddress": row.office_address,
|
||||
"displayName": _display_name(row),
|
||||
}
|
||||
|
||||
|
||||
def _account(db, site_member_id: int):
|
||||
from app.models.member import SiteMember
|
||||
|
||||
return db.get(SiteMember, site_member_id)
|
||||
|
||||
|
||||
def _profile_for_account(db, site_member_id: int) -> AssociationProfile | None:
|
||||
return db.scalar(select(AssociationProfile).where(AssociationProfile.site_member_id == site_member_id))
|
||||
|
||||
|
||||
def list_profiles(db, *, current: int, size: int, keyword: str) -> dict:
|
||||
from app.models.member import SiteMember
|
||||
|
||||
if current < 1:
|
||||
current = 1
|
||||
if size < 1:
|
||||
size = 10
|
||||
if size > 100:
|
||||
size = 100
|
||||
filters = []
|
||||
text = (keyword or "").strip()
|
||||
if text:
|
||||
matched_ids = db.scalars(select(SiteMember.id).where(SiteMember.email.contains(text.lower()))).all()
|
||||
filters.append(
|
||||
AssociationProfile.member_no.contains(text)
|
||||
| AssociationProfile.person_name.contains(text)
|
||||
| AssociationProfile.org_name.contains(text)
|
||||
| AssociationProfile.site_member_id.in_(matched_ids or [-1])
|
||||
)
|
||||
total = db.scalar(select(func.count()).select_from(AssociationProfile).where(*filters)) or 0
|
||||
rows = db.scalars(
|
||||
select(AssociationProfile)
|
||||
.where(*filters)
|
||||
.order_by(AssociationProfile.id.desc())
|
||||
.offset((current - 1) * size)
|
||||
.limit(size)
|
||||
).all()
|
||||
return {
|
||||
"records": [_profile_body(db, row, _account(db, row.site_member_id), reveal=False) for row in rows],
|
||||
"current": current,
|
||||
"size": size,
|
||||
"total": int(total),
|
||||
}
|
||||
|
||||
|
||||
def read_profile(db, profile_id: int, *, reveal: bool) -> dict:
|
||||
row = db.get(AssociationProfile, profile_id)
|
||||
if row is None:
|
||||
raise LookupError("会员不存在")
|
||||
return _profile_body(db, row, _account(db, row.site_member_id), reveal=reveal)
|
||||
|
||||
|
||||
def profile_for_member(db, site_member_id: int) -> dict | None:
|
||||
row = _profile_for_account(db, site_member_id)
|
||||
if row is None:
|
||||
return None
|
||||
return _profile_body(db, row, _account(db, site_member_id), reveal=True)
|
||||
|
||||
|
||||
def _attach_account(db, email: str, password_hash: str | None, current_id: int | None):
|
||||
from app.models.member import SiteMember, bump_member_credentials
|
||||
|
||||
account = db.scalar(select(SiteMember).where(SiteMember.email == email))
|
||||
if account is None:
|
||||
if not password_hash:
|
||||
raise ValueError("请设置初始密码")
|
||||
account = SiteMember(
|
||||
email=email,
|
||||
password_hash=password_hash,
|
||||
status="active",
|
||||
privacy_accepted_at=_now(),
|
||||
created_at=_now(),
|
||||
updated_at=_now(),
|
||||
)
|
||||
db.add(account)
|
||||
db.flush()
|
||||
elif password_hash:
|
||||
account.password_hash = password_hash
|
||||
bump_member_credentials(account)
|
||||
account.updated_at = _now()
|
||||
holder = _profile_for_account(db, account.id)
|
||||
if holder is not None and holder.id != current_id:
|
||||
raise ValueError("该邮箱已有会员档案")
|
||||
return account
|
||||
|
||||
|
||||
def create_profile(db, payload: dict, password_hash: str | None) -> dict:
|
||||
email = _email(payload.get("email"))
|
||||
account = _attach_account(db, email, password_hash, None)
|
||||
row = AssociationProfile(site_member_id=account.id, kind="individual", created_at=_now(), updated_at=_now())
|
||||
_apply_profile(db, row, payload)
|
||||
row.updated_at = _now()
|
||||
db.add(row)
|
||||
db.commit()
|
||||
db.refresh(row)
|
||||
return _profile_body(db, row, account, reveal=True)
|
||||
|
||||
|
||||
def update_profile(db, profile_id: int, payload: dict, password_hash: str | None) -> dict:
|
||||
row = db.get(AssociationProfile, profile_id)
|
||||
if row is None:
|
||||
raise LookupError("会员不存在")
|
||||
email = _email(payload.get("email"))
|
||||
account = _attach_account(db, email, password_hash, row.id)
|
||||
row.site_member_id = account.id
|
||||
_apply_profile(db, row, payload)
|
||||
row.updated_at = _now()
|
||||
db.commit()
|
||||
db.refresh(row)
|
||||
return _profile_body(db, row, account, reveal=True)
|
||||
|
||||
|
||||
def delete_profile(db, profile_id: int) -> None:
|
||||
row = db.get(AssociationProfile, profile_id)
|
||||
if row is None:
|
||||
raise LookupError("会员不存在")
|
||||
db.delete(row)
|
||||
db.commit()
|
||||
|
||||
|
||||
def _event_body(db, row: TrainingEvent, *, include_html: bool) -> dict:
|
||||
count = db.scalar(
|
||||
select(func.count()).select_from(TrainingRegistration).where(TrainingRegistration.event_id == row.id)
|
||||
) or 0
|
||||
remaining = None if row.quota is None else max(row.quota - int(count), 0)
|
||||
body = {
|
||||
"id": row.id,
|
||||
"title": row.title,
|
||||
"place": row.place,
|
||||
"startsOn": row.starts_on,
|
||||
"endsOn": row.ends_on,
|
||||
"quota": row.quota,
|
||||
"registeredCount": int(count),
|
||||
"remaining": remaining,
|
||||
"published": bool(row.published),
|
||||
"mealNote": row.meal_note,
|
||||
"mealDates": _load_dates(row.meal_dates),
|
||||
"payeeName": row.payee_name,
|
||||
"bankName": row.bank_name,
|
||||
"bankAccount": row.bank_account,
|
||||
"transferNote": row.transfer_note,
|
||||
"lodgingNote": row.lodging_note,
|
||||
}
|
||||
if include_html:
|
||||
body["bodyHtml"] = row.body_html
|
||||
return body
|
||||
|
||||
|
||||
def _apply_event(db, row: TrainingEvent, payload: dict) -> None:
|
||||
row.title = _required(payload.get("title"), "会议名称", 200)
|
||||
row.place = _optional(payload.get("place"), "培训地点", 200)
|
||||
row.starts_on = _date_text(payload.get("startsOn"), "开始日期")
|
||||
row.ends_on = _date_text(payload.get("endsOn"), "结束日期")
|
||||
if row.starts_on and row.ends_on and row.ends_on < row.starts_on:
|
||||
raise ValueError("结束日期不能早于开始日期")
|
||||
row.quota = _quota(payload.get("quota"))
|
||||
row.body_html = _filter_html(db, payload.get("bodyHtml") or "")
|
||||
row.published = bool(payload.get("published"))
|
||||
row.meal_note = _optional(payload.get("mealNote"), "用餐说明", 80)
|
||||
row.meal_dates = _dump_dates(_event_dates(payload.get("mealDates")))
|
||||
row.payee_name = _optional(payload.get("payeeName"), "账户名称", 80)
|
||||
row.bank_name = _optional(payload.get("bankName"), "开户行", 80)
|
||||
row.bank_account = _optional(payload.get("bankAccount"), "账号", 40)
|
||||
row.transfer_note = _optional(payload.get("transferNote"), "转账备注", 200)
|
||||
row.lodging_note = _optional(payload.get("lodgingNote"), "食宿标准", 500)
|
||||
row.updated_at = _now()
|
||||
|
||||
|
||||
def list_events(db, *, published_only: bool) -> dict:
|
||||
query = select(TrainingEvent).order_by(TrainingEvent.id.desc())
|
||||
if published_only:
|
||||
query = query.where(TrainingEvent.published.is_(True))
|
||||
rows = db.scalars(query).all()
|
||||
if published_only and not rows:
|
||||
return {"placeholder": "暂无培训报名", "items": []}
|
||||
return {"items": [_event_body(db, row, include_html=False) for row in rows]}
|
||||
|
||||
|
||||
def read_event(db, event_id: int, *, published_only: bool) -> dict:
|
||||
row = db.get(TrainingEvent, event_id)
|
||||
if row is None or (published_only and not row.published):
|
||||
raise LookupError("培训公告不存在")
|
||||
return _event_body(db, row, include_html=True)
|
||||
|
||||
|
||||
def create_event(db, payload: dict) -> dict:
|
||||
row = TrainingEvent(title="", created_at=_now(), updated_at=_now())
|
||||
_apply_event(db, row, payload)
|
||||
db.add(row)
|
||||
db.commit()
|
||||
db.refresh(row)
|
||||
return _event_body(db, row, include_html=True)
|
||||
|
||||
|
||||
def update_event(db, event_id: int, payload: dict) -> dict:
|
||||
row = db.get(TrainingEvent, event_id)
|
||||
if row is None:
|
||||
raise LookupError("培训公告不存在")
|
||||
_apply_event(db, row, payload)
|
||||
db.commit()
|
||||
db.refresh(row)
|
||||
return _event_body(db, row, include_html=True)
|
||||
|
||||
|
||||
def delete_event(db, event_id: int) -> None:
|
||||
row = db.get(TrainingEvent, event_id)
|
||||
if row is None:
|
||||
raise LookupError("培训公告不存在")
|
||||
db.execute(delete(TrainingRegistration).where(TrainingRegistration.event_id == row.id))
|
||||
db.delete(row)
|
||||
db.commit()
|
||||
|
||||
|
||||
def _registration_body(row: TrainingRegistration, *, reveal: bool) -> dict:
|
||||
mobile = _decrypt(row.mobile_cipher)
|
||||
id_card = _decrypt(row.id_card_cipher)
|
||||
if not reveal:
|
||||
mobile = _mask_mobile(mobile)
|
||||
id_card = _mask_id(id_card)
|
||||
return {
|
||||
"id": row.id,
|
||||
"eventId": row.event_id,
|
||||
"siteMemberId": row.site_member_id,
|
||||
"region": row.region,
|
||||
"orgName": row.org_name,
|
||||
"personName": row.person_name,
|
||||
"gender": row.gender,
|
||||
"genderLabel": GENDER_LABELS.get(row.gender, ""),
|
||||
"position": row.position,
|
||||
"idCard": id_card,
|
||||
"mobile": mobile,
|
||||
"appraiserRegNo": row.appraiser_reg_no,
|
||||
"email": row.email,
|
||||
"lodging": row.lodging,
|
||||
"lodgingLabel": "协会代订" if row.lodging == "association" else "自理",
|
||||
"roomStandard": bool(row.room_standard),
|
||||
"roomSingle": bool(row.room_single),
|
||||
"standardCount": row.standard_count,
|
||||
"singleCount": row.single_count,
|
||||
"dine": bool(row.dine),
|
||||
"dineLabel": "是" if row.dine else "否",
|
||||
"mealDates": _load_dates(row.meal_dates),
|
||||
}
|
||||
|
||||
|
||||
def _apply_registration(row: TrainingRegistration, payload: dict, allowed_dates: list[str]) -> None:
|
||||
row.region = _required(payload.get("region"), "所在地区", 80)
|
||||
row.org_name = _required(payload.get("orgName"), "单位名称", 200)
|
||||
row.person_name = _required(payload.get("personName"), "姓名", 40)
|
||||
row.gender = _choice(payload.get("gender"), GENDERS, "性别")
|
||||
row.position = _required(payload.get("position"), "职务", 80)
|
||||
row.id_card_cipher = _encrypt(_id_card(payload.get("idCard"), required=True))
|
||||
row.mobile_cipher = _encrypt(_mobile(payload.get("mobile"), required=True))
|
||||
row.appraiser_reg_no = _reg_no(payload.get("appraiserRegNo"), required=True)
|
||||
row.email = _email(payload.get("email"))
|
||||
lodging = _choice(payload.get("lodging"), LODGING, "住宿")
|
||||
row.lodging = lodging
|
||||
if lodging == "self":
|
||||
row.room_standard = False
|
||||
row.room_single = False
|
||||
row.standard_count = 0
|
||||
row.single_count = 0
|
||||
else:
|
||||
row.room_standard = bool(payload.get("roomStandard"))
|
||||
row.room_single = bool(payload.get("roomSingle"))
|
||||
row.standard_count = _count(payload.get("standardCount"), "标间间数") if row.room_standard else 0
|
||||
row.single_count = _count(payload.get("singleCount"), "单间间数") if row.room_single else 0
|
||||
if row.room_standard and row.standard_count < 1:
|
||||
raise ValueError("请填写标间间数")
|
||||
if row.room_single and row.single_count < 1:
|
||||
raise ValueError("请填写单间间数")
|
||||
dine = bool(payload.get("dine"))
|
||||
row.dine = dine
|
||||
row.meal_dates = _dump_dates(_selected_dates(payload.get("mealDates"), allowed_dates, dine))
|
||||
row.updated_at = _now()
|
||||
|
||||
|
||||
def _ensure_unique(db, event_id: int, email: str, site_member_id: int | None, current_id: int | None) -> None:
|
||||
rows = db.scalars(select(TrainingRegistration).where(TrainingRegistration.event_id == event_id)).all()
|
||||
for row in rows:
|
||||
if current_id is not None and row.id == current_id:
|
||||
continue
|
||||
if row.email == email:
|
||||
raise ValueError("该邮箱已报名这场会议")
|
||||
if site_member_id is not None and row.site_member_id == site_member_id:
|
||||
raise ValueError("已报名这场会议")
|
||||
|
||||
|
||||
def list_registrations(db, event_id: int, *, reveal: bool) -> dict:
|
||||
event = db.get(TrainingEvent, event_id)
|
||||
if event is None:
|
||||
raise LookupError("培训公告不存在")
|
||||
rows = db.scalars(
|
||||
select(TrainingRegistration)
|
||||
.where(TrainingRegistration.event_id == event_id)
|
||||
.order_by(TrainingRegistration.id.desc())
|
||||
).all()
|
||||
return {"items": [_registration_body(row, reveal=reveal) for row in rows]}
|
||||
|
||||
|
||||
def member_registrations(db, site_member_id: int) -> dict:
|
||||
from app.models.member import SiteMember
|
||||
|
||||
account = db.get(SiteMember, site_member_id)
|
||||
email = account.email if account else ""
|
||||
rows = db.scalars(
|
||||
select(TrainingRegistration)
|
||||
.where(
|
||||
(TrainingRegistration.site_member_id == site_member_id)
|
||||
| (TrainingRegistration.email == email)
|
||||
)
|
||||
.order_by(TrainingRegistration.id.desc())
|
||||
).all()
|
||||
items = []
|
||||
for row in rows:
|
||||
event = db.get(TrainingEvent, row.event_id)
|
||||
body = _registration_body(row, reveal=True)
|
||||
body["eventTitle"] = event.title if event else ""
|
||||
body["eventPublished"] = bool(event.published) if event else False
|
||||
items.append(body)
|
||||
return {"items": items}
|
||||
|
||||
|
||||
def create_registration(
|
||||
db,
|
||||
event_id: int,
|
||||
payload: dict,
|
||||
*,
|
||||
site_member_id: int | None,
|
||||
enforce_quota: bool,
|
||||
published_only: bool,
|
||||
) -> dict:
|
||||
event = db.get(TrainingEvent, event_id)
|
||||
if event is None or (published_only and not event.published):
|
||||
raise LookupError("培训公告不存在")
|
||||
if enforce_quota and event.quota is not None:
|
||||
count = db.scalar(
|
||||
select(func.count()).select_from(TrainingRegistration).where(TrainingRegistration.event_id == event.id)
|
||||
) or 0
|
||||
if int(count) >= event.quota:
|
||||
raise ValueError("名额已满")
|
||||
email = _email(payload.get("email"))
|
||||
linked = site_member_id
|
||||
if linked is None:
|
||||
from app.models.member import SiteMember
|
||||
|
||||
account = db.scalar(select(SiteMember).where(SiteMember.email == email))
|
||||
if account is not None:
|
||||
linked = account.id
|
||||
_ensure_unique(db, event.id, email, linked, None)
|
||||
row = TrainingRegistration(event_id=event.id, site_member_id=linked, created_at=_now(), updated_at=_now())
|
||||
_apply_registration(row, payload, _load_dates(event.meal_dates))
|
||||
db.add(row)
|
||||
db.commit()
|
||||
db.refresh(row)
|
||||
return _registration_body(row, reveal=True)
|
||||
|
||||
|
||||
def update_registration(db, registration_id: int, payload: dict) -> dict:
|
||||
row = db.get(TrainingRegistration, registration_id)
|
||||
if row is None:
|
||||
raise LookupError("报名不存在")
|
||||
event = db.get(TrainingEvent, row.event_id)
|
||||
if event is None:
|
||||
raise LookupError("培训公告不存在")
|
||||
email = _email(payload.get("email"))
|
||||
from app.models.member import SiteMember
|
||||
|
||||
account = db.scalar(select(SiteMember).where(SiteMember.email == email))
|
||||
linked = account.id if account is not None else None
|
||||
_ensure_unique(db, event.id, email, linked, row.id)
|
||||
row.site_member_id = linked
|
||||
_apply_registration(row, payload, _load_dates(event.meal_dates))
|
||||
db.commit()
|
||||
db.refresh(row)
|
||||
return _registration_body(row, reveal=True)
|
||||
|
||||
|
||||
def delete_registration(db, registration_id: int) -> None:
|
||||
row = db.get(TrainingRegistration, registration_id)
|
||||
if row is None:
|
||||
raise LookupError("报名不存在")
|
||||
db.delete(row)
|
||||
db.commit()
|
||||
|
||||
|
||||
def read_registration(db, registration_id: int) -> dict:
|
||||
row = db.get(TrainingRegistration, registration_id)
|
||||
if row is None:
|
||||
raise LookupError("报名不存在")
|
||||
return _registration_body(row, reveal=True)
|
||||
@@ -1,6 +1,6 @@
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from sqlalchemy import Boolean, DateTime, ForeignKey, String, Text, UniqueConstraint
|
||||
from sqlalchemy import Boolean, DateTime, ForeignKey, Integer, String, Text, UniqueConstraint, inspect, text
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from app.db import Base
|
||||
@@ -21,6 +21,7 @@ class AdminUser(Base):
|
||||
mobile_mask: Mapped[str] = mapped_column(String(32), nullable=False, default="")
|
||||
status: Mapped[str] = mapped_column(String(16), nullable=False, default="active")
|
||||
failed_login_count: Mapped[int] = mapped_column(nullable=False, default=0)
|
||||
credential_epoch: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default="0")
|
||||
locked_until: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, default=utcnow)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
@@ -77,3 +78,17 @@ class AdminRoleResource(Base):
|
||||
resource_id: Mapped[int] = mapped_column(
|
||||
ForeignKey("admin_resource.id", ondelete="CASCADE"), primary_key=True
|
||||
)
|
||||
|
||||
|
||||
def bump_admin_credentials(user: AdminUser) -> None:
|
||||
user.credential_epoch = int(user.credential_epoch or 0) + 1
|
||||
|
||||
|
||||
def ensure_admin_credential_column(db) -> None:
|
||||
bind = db.get_bind()
|
||||
if bind.dialect.name != "mysql":
|
||||
return
|
||||
names = {column["name"] for column in inspect(bind).get_columns("admin_user")}
|
||||
if "credential_epoch" not in names:
|
||||
db.execute(text("ALTER TABLE admin_user ADD COLUMN credential_epoch INT NOT NULL DEFAULT 0"))
|
||||
db.commit()
|
||||
@@ -111,6 +111,47 @@ class ValuationSuggestion(Base):
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, default=_now)
|
||||
|
||||
|
||||
COACH_WELCOME = (
|
||||
"我是估价模版智能体,专门帮你制作估价智能体要用的报告模版。"
|
||||
"可以上传历史 Word 或 PPT,也可以上传 pdf、表格和图片作参考。"
|
||||
"直接说要保留哪些章节、做成 Word 还是 PPT。"
|
||||
"整理好后下载到本地,你可以再改,然后回到模版列表里自己上传。"
|
||||
"这里不会把文件直接放进模版列表,也不回答具体估价问题。"
|
||||
)
|
||||
|
||||
|
||||
class ValuationCoachSession(Base):
|
||||
__tablename__ = "valuation_coach_session"
|
||||
__table_args__ = _mysql_args()
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
||||
owner_key: Mapped[str] = mapped_column(String(32), nullable=False, index=True)
|
||||
title: Mapped[str] = mapped_column(String(80), nullable=False, default="新会话")
|
||||
outline_name: Mapped[str] = mapped_column(String(80), nullable=False, default="")
|
||||
outline_format: Mapped[str] = mapped_column(String(8), nullable=False, default="")
|
||||
outline_text: Mapped[str] = mapped_column(_long_text(), nullable=False, default="")
|
||||
source_text: Mapped[str] = mapped_column(_long_text(), 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 ValuationCoachMessage(Base):
|
||||
__tablename__ = "valuation_coach_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="")
|
||||
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="")
|
||||
outline: Mapped[str] = mapped_column(_long_text(), nullable=False, default="")
|
||||
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":
|
||||
@@ -134,6 +175,16 @@ def ensure_valuation_columns(db) -> None:
|
||||
db.execute(
|
||||
text(f"ALTER TABLE {table} ADD COLUMN owner_key VARCHAR(32) NOT NULL DEFAULT ''")
|
||||
)
|
||||
tables = set(inspect(bind).get_table_names())
|
||||
if "valuation_coach_session" in tables:
|
||||
coach_columns = {column["name"] for column in inspect(bind).get_columns("valuation_coach_session")}
|
||||
if "title" not in coach_columns:
|
||||
db.execute(
|
||||
text(
|
||||
"ALTER TABLE valuation_coach_session "
|
||||
"ADD COLUMN title VARCHAR(80) NOT NULL DEFAULT '新会话'"
|
||||
)
|
||||
)
|
||||
for table, column in (
|
||||
("valuation_message", "content"),
|
||||
("valuation_message", "thought"),
|
||||
|
||||
@@ -2,6 +2,15 @@ import bcrypt
|
||||
from fastapi import HTTPException, status
|
||||
|
||||
PASSWORD_RULE = "密码至少 8 位,且同时包含字母和数字"
|
||||
MEMBER_PASSWORD_LIMIT = 10
|
||||
DEFAULT_MEMBER_PASSWORD = "123456"
|
||||
MEMBER_PASSWORD_RULE = "密码为 1 至 10 位,内容不限"
|
||||
|
||||
|
||||
def validate_member_password(password: str) -> None:
|
||||
text = password.strip() if isinstance(password, str) else ""
|
||||
if not text or len(text) > MEMBER_PASSWORD_LIMIT:
|
||||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=MEMBER_PASSWORD_RULE)
|
||||
|
||||
|
||||
def validate_password(password: str) -> None:
|
||||
|
||||
@@ -16,6 +16,7 @@ from app.models.rbac import (
|
||||
AdminRoleResource,
|
||||
AdminUser,
|
||||
AdminUserRole,
|
||||
bump_admin_credentials,
|
||||
utcnow,
|
||||
)
|
||||
from app.services.captcha import consume_captcha
|
||||
@@ -360,6 +361,7 @@ def change_own_password(db: Session, user_id: int, old_password: str, new_passwo
|
||||
_bad("旧密码错误")
|
||||
validate_password(new_password)
|
||||
user.password_hash = hash_password(new_password)
|
||||
bump_admin_credentials(user)
|
||||
user.updated_at = utcnow()
|
||||
commit_or_raise(db, "保存密码失败")
|
||||
return {"ok": True}
|
||||
@@ -485,6 +487,7 @@ def reset_user_password(db: Session, user_id: int, password: str) -> dict:
|
||||
_bad("用户不存在", status.HTTP_404_NOT_FOUND)
|
||||
validate_password(password)
|
||||
user.password_hash = hash_password(password)
|
||||
bump_admin_credentials(user)
|
||||
user.updated_at = utcnow()
|
||||
commit_or_raise(db, "保存密码失败")
|
||||
return {"ok": True}
|
||||
|
||||
@@ -0,0 +1,552 @@
|
||||
"""把历史文稿和对话整理成可下载的报告模版提纲。
|
||||
|
||||
估价模版智能体只产出章节或幻灯片的写作要求。下载文件由调用方交给用户本地修改,
|
||||
不写入模版列表。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import re
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
from docx import Document
|
||||
from pptx import Presentation
|
||||
|
||||
from app.services.valuation_context import IMAGE_EXCERPT
|
||||
|
||||
MAX_SECTIONS = 16
|
||||
MAX_SOURCE = 12000
|
||||
OUTLINE_LIMIT = 7500
|
||||
_CN = "一二三四五六七八九十"
|
||||
_SKIP = {
|
||||
"甘肃省房地产价格评估行业协会",
|
||||
"辅助文稿 · 不构成正式评估意见",
|
||||
"辅助文稿,不构成正式评估意见",
|
||||
"本成稿为辅助文稿,不构成正式评估意见。",
|
||||
"本回答仅供参考,不构成正式评估意见。",
|
||||
}
|
||||
_CHAPTER = re.compile(
|
||||
r"^(?:第\s*[0-9一二三四五六七八九十百]+\s*[章节篇部分]|[一二三四五六七八九十百零]+\s*[、..])\s*\S"
|
||||
)
|
||||
_SLIDE = re.compile(r"^第\s*\d+\s*页\s*$")
|
||||
_FACT = re.compile(r"\d[\d,,.]*|\d{4}\s*年|\d{1,2}\s*月|\d{1,2}\s*日|万元|元|㎡|平方米|亩|%|%")
|
||||
_NAME = re.compile(r"(?:模版|模板)?名称\s*(?:改成|改为|叫做|叫|是|为|:|:)\s*([^\s,。,;;]{1,40})")
|
||||
_DELETE = re.compile(r"(?:删除|删掉|去掉|不要)\s*第\s*([0-9一二三四五六七八九十]+)\s*[章节页]")
|
||||
_DELETE_QUOTED = re.compile(r"(?:删除|删掉|去掉)\s*[「“\"](.+?)[」”\"]")
|
||||
_ADD = re.compile(r"(?:增加|新增|加)(?:一)?(?:章|节|页)?\s*[:: ]\s*(.+)")
|
||||
_REQUIRE = re.compile(r"第\s*([0-9一二三四五六七八九十]+)\s*[章节页]\s*(?:要写|改成|改为|要求|写成)\s*(.+)")
|
||||
_LIST = re.compile(r"(?:要有|包括|分为|分成|章节(?:是|有)?)\s*(.+)")
|
||||
_FENCE = re.compile(r"```template\s*\n(.*?)```", re.IGNORECASE | re.DOTALL)
|
||||
_LEAD_NUM = re.compile(
|
||||
r"^(?:第\s*[0-9一二三四五六七八九十百]+\s*[章节篇部分]|[一二三四五六七八九十]+\s*[、..]|第\s*\d+\s*页)\s*"
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
class Section:
|
||||
title: str
|
||||
instruction: str
|
||||
|
||||
|
||||
@dataclass
|
||||
class Outline:
|
||||
name: str
|
||||
format: str
|
||||
sections: list[Section] = field(default_factory=list)
|
||||
|
||||
def render(self) -> str:
|
||||
lines = [f"名称:{self.name}", f"格式:{self.format}"]
|
||||
for index, section in enumerate(self.sections, start=1):
|
||||
if self.format == "pptx":
|
||||
lines.append(f"第{index}页 {section.title}")
|
||||
else:
|
||||
lines.append(_chapter_title(index, section.title))
|
||||
lines.append(section.instruction.strip())
|
||||
text = "\n".join(lines).strip()
|
||||
return text[:OUTLINE_LIMIT]
|
||||
|
||||
|
||||
@dataclass
|
||||
class TurnPlan:
|
||||
mode: str
|
||||
reply: str
|
||||
outline: Outline | None
|
||||
prompt: str
|
||||
source_text: str
|
||||
fallback: Outline | None
|
||||
|
||||
|
||||
def name_from_filename(filename: str) -> str:
|
||||
stem = filename.rsplit("/", 1)[-1].rsplit(".", 1)[0]
|
||||
stem = re.sub(r"(终稿|正式稿|送审稿|演示稿|汇报材料)$", "", stem).strip()
|
||||
stem = re.sub(r"\s+", "", stem)
|
||||
return (stem or "估价模版")[:40]
|
||||
|
||||
|
||||
def merge_source(existing: str, excerpts: list[tuple[str, str]]) -> str:
|
||||
blocks = [existing.strip()] if existing.strip() else []
|
||||
for name, body in excerpts:
|
||||
cleaned = body.strip()
|
||||
if not cleaned or cleaned == IMAGE_EXCERPT:
|
||||
continue
|
||||
header = f"【{name}】"
|
||||
if header in existing or header in "\n".join(blocks):
|
||||
continue
|
||||
blocks.append(f"{header}\n{cleaned}")
|
||||
return "\n\n".join(blocks)[:MAX_SOURCE]
|
||||
|
||||
|
||||
def outline_from_documents(excerpts: list[tuple[str, str, str]]) -> Outline | None:
|
||||
"""excerpts: (filename, extension, text)。取第一份 docx 或 pptx 的结构。"""
|
||||
chosen: tuple[str, str, str] | None = None
|
||||
for item in excerpts:
|
||||
if item[1] in {"docx", "pptx"} and item[2].strip():
|
||||
chosen = item
|
||||
break
|
||||
if chosen is None:
|
||||
return None
|
||||
filename, extension, text = chosen
|
||||
sections = sections_from_slides(text) if extension == "pptx" else sections_from_chapters(text)
|
||||
if not sections and text.strip():
|
||||
title = "正文结构"
|
||||
sections = [Section(title, instruction_for(title, text[:800]))]
|
||||
if not sections:
|
||||
return None
|
||||
return Outline(name=name_from_filename(filename), format=extension, sections=sections[:MAX_SECTIONS])
|
||||
|
||||
|
||||
def sections_from_slides(text: str) -> list[Section]:
|
||||
if not re.search(r"(?m)^第\s*\d+\s*页\s*$", text):
|
||||
return []
|
||||
sections: list[Section] = []
|
||||
for chunk in re.split(r"(?m)^第\s*\d+\s*页\s*$", text)[1:]:
|
||||
lines = _content_lines(chunk)
|
||||
if not lines:
|
||||
continue
|
||||
title = clean_title(lines[0])
|
||||
sections.append(Section(title, instruction_for(title, "\n".join(lines[1:]))))
|
||||
if len(sections) >= MAX_SECTIONS:
|
||||
break
|
||||
return sections
|
||||
|
||||
|
||||
def sections_from_chapters(text: str) -> list[Section]:
|
||||
found: list[Section] = []
|
||||
title = ""
|
||||
body: list[str] = []
|
||||
|
||||
def flush() -> None:
|
||||
if not title:
|
||||
return
|
||||
found.append(Section(title, instruction_for(title, "\n".join(body))))
|
||||
|
||||
for raw in text.splitlines():
|
||||
line = raw.strip()
|
||||
if not line or line in _SKIP or _SLIDE.match(line):
|
||||
continue
|
||||
if _CHAPTER.match(line) and len(line) <= 40:
|
||||
flush()
|
||||
title = clean_title(line)
|
||||
body = []
|
||||
if len(found) >= MAX_SECTIONS:
|
||||
break
|
||||
continue
|
||||
if title:
|
||||
body.append(line)
|
||||
flush()
|
||||
return found[:MAX_SECTIONS]
|
||||
|
||||
|
||||
def plan_turn(
|
||||
*,
|
||||
message: str,
|
||||
outline: Outline | None,
|
||||
source_text: str,
|
||||
excerpts: list[tuple[str, str, str]],
|
||||
) -> TurnPlan:
|
||||
text = message.strip()
|
||||
source = merge_source(source_text, [(name, body) for name, _ext, body in excerpts])
|
||||
file_outline = outline_from_documents(excerpts)
|
||||
previous = outline if outline and outline.sections else None
|
||||
base = file_outline or previous
|
||||
started = base is not None and bool(base.sections)
|
||||
before = base.render() if started else ""
|
||||
edited, recognized = apply_commands(base, text)
|
||||
if edited is not None:
|
||||
base = edited
|
||||
after = base.render() if base is not None and base.sections else ""
|
||||
freeform = bool(text) and not recognized
|
||||
if recognized and started and base is not None and not base.sections:
|
||||
reply = "这些章节已经去掉,当前没有可调整的提纲。可以再说「要有估价对象、估价方法」,或重新上传文稿。"
|
||||
return TurnPlan("local", reply, base, "", source, None)
|
||||
if file_outline is None and recognized and started and before and before == after:
|
||||
return TurnPlan("local", "没有找到要改的位置,当前提纲保持不变。", None, "", source, None)
|
||||
if file_outline is not None and not freeform:
|
||||
return _local_plan(base, source, lead="我按附件的结构")
|
||||
if recognized and base is not None and base.sections:
|
||||
return _local_plan(base, source, lead="已按你的说法")
|
||||
if recognized and (base is None or not base.sections):
|
||||
reply = "还没有可调整的提纲。请上传历史 docx 或 pptx,或直接说章节,例如「要有估价对象、估价方法、估价结果」。"
|
||||
return TurnPlan("local", reply, None, "", source, None)
|
||||
if file_outline is not None and freeform:
|
||||
return TurnPlan("model", "", None, model_prompt(text, file_outline, source), source, file_outline)
|
||||
if not text and file_outline is None:
|
||||
reply = "请输入要怎么整理模版,或上传一份历史文稿。"
|
||||
return TurnPlan("local", reply, outline if outline and outline.sections else None, "", source, None)
|
||||
return TurnPlan("model", "", None, model_prompt(text, outline, source), source, outline if outline and outline.sections else None)
|
||||
|
||||
|
||||
def apply_commands(outline: Outline | None, message: str) -> tuple[Outline | None, bool]:
|
||||
text = message.strip()
|
||||
if not text:
|
||||
return None, False
|
||||
recognized = False
|
||||
current = _copy(outline) if outline else None
|
||||
listed = _sections_from_request(text)
|
||||
if listed:
|
||||
recognized = True
|
||||
current = Outline(
|
||||
name=current.name if current else "估价模版",
|
||||
format=current.format if current else "docx",
|
||||
sections=listed,
|
||||
)
|
||||
pasted = _pasted_sections(text)
|
||||
if pasted:
|
||||
recognized = True
|
||||
current = Outline(
|
||||
name=current.name if current else "估价模版",
|
||||
format=current.format if current else "docx",
|
||||
sections=pasted,
|
||||
)
|
||||
fmt = _mentioned_format(text)
|
||||
if fmt:
|
||||
recognized = True
|
||||
if current is None:
|
||||
current = Outline(name="估价模版", format=fmt, sections=[])
|
||||
else:
|
||||
current.format = fmt
|
||||
found_name = _NAME.search(text)
|
||||
if found_name:
|
||||
recognized = True
|
||||
if current is None:
|
||||
current = Outline(name=found_name.group(1).strip()[:40], format="docx", sections=[])
|
||||
else:
|
||||
current.name = found_name.group(1).strip()[:40]
|
||||
if current is None:
|
||||
return None, recognized
|
||||
deleted = _DELETE.search(text) or _DELETE_QUOTED.search(text)
|
||||
if deleted:
|
||||
recognized = True
|
||||
if deleted.re is _DELETE:
|
||||
index = _ordinal(deleted.group(1))
|
||||
if index and 1 <= index <= len(current.sections):
|
||||
del current.sections[index - 1]
|
||||
else:
|
||||
needle = deleted.group(1).strip()
|
||||
current.sections = [item for item in current.sections if needle not in item.title]
|
||||
added = _ADD.search(text)
|
||||
if added and "第" not in added.group(0)[:2]:
|
||||
recognized = True
|
||||
title, instruction = _split_requirement(added.group(1))
|
||||
if len(current.sections) < MAX_SECTIONS:
|
||||
current.sections.append(Section(clean_title(title), instruction or instruction_for(title, "")))
|
||||
required = _REQUIRE.search(text)
|
||||
if required:
|
||||
recognized = True
|
||||
index = _ordinal(required.group(1))
|
||||
if index and 1 <= index <= len(current.sections):
|
||||
current.sections[index - 1].instruction = _as_instruction(required.group(2).strip())
|
||||
if not current.sections:
|
||||
return (current if recognized else None), recognized
|
||||
return current, recognized
|
||||
|
||||
|
||||
def model_prompt(message: str, outline: Outline | None, source_text: str) -> str:
|
||||
current = outline.render() if outline and outline.sections else "尚无"
|
||||
source = (source_text or "无").strip()[:4000]
|
||||
return "\n".join(
|
||||
[
|
||||
"你是估价模版智能体,只帮用户整理报告模版提纲,不回答估价问题,不写正式报告,不编造数据。",
|
||||
"先用一两句中文说明这次怎么调整。然后单独给出完整提纲,放在 ```template 代码块中。",
|
||||
"代码块第一行写「名称:」,第二行写「格式:docx」或「格式:pptx」。",
|
||||
"Word 每一章用「一、」「二、」单独成行作标题,下一行只写这一章要回答什么。",
|
||||
"PPT 每一页用「第1页 标题」单独成行,下一行只写这一页要回答什么。",
|
||||
"每条要求都写明没有依据时写「待补充」,禁止照抄历史文稿中的数字、日期、价格、面积和名称。",
|
||||
f"【当前提纲】\n{current}",
|
||||
f"【历史文稿摘录】\n{source}",
|
||||
f"【用户要求】\n{message.strip() or '请按附件整理成模版'}",
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
def finish_model_answer(raw: str, *, fallback: Outline | None) -> tuple[str, Outline | None]:
|
||||
prose, block = split_coach_answer(raw)
|
||||
parsed = parse_outline_block(block) if block else None
|
||||
if parsed and parsed.sections:
|
||||
lead = prose.strip()
|
||||
if len(lead) > 180:
|
||||
lead = ""
|
||||
reply = lead or summary(parsed, lead="已按对话")
|
||||
if "下载后可以自己修改" not in reply:
|
||||
reply = f"{reply}\n{summary(parsed, lead='当前提纲')}"
|
||||
return reply.strip(), parsed
|
||||
if fallback and fallback.sections:
|
||||
return summary(fallback, lead="我按已有材料"), fallback
|
||||
return "没能整理出模版提纲。可以上传 docx 或 pptx,或直接说要有哪些章节。", None
|
||||
|
||||
|
||||
def split_coach_answer(raw: str) -> tuple[str, str]:
|
||||
match = _FENCE.search(raw or "")
|
||||
if match:
|
||||
prose = (raw[: match.start()] + raw[match.end() :]).strip()
|
||||
return prose, match.group(1).strip()
|
||||
parsed = parse_outline_block(raw or "")
|
||||
if parsed and parsed.sections:
|
||||
return "", raw.strip()
|
||||
return (raw or "").strip(), ""
|
||||
|
||||
|
||||
def parse_outline_block(text: str) -> Outline | None:
|
||||
name = "估价模版"
|
||||
fmt = ""
|
||||
sections: list[Section] = []
|
||||
title = ""
|
||||
body: list[str] = []
|
||||
|
||||
def flush() -> None:
|
||||
if title:
|
||||
sections.append(Section(clean_title(title), _as_instruction(" ".join(body)) if body else instruction_for(title, "")))
|
||||
|
||||
for raw in (text or "").splitlines():
|
||||
line = raw.strip()
|
||||
if not line or line.startswith("```"):
|
||||
continue
|
||||
if line.startswith("名称:") or line.startswith("名称:"):
|
||||
flush()
|
||||
title = ""
|
||||
body = []
|
||||
name = line.split(":", 1)[-1].split(":", 1)[-1].strip()[:40] or name
|
||||
continue
|
||||
if line.startswith("格式:") or line.startswith("格式:"):
|
||||
flush()
|
||||
title = ""
|
||||
body = []
|
||||
value = line.split(":", 1)[-1].split(":", 1)[-1].strip().lower()
|
||||
if value in {"docx", "pptx"}:
|
||||
fmt = value
|
||||
continue
|
||||
slide = re.match(r"^第\s*(\d+)\s*页\s*(.+)$", line)
|
||||
chapter = _CHAPTER.match(line) and len(line) <= 40
|
||||
if slide or chapter:
|
||||
flush()
|
||||
title = slide.group(2) if slide else line
|
||||
if not fmt:
|
||||
fmt = "pptx" if slide else "docx"
|
||||
body = []
|
||||
continue
|
||||
if title:
|
||||
body.append(line)
|
||||
flush()
|
||||
if not sections:
|
||||
return None
|
||||
return Outline(name=name or "估价模版", format=fmt or "docx", sections=sections[:MAX_SECTIONS])
|
||||
|
||||
|
||||
def summary(outline: Outline, *, lead: str) -> str:
|
||||
kind = "PPT" if outline.format == "pptx" else "Word"
|
||||
unit = "页" if outline.format == "pptx" else "章"
|
||||
lines = [f"{lead}已整理为{kind}模版「{outline.name}」,共 {len(outline.sections)} {unit}:"]
|
||||
for index, section in enumerate(outline.sections, start=1):
|
||||
lines.append(f"{index}. {section.title}")
|
||||
lines.append("可以继续调整,例如「改成 PPT」「删除第2章」或「第1章要写坐落和用途」。")
|
||||
lines.append("下载后可以自己修改,再从模版列表上传。这里不会直接加入模版列表。")
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def prose_ready(buffer: str) -> str:
|
||||
"""流式输出时先放出代码块之前的说明。"""
|
||||
if "```" not in buffer:
|
||||
hold = len(buffer) - len(buffer.rstrip("`"))
|
||||
return buffer[:-hold] if hold else buffer
|
||||
return buffer[: buffer.find("```")]
|
||||
|
||||
|
||||
def build_template_file(outline: Outline) -> tuple[bytes, str, str]:
|
||||
if outline.format == "pptx":
|
||||
return (
|
||||
_build_pptx(outline),
|
||||
"application/vnd.openxmlformats-officedocument.presentationml.presentation",
|
||||
f"{outline.name}.pptx",
|
||||
)
|
||||
return (
|
||||
_build_docx(outline),
|
||||
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
||||
f"{outline.name}.docx",
|
||||
)
|
||||
|
||||
|
||||
def instruction_for(title: str, body: str) -> str:
|
||||
hints = _hint_lines(body)
|
||||
text = f"写明与「{title}」有关的事实和依据。不要照抄历史文稿中的数字、日期、价格、面积和名称;没有依据时写「待补充」。"
|
||||
if hints:
|
||||
text += "可涉及:" + "、".join(hints) + "。"
|
||||
return text[:400]
|
||||
|
||||
|
||||
def clean_title(title: str) -> str:
|
||||
bare = _LEAD_NUM.sub("", title.strip())
|
||||
cleaned = _FACT.sub("", bare)
|
||||
cleaned = re.sub(r"\s+", "", cleaned).strip(",。、::;;")
|
||||
return (cleaned or "未命名")[:40]
|
||||
|
||||
|
||||
def _local_plan(outline: Outline, source: str, *, lead: str) -> TurnPlan:
|
||||
if not outline.sections:
|
||||
reply = "还没有可调整的提纲。请上传历史 docx 或 pptx,或直接说章节,例如「要有估价对象、估价方法、估价结果」。"
|
||||
return TurnPlan("local", reply, None, "", source, None)
|
||||
return TurnPlan("local", summary(outline, lead=lead), outline, "", source, None)
|
||||
|
||||
|
||||
def _copy(outline: Outline) -> Outline:
|
||||
return Outline(
|
||||
name=outline.name,
|
||||
format=outline.format if outline.format in {"docx", "pptx"} else "docx",
|
||||
sections=[Section(item.title, item.instruction) for item in outline.sections],
|
||||
)
|
||||
|
||||
|
||||
def _chapter_title(index: int, title: str) -> str:
|
||||
if re.match(r"^[一二三四五六七八九十]+、", title):
|
||||
return title
|
||||
return f"{_cn(index)}、{title}"
|
||||
|
||||
|
||||
def _cn(index: int) -> str:
|
||||
if index <= 10:
|
||||
return "十" if index == 10 else _CN[index - 1]
|
||||
if index < 20:
|
||||
return "十" + _CN[index - 11]
|
||||
if index == 20:
|
||||
return "二十"
|
||||
return str(index)
|
||||
|
||||
|
||||
def _content_lines(chunk: str) -> list[str]:
|
||||
lines = []
|
||||
for raw in chunk.splitlines():
|
||||
line = raw.strip()
|
||||
if not line or line in _SKIP:
|
||||
continue
|
||||
line = re.sub(r"^备注[::]\s*", "", line).strip()
|
||||
if line:
|
||||
lines.append(line)
|
||||
return lines
|
||||
|
||||
|
||||
def _hint_lines(body: str) -> list[str]:
|
||||
hints: list[str] = []
|
||||
for raw in body.splitlines():
|
||||
line = re.sub(r"^[-•·]\s*", "", raw.strip())
|
||||
line = re.sub(r"^备注[::]\s*", "", line)
|
||||
if not line or line in _SKIP:
|
||||
continue
|
||||
cleaned = _FACT.sub("", line)
|
||||
cleaned = re.sub(r"\s+", "", cleaned).strip(",。;;、,.")
|
||||
if not (2 <= len(cleaned) <= 18):
|
||||
continue
|
||||
if cleaned not in hints:
|
||||
hints.append(cleaned)
|
||||
if len(hints) >= 4:
|
||||
break
|
||||
return hints
|
||||
|
||||
|
||||
def _mentioned_format(message: str) -> str:
|
||||
hits: list[tuple[int, str]] = []
|
||||
lowered = message.lower()
|
||||
for word, fmt in (("ppt", "pptx"), ("幻灯片", "pptx"), ("演示文稿", "pptx"), ("word", "docx")):
|
||||
index = lowered.find(word) if word in {"ppt", "word"} else message.find(word)
|
||||
if index >= 0:
|
||||
hits.append((index, fmt))
|
||||
if not hits:
|
||||
return ""
|
||||
hits.sort()
|
||||
return hits[-1][1]
|
||||
|
||||
|
||||
def _sections_from_request(message: str) -> list[Section]:
|
||||
match = _LIST.search(message)
|
||||
if match is None:
|
||||
return []
|
||||
parts = re.split(r"[、,,和及/]", match.group(1))
|
||||
titles = []
|
||||
for part in parts:
|
||||
title = clean_title(part.strip(" 。."))
|
||||
if title and title not in titles and title != "未命名":
|
||||
titles.append(title)
|
||||
if len(titles) < 2:
|
||||
return []
|
||||
return [Section(title, instruction_for(title, "")) for title in titles[:MAX_SECTIONS]]
|
||||
|
||||
|
||||
def _pasted_sections(message: str) -> list[Section]:
|
||||
if message.count("\n") < 1:
|
||||
return []
|
||||
if message.lower().count("第") and re.search(r"(?m)^第\s*\d+\s*页", message):
|
||||
return sections_from_slides(message)
|
||||
chapters = sections_from_chapters(message)
|
||||
return chapters if len(chapters) >= 2 else []
|
||||
|
||||
|
||||
def _split_requirement(text: str) -> tuple[str, str]:
|
||||
if ",要求" in text:
|
||||
title, instruction = text.split(",要求", 1)
|
||||
return title.strip(), _as_instruction(instruction.strip())
|
||||
if ":" in text:
|
||||
title, instruction = text.split(":", 1)
|
||||
return title.strip(), _as_instruction(instruction.strip())
|
||||
return text.strip(), ""
|
||||
|
||||
|
||||
def _as_instruction(text: str) -> str:
|
||||
cleaned = text.strip(" 。")
|
||||
if "待补充" not in cleaned:
|
||||
cleaned += "。没有依据时写「待补充」。"
|
||||
return cleaned[:400]
|
||||
|
||||
|
||||
def _ordinal(token: str) -> int | None:
|
||||
if token.isdigit():
|
||||
value = int(token)
|
||||
return value if value > 0 else None
|
||||
if token == "十":
|
||||
return 10
|
||||
if len(token) == 1 and token in _CN:
|
||||
return _CN.index(token) + 1
|
||||
if token.startswith("十") and len(token) == 2 and token[1] in _CN:
|
||||
return 10 + _CN.index(token[1]) + 1
|
||||
return None
|
||||
|
||||
|
||||
def _build_docx(outline: Outline) -> bytes:
|
||||
document = Document()
|
||||
document.add_heading(outline.name, level=1)
|
||||
for index, section in enumerate(outline.sections, start=1):
|
||||
document.add_heading(_chapter_title(index, section.title), level=2)
|
||||
document.add_paragraph(section.instruction)
|
||||
buffer = io.BytesIO()
|
||||
document.save(buffer)
|
||||
return buffer.getvalue()
|
||||
|
||||
|
||||
def _build_pptx(outline: Outline) -> bytes:
|
||||
presentation = Presentation()
|
||||
layout = presentation.slide_layouts[1]
|
||||
for section in outline.sections:
|
||||
slide = presentation.slides.add_slide(layout)
|
||||
slide.shapes.title.text = section.title
|
||||
slide.placeholders[1].text = section.instruction
|
||||
buffer = io.BytesIO()
|
||||
presentation.save(buffer)
|
||||
return buffer.getvalue()
|
||||
@@ -183,6 +183,19 @@ def test_portal_member_needs_agent_flag(client: TestClient):
|
||||
)
|
||||
assert disabled.status_code == 200
|
||||
assert client.get("/api/site/auth/agent/me", headers=agent_headers).status_code == 401
|
||||
assert client.post("/api/site/member/valuation/sessions", headers=agent_headers).status_code == 401
|
||||
|
||||
restored = client.put(
|
||||
f"/api/admin/site-members/{member_id}",
|
||||
headers=headers,
|
||||
json={"email": member_email, "status": "active", "agentEnabled": True, "password": "Newpass12"},
|
||||
)
|
||||
assert restored.status_code == 200, restored.text
|
||||
assert client.get("/api/site/auth/agent/me", headers=agent_headers).status_code == 401
|
||||
renewed = client.post("/api/site/auth/agent-login", json={"username": member_email, "password": "Newpass12"})
|
||||
assert renewed.status_code == 200, renewed.text
|
||||
fresh = {"Authorization": f"Bearer {renewed.json()['accessToken']}"}
|
||||
assert client.get("/api/site/auth/agent/me", headers=fresh).status_code == 200
|
||||
|
||||
|
||||
def test_builtin_admin_is_listed_with_site_members(client: TestClient):
|
||||
@@ -226,6 +239,21 @@ def test_builtin_admin_is_listed_with_site_members(client: TestClient):
|
||||
assert me.status_code == 200
|
||||
assert me.json()["canManage"] is False
|
||||
assert me.json()["username"] == username
|
||||
paused = client.put(
|
||||
f"/api/admin/site-members/staff-{user_id}",
|
||||
headers=headers,
|
||||
json={"email": username, "displayName": "同步前", "status": "active", "agentEnabled": False},
|
||||
)
|
||||
assert paused.status_code == 200, paused.text
|
||||
old_headers = {"Authorization": f"Bearer {logged_in.json()['accessToken']}"}
|
||||
assert client.get("/api/site/auth/agent/me", headers=old_headers).status_code == 401
|
||||
resumed = client.put(
|
||||
f"/api/admin/site-members/staff-{user_id}",
|
||||
headers=headers,
|
||||
json={"email": username, "displayName": "同步前", "status": "active", "agentEnabled": True},
|
||||
)
|
||||
assert resumed.status_code == 200, resumed.text
|
||||
assert client.get("/api/site/auth/agent/me", headers=old_headers).status_code == 200
|
||||
_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
|
||||
@@ -239,6 +267,7 @@ def test_builtin_admin_is_listed_with_site_members(client: TestClient):
|
||||
assert updated.status_code == 200, updated.text
|
||||
assert updated.json()["displayName"] == "同步后"
|
||||
assert updated.json()["agentEnabled"] is False
|
||||
assert client.get("/api/site/auth/agent/me", headers=old_headers).status_code == 401
|
||||
db = _session(client)
|
||||
try:
|
||||
stored = db.get(AdminUser, user_id)
|
||||
|
||||
@@ -17,7 +17,7 @@ _PLACEHOLDERS = (
|
||||
"政策法规整理中",
|
||||
"数据看板整理中",
|
||||
"估价师、机构与公众入口即将开放",
|
||||
"报告查询、报告审核与投诉举报入口即将开放",
|
||||
"报告查询与投诉举报入口即将开放",
|
||||
"协会荣誉与资质整理中",
|
||||
"会员单位名录整理中",
|
||||
"办公地址整理中",
|
||||
@@ -560,8 +560,7 @@ def _clear_entries(client, headers) -> None:
|
||||
json={
|
||||
"links": [
|
||||
{"key": "reportQuery", "label": "报告查询", "url": "/reports/query", "visible": False, "sortOrder": 0},
|
||||
{"key": "reportReview", "label": "报告审核", "url": "/reports/review", "visible": False, "sortOrder": 1},
|
||||
{"key": "complaint", "label": "投诉举报", "url": "", "visible": False, "sortOrder": 2},
|
||||
{"key": "complaint", "label": "投诉举报", "url": "", "visible": False, "sortOrder": 1},
|
||||
]
|
||||
},
|
||||
)
|
||||
@@ -582,7 +581,7 @@ def test_public_home_exposes_audience_hot_links_and_shortcut_menu(client):
|
||||
empty = client.get("/api/site/home")
|
||||
assert empty.status_code == 200, empty.text
|
||||
assert "估价师、机构与公众入口即将开放" in empty.text
|
||||
assert "报告查询、报告审核与投诉举报入口即将开放" in empty.text
|
||||
assert "报告查询与投诉举报入口即将开放" in empty.text
|
||||
assert empty.json()["shortcutMenu"]["items"] == [
|
||||
{"label": "首页", "url": "/", "navigation": "sameWindow"}
|
||||
]
|
||||
@@ -637,19 +636,12 @@ def test_public_home_exposes_audience_hot_links_and_shortcut_menu(client):
|
||||
"visible": True,
|
||||
"sortOrder": 1,
|
||||
},
|
||||
{
|
||||
"key": "reportReview",
|
||||
"label": "报告审核",
|
||||
"url": "https://example.com/review",
|
||||
"visible": False,
|
||||
"sortOrder": 2,
|
||||
},
|
||||
{
|
||||
"key": "complaint",
|
||||
"label": "投诉举报",
|
||||
"url": "",
|
||||
"visible": False,
|
||||
"sortOrder": 3,
|
||||
"sortOrder": 2,
|
||||
},
|
||||
]
|
||||
},
|
||||
@@ -677,7 +669,7 @@ def test_public_home_exposes_audience_hot_links_and_shortcut_menu(client):
|
||||
body = home.json()
|
||||
text = home.text
|
||||
assert "估价师、机构与公众入口即将开放" not in text
|
||||
assert "报告查询、报告审核与投诉举报入口即将开放" not in text
|
||||
assert "报告查询与投诉举报入口即将开放" not in text
|
||||
assert "不展示的机构入口" not in text
|
||||
assert "真伪" not in text
|
||||
assert "authenticity" not in text
|
||||
@@ -770,7 +762,7 @@ def test_public_home_lists_members_without_links_and_keeps_empty_honors(client):
|
||||
headers=headers,
|
||||
json={
|
||||
"intervalSeconds": 5,
|
||||
"items": [{"imageFileId": honor_id, "sortOrder": 1}],
|
||||
"items": [{"imageFileId": honor_id, "caption": "示范表彰", "sortOrder": 1}],
|
||||
},
|
||||
)
|
||||
assert shown.status_code == 200, shown.text
|
||||
@@ -778,6 +770,7 @@ def test_public_home_lists_members_without_links_and_keeps_empty_honors(client):
|
||||
assert with_honor.status_code == 200, with_honor.text
|
||||
assert "协会荣誉与资质整理中" not in with_honor.text
|
||||
honor_items = with_honor.json()["honors"]["items"]
|
||||
assert honor_items[0]["caption"] == "示范表彰"
|
||||
assert with_honor.json()["honors"]["intervalSeconds"] == 5
|
||||
downloaded = httpx.get(honor_items[0]["imageUrl"], timeout=5.0, follow_redirects=True)
|
||||
assert downloaded.status_code == 200
|
||||
|
||||
@@ -0,0 +1,286 @@
|
||||
"""会员服务:外链、协会会员档案、会员资讯、培训报名。"""
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import uuid
|
||||
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from app.core.config import get_settings
|
||||
from app.core.security import create_access_token
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client(monkeypatch):
|
||||
monkeypatch.setenv("JWT_SECRET", "test-secret-must-be-32-characters!")
|
||||
monkeypatch.setenv("API_PAYLOAD_ENCRYPT", "false")
|
||||
key = base64.b64encode(hashlib.sha256(b"membership-field-key").digest()).decode("ascii")
|
||||
monkeypatch.setenv("FIELD_AES_KEY", key)
|
||||
get_settings.cache_clear()
|
||||
if not get_settings().database_url.strip():
|
||||
pytest.skip("DATABASE_URL 为空")
|
||||
from app.main import create_app
|
||||
|
||||
with TestClient(create_app()) as api:
|
||||
yield api
|
||||
get_settings.cache_clear()
|
||||
|
||||
|
||||
def _staff() -> dict[str, str]:
|
||||
return {"Authorization": f"Bearer {create_access_token('1', 'staff')}"}
|
||||
|
||||
|
||||
def _profile(email: str, **extra) -> dict:
|
||||
body = {
|
||||
"email": email,
|
||||
"password": "Member123",
|
||||
"kind": "individual",
|
||||
"personName": "张三",
|
||||
"membershipStatus": "active",
|
||||
"feeStatus": "unpaid",
|
||||
"mobile": "13800138000",
|
||||
"idCard": "620102199001011234",
|
||||
"appraiserRegNo": "1234567890",
|
||||
}
|
||||
body.update(extra)
|
||||
return body
|
||||
|
||||
|
||||
def _registration(**extra) -> dict:
|
||||
body = {
|
||||
"region": "甘肃省兰州市",
|
||||
"orgName": "示例估价公司",
|
||||
"personName": "李四",
|
||||
"gender": "female",
|
||||
"position": "估价师",
|
||||
"idCard": "620102199202023214",
|
||||
"mobile": "13900139000",
|
||||
"appraiserRegNo": "1098765432",
|
||||
"email": "attendee@example.com",
|
||||
"lodging": "association",
|
||||
"roomStandard": True,
|
||||
"standardCount": 1,
|
||||
"dine": True,
|
||||
"mealDates": ["7月29日", "8月1日"],
|
||||
}
|
||||
body.update(extra)
|
||||
return body
|
||||
|
||||
|
||||
def test_member_notices_follow_column_articles(client: TestClient):
|
||||
staff = _staff()
|
||||
created = []
|
||||
draft_title = f"章程草稿{uuid.uuid4().hex[:6]}"
|
||||
try:
|
||||
empty = client.get("/api/site/about/articles/member_notices")
|
||||
assert empty.status_code == 200, empty.text
|
||||
draft = client.post(
|
||||
"/api/admin/home/articles",
|
||||
headers=staff,
|
||||
json={
|
||||
"category": "member_notices",
|
||||
"title": draft_title,
|
||||
"published": False,
|
||||
"bodyHtml": "<p>未发布</p>",
|
||||
"attachmentFileIds": [],
|
||||
},
|
||||
)
|
||||
assert draft.status_code == 200, draft.text
|
||||
created.append(draft.json()["id"])
|
||||
published = client.post(
|
||||
"/api/admin/home/articles",
|
||||
headers=staff,
|
||||
json={
|
||||
"category": "member_notices",
|
||||
"title": f"协会章程{uuid.uuid4().hex[:6]}",
|
||||
"published": True,
|
||||
"bodyHtml": "<p>会员权利</p><script>alert(1)</script>",
|
||||
"attachmentFileIds": [],
|
||||
},
|
||||
)
|
||||
assert published.status_code == 200, published.text
|
||||
created.append(published.json()["id"])
|
||||
listed = client.get("/api/site/about/articles/member_notices")
|
||||
titles = [item["title"] for item in listed.json()["items"]]
|
||||
assert published.json()["id"]
|
||||
assert any(item["id"] == published.json()["id"] for item in listed.json()["items"])
|
||||
assert draft_title not in titles
|
||||
detail = client.get(f"/api/site/home/articles/{published.json()['id']}")
|
||||
assert "会员权利" in detail.text
|
||||
assert "script" not in detail.text
|
||||
finally:
|
||||
for item_id in created:
|
||||
client.delete(f"/api/admin/home/articles/{item_id}", headers=staff)
|
||||
|
||||
|
||||
def test_new_member_password_is_short_and_optional(client: TestClient):
|
||||
staff = _staff()
|
||||
stamp = uuid.uuid4().hex[:8]
|
||||
simple = f"simple-{stamp}@example.com"
|
||||
letters = f"letters-{stamp}@example.com"
|
||||
blank = f"blank-{stamp}@example.com"
|
||||
created_ids: list[int] = []
|
||||
try:
|
||||
short = client.post(
|
||||
"/api/admin/membership/profiles",
|
||||
headers=staff,
|
||||
json=_profile(simple, password="123456"),
|
||||
)
|
||||
assert short.status_code == 200, short.text
|
||||
created_ids.append(short.json()["id"])
|
||||
signed = client.post("/api/site/auth/login", json={"email": simple, "password": "123456"})
|
||||
assert signed.status_code == 200, signed.text
|
||||
|
||||
free = client.post(
|
||||
"/api/admin/membership/profiles",
|
||||
headers=staff,
|
||||
json=_profile(letters, password="abc"),
|
||||
)
|
||||
assert free.status_code == 200, free.text
|
||||
created_ids.append(free.json()["id"])
|
||||
signed = client.post("/api/site/auth/login", json={"email": letters, "password": "abc"})
|
||||
assert signed.status_code == 200, signed.text
|
||||
|
||||
too_long = client.post(
|
||||
"/api/admin/membership/profiles",
|
||||
headers=staff,
|
||||
json=_profile(f"long-{stamp}@example.com", password="12345678901"),
|
||||
)
|
||||
assert too_long.status_code == 400
|
||||
assert "10" in too_long.text
|
||||
|
||||
omitted = _profile(blank)
|
||||
omitted.pop("password")
|
||||
defaulted = client.post("/api/admin/membership/profiles", headers=staff, json=omitted)
|
||||
assert defaulted.status_code == 200, defaulted.text
|
||||
created_ids.append(defaulted.json()["id"])
|
||||
signed = client.post("/api/site/auth/login", json={"email": blank, "password": "123456"})
|
||||
assert signed.status_code == 200, signed.text
|
||||
|
||||
reset = client.put(
|
||||
f"/api/admin/membership/profiles/{created_ids[-1]}",
|
||||
headers=staff,
|
||||
json=_profile(blank, password="8888"),
|
||||
)
|
||||
assert reset.status_code == 200, reset.text
|
||||
signed = client.post("/api/site/auth/login", json={"email": blank, "password": "8888"})
|
||||
assert signed.status_code == 200, signed.text
|
||||
finally:
|
||||
for profile_id in created_ids:
|
||||
client.delete(f"/api/admin/membership/profiles/{profile_id}", headers=staff)
|
||||
|
||||
|
||||
def test_profile_syncs_portal_account_and_training_meal_dates_are_multi_select(client: TestClient):
|
||||
staff = _staff()
|
||||
stamp = uuid.uuid4().hex[:8]
|
||||
email = f"member-{stamp}@example.com"
|
||||
other = f"other-{stamp}@example.com"
|
||||
profile_id = None
|
||||
other_id = None
|
||||
event_id = None
|
||||
try:
|
||||
created = client.post("/api/admin/membership/profiles", headers=staff, json=_profile(email))
|
||||
assert created.status_code == 200, created.text
|
||||
profile_id = created.json()["id"]
|
||||
assert created.json()["idCard"] == "620102199001011234"
|
||||
listed = client.get("/api/admin/membership/profiles", headers=staff, params={"keyword": email})
|
||||
assert listed.status_code == 200, listed.text
|
||||
assert "620102199001011234" not in listed.text
|
||||
assert "**********" in listed.text
|
||||
|
||||
login = client.post("/api/site/auth/login", json={"email": email, "password": "Member123"})
|
||||
assert login.status_code == 200, login.text
|
||||
token = {"Authorization": f"Bearer {login.json()['accessToken']}"}
|
||||
own = client.get("/api/site/membership/profile", headers=token)
|
||||
assert own.status_code == 200, own.text
|
||||
assert own.json()["profile"]["personName"] == "张三"
|
||||
stranger = client.get("/api/site/membership/profile")
|
||||
assert stranger.status_code == 401
|
||||
|
||||
again = client.post(
|
||||
"/api/admin/membership/profiles",
|
||||
headers=staff,
|
||||
json=_profile(email, personName="不应再建"),
|
||||
)
|
||||
assert again.status_code == 400
|
||||
assert "已有会员档案" in again.text
|
||||
|
||||
event = client.post(
|
||||
"/api/admin/membership/events",
|
||||
headers=staff,
|
||||
json={
|
||||
"title": f"估价会议{stamp}",
|
||||
"place": "兰州",
|
||||
"startsOn": "2026-07-29",
|
||||
"endsOn": "2026-07-30",
|
||||
"quota": 1,
|
||||
"published": True,
|
||||
"mealNote": "午餐自助餐80元/位",
|
||||
"mealDates": ["7月29日", "8月1日"],
|
||||
"payeeName": "甘肃省房地产价格评估行业协会",
|
||||
"bankName": "招商银行兰州中央广场支行",
|
||||
"bankAccount": "9319000000000000",
|
||||
"bodyHtml": "<p>会议通知</p>",
|
||||
},
|
||||
)
|
||||
assert event.status_code == 200, event.text
|
||||
event_id = event.json()["id"]
|
||||
assert event.json()["mealDates"] == ["7月29日", "8月1日"]
|
||||
|
||||
hidden = client.get("/api/site/membership/events")
|
||||
assert any(item["id"] == event_id for item in hidden.json()["items"])
|
||||
|
||||
bad_date = client.post(
|
||||
f"/api/site/membership/events/{event_id}/registrations",
|
||||
headers=token,
|
||||
json=_registration(email=email, mealDates=["7月30日"]),
|
||||
)
|
||||
assert bad_date.status_code == 400
|
||||
assert "用餐日期" in bad_date.text
|
||||
|
||||
submitted = client.post(
|
||||
f"/api/site/membership/events/{event_id}/registrations",
|
||||
headers=token,
|
||||
json=_registration(email=email, personName="张三", mealDates=["8月1日", "7月29日"]),
|
||||
)
|
||||
assert submitted.status_code == 200, submitted.text
|
||||
assert submitted.json()["mealDates"] == ["8月1日", "7月29日"]
|
||||
|
||||
mine = client.get("/api/site/membership/registrations", headers=token)
|
||||
assert mine.status_code == 200, mine.text
|
||||
assert mine.json()["items"][0]["eventId"] == event_id
|
||||
|
||||
other_profile = client.post("/api/admin/membership/profiles", headers=staff, json=_profile(other, personName="王五"))
|
||||
assert other_profile.status_code == 200, other_profile.text
|
||||
other_id = other_profile.json()["id"]
|
||||
other_login = client.post("/api/site/auth/login", json={"email": other, "password": "Member123"})
|
||||
other_token = {"Authorization": f"Bearer {other_login.json()['accessToken']}"}
|
||||
full = client.post(
|
||||
f"/api/site/membership/events/{event_id}/registrations",
|
||||
headers=other_token,
|
||||
json=_registration(email=other, personName="王五"),
|
||||
)
|
||||
assert full.status_code == 400
|
||||
assert "名额已满" in full.text
|
||||
other_mine = client.get("/api/site/membership/registrations", headers=other_token)
|
||||
assert other_mine.json()["items"] == []
|
||||
|
||||
roster = client.get(f"/api/admin/membership/events/{event_id}/registrations", headers=staff)
|
||||
assert roster.status_code == 200, roster.text
|
||||
assert len(roster.json()["items"]) == 1
|
||||
assert "620102199202023214" not in roster.text
|
||||
finally:
|
||||
if event_id:
|
||||
client.delete(f"/api/admin/membership/events/{event_id}", headers=staff)
|
||||
if profile_id:
|
||||
client.delete(f"/api/admin/membership/profiles/{profile_id}", headers=staff)
|
||||
if other_id:
|
||||
client.delete(f"/api/admin/membership/profiles/{other_id}", headers=staff)
|
||||
for address in (email, other):
|
||||
listed = client.get("/api/admin/site-members", headers=staff, params={"email": address, "current": 1, "size": 10})
|
||||
if listed.status_code != 200:
|
||||
continue
|
||||
for row in listed.json().get("records") or []:
|
||||
if row.get("email") == address:
|
||||
client.delete(f"/api/admin/site-members/{row['id']}", headers=staff)
|
||||
@@ -1,4 +1,4 @@
|
||||
"""报告备案对照,以及首页报告查询、报告审核固定打开站内页。"""
|
||||
"""报告备案对照,以及首页报告查询固定打开站内页。"""
|
||||
|
||||
from uuid import uuid4
|
||||
|
||||
@@ -115,8 +115,7 @@ def test_hot_links_open_report_pages_on_site(client: TestClient):
|
||||
before = client.get("/api/admin/home", headers=staff).json()["hotLinks"]["links"]
|
||||
hidden = [
|
||||
{"key": "reportQuery", "label": "报告查询", "url": "/reports/query", "visible": False, "sortOrder": 0},
|
||||
{"key": "reportReview", "label": "报告审核", "url": "/reports/review", "visible": False, "sortOrder": 1},
|
||||
{"key": "complaint", "label": "投诉举报", "url": "", "visible": False, "sortOrder": 2},
|
||||
{"key": "complaint", "label": "投诉举报", "url": "", "visible": False, "sortOrder": 1},
|
||||
]
|
||||
try:
|
||||
saved = client.put(
|
||||
@@ -124,26 +123,19 @@ def test_hot_links_open_report_pages_on_site(client: TestClient):
|
||||
headers=staff,
|
||||
json={
|
||||
"links": [
|
||||
{
|
||||
"key": "reportReview",
|
||||
"label": "辅助审核",
|
||||
"url": "https://example.com/review",
|
||||
"visible": True,
|
||||
"sortOrder": 0,
|
||||
},
|
||||
{
|
||||
"key": "complaint",
|
||||
"label": "投诉举报",
|
||||
"url": "https://example.com/complaint",
|
||||
"visible": True,
|
||||
"sortOrder": 1,
|
||||
"sortOrder": 0,
|
||||
},
|
||||
{
|
||||
"key": "reportQuery",
|
||||
"label": "查备案",
|
||||
"url": "https://example.com/report-check",
|
||||
"visible": True,
|
||||
"sortOrder": 2,
|
||||
"sortOrder": 1,
|
||||
},
|
||||
]
|
||||
},
|
||||
@@ -151,12 +143,12 @@ def test_hot_links_open_report_pages_on_site(client: TestClient):
|
||||
assert saved.status_code == 200, saved.text
|
||||
home = client.get("/api/site/home")
|
||||
assert home.json()["hotLinks"]["links"] == [
|
||||
{"label": "辅助审核", "url": "/reports/review", "navigation": "sameWindow"},
|
||||
{"label": "投诉举报", "url": "https://example.com/complaint", "navigation": "newWindow"},
|
||||
{"label": "查备案", "url": "/reports/query", "navigation": "sameWindow"},
|
||||
]
|
||||
assert "example.com/report-check" not in home.text
|
||||
assert "example.com/review" not in home.text
|
||||
assert "报告审核" not in home.text
|
||||
assert "/reports/review" not in home.text
|
||||
|
||||
rejected = client.put(
|
||||
"/api/admin/home/hot-links",
|
||||
@@ -167,7 +159,7 @@ def test_hot_links_open_report_pages_on_site(client: TestClient):
|
||||
|
||||
cleared = client.put("/api/admin/home/hot-links", headers=staff, json={"links": hidden})
|
||||
assert cleared.status_code == 200, cleared.text
|
||||
assert client.get("/api/site/home").json()["hotLinks"]["placeholder"] == "报告查询、报告审核与投诉举报入口即将开放"
|
||||
assert client.get("/api/site/home").json()["hotLinks"]["placeholder"] == "报告查询与投诉举报入口即将开放"
|
||||
finally:
|
||||
restore = before or hidden
|
||||
client.put("/api/admin/home/hot-links", headers=staff, json={"links": restore})
|
||||
@@ -0,0 +1,757 @@
|
||||
"""估价模版智能体:对话整理提纲,只提供下载,不进入模版列表。"""
|
||||
|
||||
import io
|
||||
import json
|
||||
from urllib.parse import unquote
|
||||
|
||||
import pytest
|
||||
from docx import Document
|
||||
from fastapi import FastAPI
|
||||
from fastapi.testclient import TestClient
|
||||
from pptx import Presentation
|
||||
from sqlalchemy import create_engine, func, select
|
||||
from sqlalchemy.orm import Session
|
||||
from sqlalchemy.pool import StaticPool
|
||||
|
||||
from app.api.site.template_coach import router as coach_router
|
||||
from app.api.site.valuation import router as valuation_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 AGENT_ADMIN_ROLE_CODE, AgentAdminLink
|
||||
from app.models.member import SiteMember
|
||||
from app.models.rbac import AdminRole, AdminUser, AdminUserRole
|
||||
from app.models.valuation import (
|
||||
ValuationCoachMessage,
|
||||
ValuationCoachSession,
|
||||
ValuationFile,
|
||||
ValuationMessage,
|
||||
ValuationSession,
|
||||
ValuationSuggestion,
|
||||
ValuationTemplate,
|
||||
)
|
||||
from app.services.dify_chat import DifyChatError, DifyNotConfigured
|
||||
from app.services.template_coach import prose_ready, sections_from_chapters
|
||||
from app.services.valuation_context import extract_excerpt
|
||||
|
||||
|
||||
def token(owner: str) -> dict:
|
||||
return {"Authorization": f"Bearer {create_access_token(owner, 'agent')}"}
|
||||
|
||||
|
||||
def _docx(paragraphs: list[tuple[str, str]]) -> bytes:
|
||||
document = Document()
|
||||
for kind, text in paragraphs:
|
||||
if kind == "h":
|
||||
document.add_heading(text, level=1)
|
||||
else:
|
||||
document.add_paragraph(text)
|
||||
buffer = io.BytesIO()
|
||||
document.save(buffer)
|
||||
return buffer.getvalue()
|
||||
|
||||
|
||||
def _pptx() -> bytes:
|
||||
presentation = Presentation()
|
||||
layout = presentation.slide_layouts[1]
|
||||
first = presentation.slides.add_slide(layout)
|
||||
first.shapes.title.text = "住宅坐落"
|
||||
first.placeholders[1].text = "城关区某路,面积 120.5 平方米"
|
||||
second = presentation.slides.add_slide(layout)
|
||||
second.shapes.title.text = "估价方法"
|
||||
second.placeholders[1].text = "比较法"
|
||||
buffer = io.BytesIO()
|
||||
presentation.save(buffer)
|
||||
return buffer.getvalue()
|
||||
|
||||
|
||||
def _events(response) -> list[dict]:
|
||||
found = []
|
||||
for line in response.text.splitlines():
|
||||
if line.startswith("data:"):
|
||||
found.append(json.loads(line[5:]))
|
||||
return found
|
||||
|
||||
|
||||
def test_history_file_becomes_downloadable_template_without_copying_facts(client, monkeypatch):
|
||||
store: dict[str, bytes] = {}
|
||||
|
||||
def upload_object(_bucket, key, data, _content_type):
|
||||
store[key] = data
|
||||
|
||||
def read_object(_bucket, key):
|
||||
return store[key]
|
||||
|
||||
def refuse_model(**_kwargs):
|
||||
raise AssertionError("按文稿结构整理时不应调用估价问答")
|
||||
|
||||
monkeypatch.setattr("app.api.site.template_coach.upload_object", upload_object)
|
||||
monkeypatch.setattr("app.api.site.template_coach.read_object", read_object)
|
||||
monkeypatch.setattr("app.api.site.template_coach.read_upload_limit", lambda _db: 10 * 1024 * 1024)
|
||||
monkeypatch.setattr("app.api.site.template_coach.iter_dify_chat", refuse_model)
|
||||
monkeypatch.setattr("app.api.site.valuation.upload_object", upload_object)
|
||||
monkeypatch.setattr("app.api.site.valuation.read_upload_limit", lambda _db: 10 * 1024 * 1024)
|
||||
|
||||
assert client.get("/api/site/member/valuation/template-coach", headers=token("m:1")).status_code == 403
|
||||
assert client.post("/api/site/member/valuation/template-coach/messages", headers=token("s:2"), json={"query": "整理"}).status_code == 403
|
||||
rejected = client.post(
|
||||
"/api/site/member/valuation/template-coach/files",
|
||||
headers=token("s:1"),
|
||||
files={"file": ("old.doc", b"old", "application/msword")},
|
||||
)
|
||||
assert rejected.status_code == 400
|
||||
|
||||
payload = _docx(
|
||||
[
|
||||
("h", "一、估价对象"),
|
||||
("p", "兰州市城关区某路 1 号,建筑面积 120.5 平方米,成交价 186 万元。"),
|
||||
("h", "二、估价方法"),
|
||||
("p", "比较法。"),
|
||||
]
|
||||
)
|
||||
before = client.get("/api/site/member/valuation/templates/manage", headers=token("s:1")).json()["items"]
|
||||
uploaded = client.post(
|
||||
"/api/site/member/valuation/template-coach/files",
|
||||
headers=token("s:1"),
|
||||
files={"file": ("住宅估价终稿.docx", payload, "application/vnd.openxmlformats-officedocument.wordprocessingml.document")},
|
||||
)
|
||||
assert uploaded.status_code == 201
|
||||
response = client.post(
|
||||
"/api/site/member/valuation/template-coach/messages",
|
||||
headers=token("s:1"),
|
||||
json={"query": "按这份历史文稿整理成 Word 模版", "fileIds": [uploaded.json()["id"]]},
|
||||
)
|
||||
assert response.status_code == 200
|
||||
saved = next(item for item in _events(response) if item["type"] == "saved")
|
||||
assert saved["kind"] == "template"
|
||||
assert saved["draftFormat"] == "docx"
|
||||
download = client.get(
|
||||
f"/api/site/member/valuation/template-coach/messages/{saved['messageId']}/file",
|
||||
headers=token("s:1"),
|
||||
)
|
||||
assert download.status_code == 200
|
||||
text = extract_excerpt("docx", download.content, limit=8000)
|
||||
assert "估价对象" in text
|
||||
assert "估价方法" in text
|
||||
assert "待补充" in text
|
||||
assert "120.5" not in text
|
||||
assert "186" not in text
|
||||
assert client.get("/api/site/member/valuation/templates/manage", headers=token("s:1")).json()["items"] == before
|
||||
narrowed = client.post(
|
||||
"/api/site/member/valuation/template-coach/messages",
|
||||
headers=token("s:1"),
|
||||
json={"query": "第1章要写坐落、用途和面积"},
|
||||
)
|
||||
narrowed_saved = next(item for item in _events(narrowed) if item["type"] == "saved")
|
||||
narrowed_text = extract_excerpt(
|
||||
"docx",
|
||||
client.get(
|
||||
f"/api/site/member/valuation/template-coach/messages/{narrowed_saved['messageId']}/file",
|
||||
headers=token("s:1"),
|
||||
).content,
|
||||
limit=8000,
|
||||
)
|
||||
assert "坐落、用途和面积" in narrowed_text
|
||||
removed = client.post(
|
||||
"/api/site/member/valuation/template-coach/messages",
|
||||
headers=token("s:1"),
|
||||
json={"query": "删除第2章"},
|
||||
)
|
||||
removed_saved = next(item for item in _events(removed) if item["type"] == "saved")
|
||||
removed_text = extract_excerpt(
|
||||
"docx",
|
||||
client.get(
|
||||
f"/api/site/member/valuation/template-coach/messages/{removed_saved['messageId']}/file",
|
||||
headers=token("s:1"),
|
||||
).content,
|
||||
limit=8000,
|
||||
)
|
||||
assert "估价方法" not in removed_text
|
||||
assert "估价对象" in removed_text
|
||||
|
||||
switched = client.post(
|
||||
"/api/site/member/valuation/template-coach/messages",
|
||||
headers=token("s:1"),
|
||||
json={"query": "改成 PPT"},
|
||||
)
|
||||
slide_saved = next(item for item in _events(switched) if item["type"] == "saved")
|
||||
assert slide_saved["draftFormat"] == "pptx"
|
||||
slides = client.get(
|
||||
f"/api/site/member/valuation/template-coach/messages/{slide_saved['messageId']}/file",
|
||||
headers=token("s:1"),
|
||||
)
|
||||
assert "估价对象" in extract_excerpt("pptx", slides.content, limit=8000)
|
||||
assert client.get(
|
||||
f"/api/site/member/valuation/template-coach/messages/{saved['messageId']}/file",
|
||||
headers=token("s:3"),
|
||||
).status_code == 404
|
||||
|
||||
|
||||
def test_freeform_adjustment_uses_the_model_and_reset_starts_over(client, monkeypatch):
|
||||
def fake_stream(**kwargs):
|
||||
assert kwargs["conversation_id"] == ""
|
||||
assert "案例选取条件" in kwargs["query"]
|
||||
assert "估价对象" in kwargs["query"]
|
||||
yield {"type": "thought", "text": "合并章节"}
|
||||
yield {
|
||||
"type": "delta",
|
||||
"text": "已把方法要求写进一章。\n```template\n名称:住宅估价说明\n格式:docx\n一、估价方法\n写明方法及案例选取条件。没有依据时写「待补充」。\n```",
|
||||
}
|
||||
yield {"type": "done", "conversationId": "coach-should-not-persist"}
|
||||
|
||||
monkeypatch.setattr("app.api.site.template_coach.iter_dify_chat", fake_stream)
|
||||
opened = client.get("/api/site/member/valuation/template-coach", headers=token("s:1"))
|
||||
assert "不会把文件直接放进模版列表" in opened.json()["items"][0]["content"]
|
||||
response = client.post(
|
||||
"/api/site/member/valuation/template-coach/messages",
|
||||
headers=token("s:1"),
|
||||
json={"query": "要有估价对象、估价方法"},
|
||||
)
|
||||
assert next(item for item in _events(response) if item["type"] == "saved")["kind"] == "template"
|
||||
adjusted = client.post(
|
||||
"/api/site/member/valuation/template-coach/messages",
|
||||
headers=token("s:1"),
|
||||
json={"query": "把方法写得更具体,要求写明案例选取条件"},
|
||||
)
|
||||
events = _events(adjusted)
|
||||
assert any(item["type"] == "thought" for item in events)
|
||||
saved = next(item for item in events if item["type"] == "saved")
|
||||
assert saved["draftName"] == "住宅估价说明"
|
||||
body = "".join(item.get("text", "") for item in events if item["type"] in {"delta", "replace"})
|
||||
assert "```template" not in body
|
||||
downloaded = client.get(
|
||||
f"/api/site/member/valuation/template-coach/messages/{saved['messageId']}/file",
|
||||
headers=token("s:1"),
|
||||
)
|
||||
assert "案例选取条件" in extract_excerpt("docx", downloaded.content, limit=8000)
|
||||
reset = client.post("/api/site/member/valuation/template-coach/reset", headers=token("s:1"))
|
||||
assert len(reset.json()["items"]) == 1
|
||||
assert reset.json()["items"][0]["role"] == "assistant"
|
||||
|
||||
|
||||
def test_unstructured_model_answer_is_not_shown_as_a_template():
|
||||
from app.services.template_coach import Outline, Section, finish_model_answer
|
||||
|
||||
fallback = Outline(name="住宅", format="docx", sections=[Section("估价对象", "写明坐落。没有依据时写「待补充」。")])
|
||||
reply, outline = finish_model_answer("评估对象是兰州市某小区,结论值为186万元。", fallback=fallback)
|
||||
assert outline is fallback
|
||||
assert "186" not in reply
|
||||
assert "估价对象" in reply
|
||||
plain, missed = finish_model_answer("评估对象是兰州市某小区,结论值为186万元。", fallback=None)
|
||||
assert missed is None
|
||||
assert "186" not in plain
|
||||
|
||||
|
||||
def test_slide_file_keeps_slide_order(client, monkeypatch):
|
||||
store: dict[str, bytes] = {}
|
||||
monkeypatch.setattr("app.api.site.template_coach.upload_object", lambda _b, key, data, _t: store.__setitem__(key, data))
|
||||
monkeypatch.setattr("app.api.site.template_coach.read_object", lambda _b, key: store[key])
|
||||
monkeypatch.setattr("app.api.site.template_coach.read_upload_limit", lambda _db: 10 * 1024 * 1024)
|
||||
monkeypatch.setattr("app.api.site.template_coach.iter_dify_chat", lambda **_kwargs: (_ for _ in ()).throw(AssertionError("不应调用模型")))
|
||||
uploaded = client.post(
|
||||
"/api/site/member/valuation/template-coach/files",
|
||||
headers=token("s:1"),
|
||||
files={
|
||||
"file": (
|
||||
"汇报.pptx",
|
||||
_pptx(),
|
||||
"application/vnd.openxmlformats-officedocument.presentationml.presentation",
|
||||
)
|
||||
},
|
||||
)
|
||||
response = client.post(
|
||||
"/api/site/member/valuation/template-coach/messages",
|
||||
headers=token("s:1"),
|
||||
json={"fileIds": [uploaded.json()["id"]]},
|
||||
)
|
||||
saved = next(item for item in _events(response) if item["type"] == "saved")
|
||||
assert saved["draftFormat"] == "pptx"
|
||||
text = extract_excerpt(
|
||||
"pptx",
|
||||
client.get(
|
||||
f"/api/site/member/valuation/template-coach/messages/{saved['messageId']}/file",
|
||||
headers=token("s:1"),
|
||||
).content,
|
||||
limit=8000,
|
||||
)
|
||||
assert text.index("住宅坐落") < text.index("估价方法")
|
||||
assert "120.5" not in text
|
||||
|
||||
|
||||
@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 = [
|
||||
model.__table__
|
||||
for model in (
|
||||
SiteMember,
|
||||
AgentAdminLink,
|
||||
AdminUser,
|
||||
AdminRole,
|
||||
AdminUserRole,
|
||||
ValuationSession,
|
||||
ValuationMessage,
|
||||
ValuationFile,
|
||||
ValuationSuggestion,
|
||||
ValuationTemplate,
|
||||
ValuationCoachSession,
|
||||
ValuationCoachMessage,
|
||||
)
|
||||
]
|
||||
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"))
|
||||
db.add(AdminUser(id=3, username="other", 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.add(AdminUserRole(user_id=3, role_id=role.id))
|
||||
db.commit()
|
||||
assert db.scalar(select(func.count()).select_from(ValuationTemplate)) == 0
|
||||
|
||||
def database():
|
||||
with Session(engine) as db:
|
||||
yield db
|
||||
|
||||
app = FastAPI()
|
||||
app.include_router(valuation_router, prefix="/api/site/member/valuation")
|
||||
app.include_router(coach_router, prefix="/api/site/member/valuation")
|
||||
app.dependency_overrides[get_db] = database
|
||||
return TestClient(app)
|
||||
|
||||
|
||||
def _bind_store(monkeypatch, limit: int = 10 * 1024 * 1024) -> dict[str, bytes]:
|
||||
store: dict[str, bytes] = {}
|
||||
monkeypatch.setattr("app.api.site.template_coach.upload_object", lambda _b, key, data, _t: store.__setitem__(key, data))
|
||||
monkeypatch.setattr("app.api.site.template_coach.read_object", lambda _b, key: store[key])
|
||||
monkeypatch.setattr("app.api.site.template_coach.read_upload_limit", lambda _db: limit)
|
||||
return store
|
||||
|
||||
|
||||
def _saved(response):
|
||||
return next(item for item in _events(response) if item["type"] == "saved")
|
||||
|
||||
|
||||
def _visible(response) -> str:
|
||||
return "".join(item.get("text", "") for item in _events(response) if item["type"] in {"delta", "replace"})
|
||||
|
||||
|
||||
def _download(client, message_id: int, owner: str = "s:1"):
|
||||
return client.get(f"/api/site/member/valuation/template-coach/messages/{message_id}/file", headers=token(owner))
|
||||
|
||||
|
||||
def _say(client, query: str, file_ids: list[int] | None = None, owner: str = "s:1", session_id: int | None = None):
|
||||
body: dict = {"query": query, "fileIds": file_ids or []}
|
||||
if session_id is not None:
|
||||
body["sessionId"] = session_id
|
||||
return client.post(
|
||||
"/api/site/member/valuation/template-coach/messages",
|
||||
headers=token(owner),
|
||||
json=body,
|
||||
)
|
||||
|
||||
|
||||
def test_permissions_and_rejected_files(client, monkeypatch):
|
||||
_bind_store(monkeypatch, limit=8)
|
||||
assert client.get("/api/site/member/valuation/template-coach").status_code == 401
|
||||
staff = {"Authorization": f"Bearer {create_access_token('s:1', 'staff')}"}
|
||||
assert client.post("/api/site/member/valuation/template-coach/messages", headers=staff, json={"query": "整理"}).status_code == 403
|
||||
for path in ("/template-coach",):
|
||||
assert client.get(f"/api/site/member/valuation{path}", headers=token("s:2")).status_code == 403
|
||||
assert client.post("/api/site/member/valuation/template-coach/reset", headers=token("m:1")).status_code == 403
|
||||
assert client.post("/api/site/member/valuation/template-coach/messages", headers=token("s:1"), json={}).status_code == 400
|
||||
assert client.post(
|
||||
"/api/site/member/valuation/template-coach/messages",
|
||||
headers=token("s:1"),
|
||||
json={"query": "看一下", "fileIds": [99]},
|
||||
).status_code == 404
|
||||
assert client.post(
|
||||
"/api/site/member/valuation/template-coach/messages",
|
||||
headers=token("s:1"),
|
||||
json={"query": "太多", "fileIds": [1, 2, 3, 4, 5, 6]},
|
||||
).status_code == 422
|
||||
assert client.post(
|
||||
"/api/site/member/valuation/template-coach/messages",
|
||||
headers=token("s:1"),
|
||||
json={"query": "字" * 2001},
|
||||
).status_code == 422
|
||||
rejected = {
|
||||
"old.ppt": (b"ppt", 400),
|
||||
"note.gif": (b"GIF89a", 400),
|
||||
"empty.docx": (b"", 400),
|
||||
"big.docx": (b"0123456789", 400),
|
||||
}
|
||||
for name, (payload, status_code) in rejected.items():
|
||||
response = client.post(
|
||||
"/api/site/member/valuation/template-coach/files",
|
||||
headers=token("s:1"),
|
||||
files={"file": (name, payload, "application/octet-stream")},
|
||||
)
|
||||
assert response.status_code == status_code, name
|
||||
|
||||
|
||||
def test_dialogue_edits_persist_and_do_not_resurrect_deleted_chapters(client, monkeypatch):
|
||||
_bind_store(monkeypatch)
|
||||
monkeypatch.setattr(
|
||||
"app.api.site.template_coach.iter_dify_chat",
|
||||
lambda **_kwargs: (_ for _ in ()).throw(AssertionError("本地调整不应调用模型")),
|
||||
)
|
||||
created = _say(client, "要有估价对象、估价方法、估价结果")
|
||||
assert _saved(created)["draftFormat"] == "docx"
|
||||
renamed = _say(client, "模版名称改为住宅比较说明")
|
||||
renamed_file = _download(client, _saved(renamed)["messageId"])
|
||||
assert "住宅比较说明.docx" in unquote(renamed_file.headers["content-disposition"])
|
||||
added = _say(client, "增加一章:风险提示,要求写特别事项和依据")
|
||||
added_text = extract_excerpt("docx", _download(client, _saved(added)["messageId"]).content, limit=8000)
|
||||
assert "风险提示" in added_text
|
||||
assert "特别事项和依据" in added_text
|
||||
quoted = _say(client, "删掉「估价结果」")
|
||||
quoted_text = extract_excerpt("docx", _download(client, _saved(quoted)["messageId"]).content, limit=8000)
|
||||
assert "估价结果" not in quoted_text
|
||||
assert "估价对象" in quoted_text
|
||||
missing = _say(client, "删除第9章")
|
||||
assert _saved(missing)["kind"] == "chat"
|
||||
assert "保持不变" in _visible(missing)
|
||||
_say(client, "删除第1章")
|
||||
_say(client, "删除第1章")
|
||||
cleared = _say(client, "删除第1章")
|
||||
assert _saved(cleared)["kind"] == "chat"
|
||||
assert "已经去掉" in _visible(cleared)
|
||||
revived = _say(client, "改成 PPT")
|
||||
assert _saved(revived)["kind"] == "chat"
|
||||
assert "还没有可调整" in _visible(revived)
|
||||
fresh = _say(client, "要有坐落说明、收益路径")
|
||||
fresh_text = extract_excerpt("docx", _download(client, _saved(fresh)["messageId"]).content, limit=8000)
|
||||
assert "坐落说明" in fresh_text
|
||||
assert "估价对象" not in fresh_text
|
||||
|
||||
|
||||
def test_reopen_reset_and_owner_isolation(client, monkeypatch):
|
||||
calls: list[str] = []
|
||||
|
||||
def fake_stream(**kwargs):
|
||||
calls.append(kwargs["query"])
|
||||
yield {"type": "delta", "text": "保持现状。"}
|
||||
yield {"type": "done", "conversationId": "should-not-be-stored"}
|
||||
|
||||
_bind_store(monkeypatch)
|
||||
monkeypatch.setattr("app.api.site.template_coach.iter_dify_chat", fake_stream)
|
||||
_say(client, "要有甲乙丙独特章节、方法说明")
|
||||
opened = client.get("/api/site/member/valuation/template-coach", headers=token("s:1")).json()
|
||||
assert any("甲乙丙独特章节" in item["content"] for item in opened["items"])
|
||||
other = client.get("/api/site/member/valuation/template-coach", headers=token("s:3")).json()
|
||||
assert all("甲乙丙独特章节" not in item["content"] for item in other["items"])
|
||||
message_id = next(item["id"] for item in opened["items"] if item["kind"] == "template")
|
||||
assert _download(client, message_id, "s:3").status_code == 404
|
||||
welcome_id = opened["items"][0]["id"]
|
||||
assert _download(client, welcome_id).status_code == 404
|
||||
foreign = client.post(
|
||||
"/api/site/member/valuation/template-coach/files",
|
||||
headers=token("s:3"),
|
||||
files={"file": ("other.docx", _docx([("h", "一、别人的章节"), ("p", "正文")]), "application/octet-stream")},
|
||||
)
|
||||
assert _say(client, "按这份整理", [foreign.json()["id"]]).status_code == 404
|
||||
reset = client.post("/api/site/member/valuation/template-coach/reset", headers=token("s:1"))
|
||||
assert _download(client, message_id).status_code == 200
|
||||
assert len(reset.json()["sessions"]) == 2
|
||||
assert len(reset.json()["items"]) == 1
|
||||
follow = _say(client, "请把提纲改得更适合设备估价,写清比较案例怎么选")
|
||||
assert follow.status_code == 200
|
||||
assert calls and "甲乙丙独特章节" not in calls[-1]
|
||||
assert client.get("/api/site/member/valuation/sessions", headers=token("s:1")).json()["items"] == []
|
||||
|
||||
|
||||
def test_model_failure_keeps_file_structure_and_hides_unstructured_answer(client, monkeypatch):
|
||||
_bind_store(monkeypatch)
|
||||
|
||||
def fail(**_kwargs):
|
||||
raise DifyNotConfigured("未配置估价智能体 API Key")
|
||||
|
||||
monkeypatch.setattr("app.api.site.template_coach.iter_dify_chat", fail)
|
||||
payload = _docx(
|
||||
[
|
||||
("h", "甘肃省房地产价格评估行业协会"),
|
||||
("h", "一、估价对象"),
|
||||
("p", "2019年5月1日,建筑面积 88 平方米,总价 500 万元。"),
|
||||
("p", "没有标题的整段叙述会很长,不应该被当成短标签抄进模版。"),
|
||||
]
|
||||
)
|
||||
uploaded = client.post(
|
||||
"/api/site/member/valuation/template-coach/files",
|
||||
headers=token("s:1"),
|
||||
files={"file": ("住宅估价正式稿.docx", payload, "application/octet-stream")},
|
||||
)
|
||||
response = _say(client, "请把这一章改写成必须列出比较案例的选取条件", [uploaded.json()["id"]])
|
||||
saved = _saved(response)
|
||||
assert saved["kind"] == "template"
|
||||
text = extract_excerpt("docx", _download(client, saved["messageId"]).content, limit=8000)
|
||||
assert "估价对象" in text
|
||||
assert "待补充" in text
|
||||
assert "2019" not in text
|
||||
assert "500" not in text
|
||||
assert "88" not in text
|
||||
assert "甘肃省房地产价格评估行业协会" not in text
|
||||
assert "住宅估价正式稿" not in saved["draftName"]
|
||||
assert "住宅估价" in saved["draftName"]
|
||||
plain = _say(client, "这个小区现在值多少钱")
|
||||
assert _saved(plain)["kind"] == "template"
|
||||
assert "500" not in _visible(plain)
|
||||
assert "已有材料" in _visible(plain)
|
||||
|
||||
def chat_error(**_kwargs):
|
||||
raise DifyChatError("Dify 返回错误")
|
||||
|
||||
monkeypatch.setattr("app.api.site.template_coach.iter_dify_chat", chat_error)
|
||||
again = _say(client, "再按对话改一版,突出收益法的适用条件")
|
||||
again_text = extract_excerpt("docx", _download(client, _saved(again)["messageId"]).content, limit=8000)
|
||||
assert "估价对象" in again_text
|
||||
assert "收益法" not in again_text
|
||||
assert "500" not in again_text
|
||||
client.post("/api/site/member/valuation/template-coach/reset", headers=token("s:1"))
|
||||
offline = _say(client, "这个小区现在值多少钱")
|
||||
assert _saved(offline)["kind"] == "chat"
|
||||
assert "暂时连不上估价智能体" in _visible(offline)
|
||||
|
||||
|
||||
def test_stream_hides_template_fence_and_first_office_file_wins(client, monkeypatch):
|
||||
_bind_store(monkeypatch)
|
||||
sent: list[dict] = []
|
||||
|
||||
def fake_stream(**kwargs):
|
||||
sent.append(kwargs)
|
||||
yield {"type": "thought", "text": "只改提纲"}
|
||||
yield {"type": "delta", "text": "已按两页合并。\n``"}
|
||||
yield {
|
||||
"type": "delta",
|
||||
"text": "`template\n名称:合并汇报\n格式:pptx\n第1页 比较案例\n写明选取条件。没有依据时写「待补充」。\n```",
|
||||
}
|
||||
yield {"type": "done", "conversationId": "ignore"}
|
||||
|
||||
monkeypatch.setattr("app.api.site.template_coach.iter_dify_chat", fake_stream)
|
||||
word = client.post(
|
||||
"/api/site/member/valuation/template-coach/files",
|
||||
headers=token("s:1"),
|
||||
files={"file": ("甲稿.docx", _docx([("h", "一、只在Word"), ("p", "说明")]), "application/octet-stream")},
|
||||
)
|
||||
slides = client.post(
|
||||
"/api/site/member/valuation/template-coach/files",
|
||||
headers=token("s:1"),
|
||||
files={"file": ("乙稿.pptx", _pptx(), "application/octet-stream")},
|
||||
)
|
||||
response = _say(
|
||||
client,
|
||||
"不要照着页数,改成突出比较案例的选取条件",
|
||||
[word.json()["id"], slides.json()["id"]],
|
||||
)
|
||||
assert any(item["type"] == "thought" for item in _events(response))
|
||||
assert "```" not in _visible(response)
|
||||
assert sent and sent[0]["conversation_id"] == ""
|
||||
assert "只在Word" in sent[0]["query"]
|
||||
saved = _saved(response)
|
||||
assert saved["draftFormat"] == "pptx"
|
||||
assert saved["draftName"] == "合并汇报"
|
||||
text = extract_excerpt("pptx", _download(client, saved["messageId"]).content, limit=8000)
|
||||
assert "比较案例" in text
|
||||
assert "120.5" not in text
|
||||
before = client.get("/api/site/member/valuation/templates/manage", headers=token("s:1")).json()["items"]
|
||||
assert client.get("/api/site/member/valuation/templates/manage", headers=token("s:1")).json()["items"] == before
|
||||
|
||||
|
||||
def test_new_session_keeps_the_previous_one(client):
|
||||
first = client.get("/api/site/member/valuation/template-coach", headers=token("s:1")).json()
|
||||
made = _say(client, "要有估价对象、估价方法", session_id=first["sessionId"])
|
||||
saved = _saved(made)
|
||||
assert saved["kind"] == "template"
|
||||
second = client.post("/api/site/member/valuation/template-coach/sessions", headers=token("s:1"))
|
||||
assert second.status_code == 201
|
||||
opened = second.json()
|
||||
assert len(opened["sessions"]) == 2
|
||||
assert opened["sessionId"] != first["sessionId"]
|
||||
assert len(opened["items"]) == 1
|
||||
assert _download(client, saved["messageId"]).status_code == 200
|
||||
fresh = _say(client, "改成 PPT", session_id=opened["sessionId"])
|
||||
assert _saved(fresh)["kind"] == "chat"
|
||||
assert "还没有可调整" in _visible(fresh)
|
||||
continued = _say(client, "删除第1章", session_id=first["sessionId"])
|
||||
assert _saved(continued)["kind"] == "template"
|
||||
assert "估价方法" in extract_excerpt("docx", _download(client, _saved(continued)["messageId"]).content, limit=8000)
|
||||
renamed = client.patch(
|
||||
f"/api/site/member/valuation/template-coach/sessions/{first['sessionId']}",
|
||||
headers=token("s:1"),
|
||||
json={"title": "住宅提纲"},
|
||||
)
|
||||
assert renamed.json()["title"] == "住宅提纲"
|
||||
assert client.get(
|
||||
f"/api/site/member/valuation/template-coach/sessions/{first['sessionId']}",
|
||||
headers=token("s:3"),
|
||||
).status_code == 404
|
||||
assert client.delete(
|
||||
f"/api/site/member/valuation/template-coach/sessions/{first['sessionId']}",
|
||||
headers=token("s:1"),
|
||||
).status_code == 204
|
||||
assert _download(client, saved["messageId"]).status_code == 404
|
||||
left = client.get("/api/site/member/valuation/template-coach", headers=token("s:1")).json()
|
||||
assert left["sessionId"] == opened["sessionId"]
|
||||
assert len(left["sessions"]) == 1
|
||||
|
||||
|
||||
def test_two_sessions_keep_separate_outlines_files_and_titles(client, monkeypatch):
|
||||
prompts: list[str] = []
|
||||
|
||||
def fake_stream(**kwargs):
|
||||
prompts.append(kwargs["query"])
|
||||
yield {"type": "delta", "text": "评估对象是兰州市某小区,结论值为186万元。"}
|
||||
yield {"type": "done", "conversationId": "must-not-stick"}
|
||||
|
||||
_bind_store(monkeypatch)
|
||||
monkeypatch.setattr("app.api.site.template_coach.iter_dify_chat", fake_stream)
|
||||
templates_before = client.get("/api/site/member/valuation/templates/manage", headers=token("s:1")).json()["items"]
|
||||
opened = client.get("/api/site/member/valuation/template-coach", headers=token("s:1")).json()
|
||||
session_a = opened["sessionId"]
|
||||
created = _say(client, "要有甲乙丙独特章节、估价方法、估价结果", session_id=session_a)
|
||||
first = _saved(created)
|
||||
assert first["draftFormat"] == "docx"
|
||||
first_file = _download(client, first["messageId"]).content
|
||||
assert "甲乙丙独特章节" in extract_excerpt("docx", first_file, limit=8000)
|
||||
assert "估价结果" in extract_excerpt("docx", first_file, limit=8000)
|
||||
listed = client.get("/api/site/member/valuation/template-coach", headers=token("s:1")).json()
|
||||
assert listed["sessions"][0]["id"] == session_a
|
||||
assert listed["sessions"][0]["title"] == "要有甲乙丙独特章节、估价方法、估价结果"[:22]
|
||||
|
||||
second = client.post("/api/site/member/valuation/template-coach/sessions", headers=token("s:1")).json()
|
||||
session_b = second["sessionId"]
|
||||
assert session_b != session_a
|
||||
assert second["sessions"][0]["id"] == session_b
|
||||
assert second["sessions"][0]["title"] == "新会话"
|
||||
uploaded = client.post(
|
||||
"/api/site/member/valuation/template-coach/files",
|
||||
headers=token("s:1"),
|
||||
files={"file": ("历史汇报.pptx", _pptx(), "application/octet-stream")},
|
||||
)
|
||||
slides = _say(client, "", [uploaded.json()["id"]], session_id=session_b)
|
||||
slide_saved = _saved(slides)
|
||||
assert slide_saved["draftFormat"] == "pptx"
|
||||
slide_file = _download(client, slide_saved["messageId"]).content
|
||||
assert "住宅坐落" in extract_excerpt("pptx", slide_file, limit=8000)
|
||||
assert "120.5" not in extract_excerpt("pptx", slide_file, limit=8000)
|
||||
named = client.get("/api/site/member/valuation/template-coach/sessions/" + str(session_b), headers=token("s:1")).json()
|
||||
assert named["sessionId"] == session_b
|
||||
assert named["sessions"][0]["title"] == "历史汇报.pptx"
|
||||
|
||||
narrowed = _say(client, "模版名称改为住宅比较说明,删除第3章", session_id=session_a)
|
||||
narrowed_saved = _saved(narrowed)
|
||||
assert narrowed_saved["draftName"] == "住宅比较说明"
|
||||
narrowed_text = extract_excerpt("docx", _download(client, narrowed_saved["messageId"]).content, limit=8000)
|
||||
assert "估价结果" not in narrowed_text
|
||||
assert "甲乙丙独特章节" in narrowed_text
|
||||
assert "估价结果" in extract_excerpt("docx", _download(client, first["messageId"]).content, limit=8000)
|
||||
assert "住宅比较说明" not in extract_excerpt("pptx", _download(client, slide_saved["messageId"]).content, limit=8000)
|
||||
|
||||
switched = _say(client, "改成 PPT", session_id=session_a)
|
||||
assert _saved(switched)["draftFormat"] == "pptx"
|
||||
switched_text = extract_excerpt("pptx", _download(client, _saved(switched)["messageId"]).content, limit=8000)
|
||||
assert "甲乙丙独特章节" in switched_text
|
||||
assert "住宅坐落" not in switched_text
|
||||
assert "住宅坐落" in extract_excerpt("pptx", _download(client, slide_saved["messageId"]).content, limit=8000)
|
||||
|
||||
isolated = _say(client, "请把设备比较写清楚一些", session_id=session_b)
|
||||
shown = ""
|
||||
for item in _events(isolated):
|
||||
if item["type"] == "delta":
|
||||
shown += item.get("text", "")
|
||||
elif item["type"] == "replace":
|
||||
shown = item.get("text", "")
|
||||
assert "186" not in shown
|
||||
reopened = client.get(f"/api/site/member/valuation/template-coach/sessions/{session_b}", headers=token("s:1")).json()
|
||||
assert all("186" not in item["content"] for item in reopened["items"])
|
||||
assert prompts and "甲乙丙独特章节" not in prompts[-1]
|
||||
assert "住宅坐落" in prompts[-1]
|
||||
_say(client, "请补充比较案例怎么写", session_id=session_a)
|
||||
assert "甲乙丙独特章节" in prompts[-1]
|
||||
assert "住宅坐落" not in prompts[-1]
|
||||
again = client.get("/api/site/member/valuation/template-coach", headers=token("s:1")).json()
|
||||
assert again["sessions"][0]["id"] == session_a
|
||||
assert again["sessions"][0]["title"] == "要有甲乙丙独特章节、估价方法、估价结果"[:22]
|
||||
assert client.patch(
|
||||
f"/api/site/member/valuation/template-coach/sessions/{session_a}",
|
||||
headers=token("s:1"),
|
||||
json={"title": " "},
|
||||
).status_code == 400
|
||||
renamed = client.patch(
|
||||
f"/api/site/member/valuation/template-coach/sessions/{session_a}",
|
||||
headers=token("s:1"),
|
||||
json={"title": "住宅提纲"},
|
||||
)
|
||||
assert renamed.json()["title"] == "住宅提纲"
|
||||
_say(client, "第1章要写坐落和权利状况", session_id=session_a)
|
||||
assert client.get("/api/site/member/valuation/template-coach", headers=token("s:1")).json()["sessions"][0]["title"] == "住宅提纲"
|
||||
|
||||
assert client.post("/api/site/member/valuation/template-coach/sessions", headers=token("m:1")).status_code == 403
|
||||
assert client.post("/api/site/member/valuation/template-coach/sessions", headers=token("s:2")).status_code == 403
|
||||
staff = {"Authorization": f"Bearer {create_access_token('s:1', 'staff')}"}
|
||||
assert client.delete(
|
||||
f"/api/site/member/valuation/template-coach/sessions/{session_a}",
|
||||
headers=staff,
|
||||
).status_code == 403
|
||||
assert client.get(
|
||||
f"/api/site/member/valuation/template-coach/sessions/{session_a}",
|
||||
headers=token("s:3"),
|
||||
).status_code == 404
|
||||
assert client.patch(
|
||||
f"/api/site/member/valuation/template-coach/sessions/{session_a}",
|
||||
headers=token("s:3"),
|
||||
json={"title": "别人的"},
|
||||
).status_code == 404
|
||||
assert client.delete(
|
||||
f"/api/site/member/valuation/template-coach/sessions/{session_a}",
|
||||
headers=token("s:3"),
|
||||
).status_code == 404
|
||||
stolen = _say(client, "删掉「甲乙丙独特章节」", session_id=session_a, owner="s:3")
|
||||
assert stolen.status_code == 404
|
||||
assert "甲乙丙独特章节" in extract_excerpt(
|
||||
"pptx",
|
||||
_download(client, _saved(switched)["messageId"]).content,
|
||||
limit=8000,
|
||||
)
|
||||
foreign = client.post(
|
||||
"/api/site/member/valuation/template-coach/files",
|
||||
headers=token("s:3"),
|
||||
files={"file": ("别人.docx", _docx([("h", "一、别人的章节"), ("p", "正文")]), "application/octet-stream")},
|
||||
)
|
||||
assert _say(client, "按这份整理", [foreign.json()["id"]], session_id=session_b).status_code == 404
|
||||
|
||||
assert client.delete(
|
||||
f"/api/site/member/valuation/template-coach/sessions/{session_a}",
|
||||
headers=token("s:1"),
|
||||
).status_code == 204
|
||||
assert _download(client, first["messageId"]).status_code == 404
|
||||
assert _download(client, slide_saved["messageId"]).status_code == 200
|
||||
remaining = client.get("/api/site/member/valuation/template-coach", headers=token("s:1")).json()
|
||||
assert [item["id"] for item in remaining["sessions"]] == [session_b]
|
||||
assert client.delete(
|
||||
f"/api/site/member/valuation/template-coach/sessions/{session_b}",
|
||||
headers=token("s:1"),
|
||||
).status_code == 204
|
||||
fresh = client.get("/api/site/member/valuation/template-coach", headers=token("s:1")).json()
|
||||
assert _download(client, slide_saved["messageId"]).status_code == 404
|
||||
assert fresh["sessions"][0]["title"] == "新会话"
|
||||
assert len(fresh["items"]) == 1
|
||||
assert fresh["items"][0]["role"] == "assistant"
|
||||
assert client.get("/api/site/member/valuation/sessions", headers=token("s:1")).json()["items"] == []
|
||||
assert client.get("/api/site/member/valuation/templates/manage", headers=token("s:1")).json()["items"] == templates_before
|
||||
|
||||
|
||||
def test_outline_parser_ignores_running_header_and_limits_chapters():
|
||||
assert prose_ready("已合并。\n``") == "已合并。\n"
|
||||
assert prose_ready("已合并。\n```template\n名称:住宅") == "已合并。\n"
|
||||
numerals = ["一", "二", "三", "四", "五", "六", "七", "八", "九", "十", "十一", "十二", "十三", "十四", "十五", "十六", "十七", "十八"]
|
||||
numbered = "本成稿为辅助文稿,不构成正式评估意见。\n" + "\n".join(f"{numeral}、部分{numeral}\n说明" for numeral in numerals)
|
||||
found = sections_from_chapters(numbered)
|
||||
assert len(found) == 16
|
||||
assert all("部分" in item.title for item in found)
|
||||
assert "不构成正式评估意见" not in "\n".join(item.instruction for item in found)
|
||||
Reference in new issue
Block a user