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
@@ -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()
|
||||
Reference in new issue
Block a user