会员服务改为固定栏目,首页在线服务不再进入报告审核。估价模版智能体可多会话制作模版并下载,下载过程显示加载状态。 Co-authored-by: Cursor <cursoragent@cursor.com>
955 lines
37 KiB
Python
955 lines
37 KiB
Python
"""会员服务:外链卡片、协会会员档案、培训报名。"""
|
|
|
|
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)
|