chore: initialize GSREA website project
This commit is contained in:
commit
d3c5461de5
1842 files changed
+246140
No files matched your search
Whitespace-only changes.
@@ -0,0 +1,319 @@
|
||||
from sqlalchemy import Boolean, Integer, String, Text, select
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from app.db import Base
|
||||
|
||||
|
||||
def _mysql_args() -> dict:
|
||||
return {"mysql_charset": "utf8mb4", "mysql_collate": "utf8mb4_unicode_ci"}
|
||||
|
||||
|
||||
ABOUT_PAGE_KEYS = ("intro", "org", "contact", "party_branch")
|
||||
ABOUT_PAGE_PLACEHOLDERS = {
|
||||
"intro": "协会简介整理中",
|
||||
"org": "组织机构整理中",
|
||||
"contact": "联系与合作信息整理中",
|
||||
"party_branch": "协会党支部介绍整理中",
|
||||
}
|
||||
EXPERT_LIST_PLACEHOLDER = "暂无专家委员会信息"
|
||||
|
||||
|
||||
class AboutPage(Base):
|
||||
__tablename__ = "about_page"
|
||||
__table_args__ = _mysql_args()
|
||||
|
||||
page_key: Mapped[str] = mapped_column(String(32), primary_key=True)
|
||||
body_html: Mapped[str] = mapped_column(Text, nullable=False, default="")
|
||||
published: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)
|
||||
|
||||
|
||||
class AboutPageAttachment(Base):
|
||||
__tablename__ = "about_page_attachment"
|
||||
__table_args__ = _mysql_args()
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
||||
page_key: Mapped[str] = mapped_column(String(32), nullable=False, index=True)
|
||||
file_id: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
position: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
|
||||
|
||||
|
||||
def _public_file(db, file_id: int):
|
||||
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" or not row.object_key:
|
||||
return None
|
||||
return row
|
||||
|
||||
|
||||
def _page_attachments(db, page_key: str) -> list:
|
||||
from app.services.storage import public_object_url
|
||||
|
||||
links = db.scalars(
|
||||
select(AboutPageAttachment)
|
||||
.where(AboutPageAttachment.page_key == page_key)
|
||||
.order_by(AboutPageAttachment.position.asc(), AboutPageAttachment.id.asc())
|
||||
).all()
|
||||
files = []
|
||||
for link in links:
|
||||
row = _public_file(db, link.file_id)
|
||||
if row is None:
|
||||
continue
|
||||
files.append({"filename": row.filename, "url": public_object_url(row.object_key)})
|
||||
return files
|
||||
|
||||
|
||||
def _editor_attachments(db, page_key: str) -> list:
|
||||
from app.services.storage import public_object_url
|
||||
|
||||
links = db.scalars(
|
||||
select(AboutPageAttachment)
|
||||
.where(AboutPageAttachment.page_key == page_key)
|
||||
.order_by(AboutPageAttachment.position.asc(), AboutPageAttachment.id.asc())
|
||||
).all()
|
||||
files = []
|
||||
for link in links:
|
||||
row = _public_file(db, link.file_id)
|
||||
if row is None:
|
||||
continue
|
||||
files.append(
|
||||
{
|
||||
"id": row.id,
|
||||
"filename": row.filename,
|
||||
"url": public_object_url(row.object_key),
|
||||
}
|
||||
)
|
||||
return files
|
||||
|
||||
|
||||
def _replace_attachments(db, page_key: str, attachments: list) -> None:
|
||||
links = db.scalars(
|
||||
select(AboutPageAttachment).where(AboutPageAttachment.page_key == page_key)
|
||||
).all()
|
||||
for link in links:
|
||||
db.delete(link)
|
||||
db.flush()
|
||||
for index, row in enumerate(attachments):
|
||||
db.add(AboutPageAttachment(page_key=page_key, file_id=row.id, position=index))
|
||||
|
||||
|
||||
def _prepare_page(db, payload: dict) -> tuple[str, bool, list]:
|
||||
from app.core.config import get_settings
|
||||
from app.models.content import AdminFile
|
||||
from app.services.html_filter import filter_html
|
||||
|
||||
attachments = []
|
||||
for file_id in payload.get("attachmentFileIds") or []:
|
||||
row = _public_file(db, file_id)
|
||||
if row is None:
|
||||
raise ValueError("附件必须是已上传的公开文件")
|
||||
attachments.append(row)
|
||||
keys = list(db.scalars(select(AdminFile.object_key).where(AdminFile.bucket == "public")))
|
||||
cleaned = filter_html(payload.get("bodyHtml") or "", list(keys), get_settings().minio_base_url)
|
||||
return cleaned, bool(payload.get("published", False)), attachments
|
||||
|
||||
|
||||
def save_about_page(db, page_key: str, payload: dict) -> None:
|
||||
if page_key not in ABOUT_PAGE_KEYS:
|
||||
raise ValueError("单篇页键不正确")
|
||||
body_html, published, attachments = _prepare_page(db, payload)
|
||||
row = db.get(AboutPage, page_key)
|
||||
if row is None:
|
||||
row = AboutPage(page_key=page_key)
|
||||
db.add(row)
|
||||
row.body_html = body_html
|
||||
row.published = published
|
||||
db.flush()
|
||||
_replace_attachments(db, page_key, attachments)
|
||||
db.commit()
|
||||
|
||||
|
||||
def admin_about_page(db, page_key: str) -> dict | None:
|
||||
if page_key not in ABOUT_PAGE_KEYS:
|
||||
return None
|
||||
row = db.get(AboutPage, page_key)
|
||||
files = _editor_attachments(db, page_key)
|
||||
return {
|
||||
"key": page_key,
|
||||
"published": bool(row.published) if row else False,
|
||||
"bodyHtml": row.body_html if row else "",
|
||||
"attachmentFileIds": [item["id"] for item in files],
|
||||
"attachments": files,
|
||||
}
|
||||
|
||||
|
||||
def public_about_page(db, page_key: str) -> dict | None:
|
||||
if page_key not in ABOUT_PAGE_KEYS:
|
||||
return None
|
||||
placeholder = ABOUT_PAGE_PLACEHOLDERS[page_key]
|
||||
row = db.get(AboutPage, page_key)
|
||||
files = _page_attachments(db, page_key) if row else []
|
||||
body = (row.body_html if row else "").strip()
|
||||
if row is None or not row.published or (not body and not files):
|
||||
return {"key": page_key, "placeholder": placeholder}
|
||||
return {
|
||||
"key": page_key,
|
||||
"bodyHtml": row.body_html,
|
||||
"attachments": files,
|
||||
}
|
||||
|
||||
|
||||
class AboutExpert(Base):
|
||||
__tablename__ = "about_expert"
|
||||
__table_args__ = _mysql_args()
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
||||
name: Mapped[str] = mapped_column(String(200), nullable=False, default="")
|
||||
body_html: Mapped[str] = mapped_column(Text, nullable=False, default="")
|
||||
sort_order: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
|
||||
published: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)
|
||||
|
||||
|
||||
class AboutExpertAttachment(Base):
|
||||
__tablename__ = "about_expert_attachment"
|
||||
__table_args__ = _mysql_args()
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
||||
expert_id: Mapped[int] = mapped_column(Integer, nullable=False, index=True)
|
||||
file_id: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
position: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
|
||||
|
||||
|
||||
def _expert_attachments(db, expert_id: int, *, editor: bool = False) -> list:
|
||||
from app.services.storage import public_object_url
|
||||
|
||||
links = db.scalars(
|
||||
select(AboutExpertAttachment)
|
||||
.where(AboutExpertAttachment.expert_id == expert_id)
|
||||
.order_by(AboutExpertAttachment.position.asc(), AboutExpertAttachment.id.asc())
|
||||
).all()
|
||||
files = []
|
||||
for link in links:
|
||||
row = _public_file(db, link.file_id)
|
||||
if row is None:
|
||||
continue
|
||||
item = {"filename": row.filename, "url": public_object_url(row.object_key)}
|
||||
if editor:
|
||||
item = {"id": row.id, **item}
|
||||
files.append(item)
|
||||
return files
|
||||
|
||||
|
||||
def _replace_expert_attachments(db, expert_id: int, attachments: list) -> None:
|
||||
links = db.scalars(
|
||||
select(AboutExpertAttachment).where(AboutExpertAttachment.expert_id == expert_id)
|
||||
).all()
|
||||
for link in links:
|
||||
db.delete(link)
|
||||
db.flush()
|
||||
for index, row in enumerate(attachments):
|
||||
db.add(AboutExpertAttachment(expert_id=expert_id, file_id=row.id, position=index))
|
||||
|
||||
|
||||
def _prepare_expert(db, payload: dict) -> tuple[dict, list]:
|
||||
from app.core.config import get_settings
|
||||
from app.models.content import AdminFile
|
||||
from app.services.html_filter import filter_html
|
||||
|
||||
name = payload.get("name")
|
||||
if not isinstance(name, str) or not name.strip():
|
||||
raise ValueError("委员会名称不能为空")
|
||||
sort_order = payload.get("sortOrder", 0)
|
||||
if isinstance(sort_order, bool) or not isinstance(sort_order, int):
|
||||
raise ValueError("排序必须是整数")
|
||||
attachments = []
|
||||
for file_id in payload.get("attachmentFileIds") or []:
|
||||
row = _public_file(db, file_id)
|
||||
if row is None:
|
||||
raise ValueError("附件必须是已上传的公开文件")
|
||||
attachments.append(row)
|
||||
keys = list(db.scalars(select(AdminFile.object_key).where(AdminFile.bucket == "public")))
|
||||
cleaned = filter_html(payload.get("bodyHtml") or "", list(keys), get_settings().minio_base_url)
|
||||
fields = {
|
||||
"name": name.strip(),
|
||||
"body_html": cleaned,
|
||||
"sort_order": sort_order,
|
||||
"published": bool(payload.get("published", False)),
|
||||
}
|
||||
return fields, attachments
|
||||
|
||||
|
||||
def create_expert(db, payload: dict) -> int:
|
||||
fields, attachments = _prepare_expert(db, payload)
|
||||
row = AboutExpert(**fields)
|
||||
db.add(row)
|
||||
db.flush()
|
||||
_replace_expert_attachments(db, row.id, attachments)
|
||||
db.commit()
|
||||
db.refresh(row)
|
||||
return row.id
|
||||
|
||||
|
||||
def update_expert(db, expert_id: int, payload: dict) -> None:
|
||||
row = db.get(AboutExpert, expert_id)
|
||||
if row is None:
|
||||
raise ValueError("专家委员会不存在")
|
||||
fields, attachments = _prepare_expert(db, payload)
|
||||
for key, value in fields.items():
|
||||
setattr(row, key, value)
|
||||
_replace_expert_attachments(db, row.id, attachments)
|
||||
db.commit()
|
||||
|
||||
|
||||
def delete_expert(db, expert_id: int) -> None:
|
||||
row = db.get(AboutExpert, expert_id)
|
||||
if row is None:
|
||||
raise ValueError("专家委员会不存在")
|
||||
links = db.scalars(
|
||||
select(AboutExpertAttachment).where(AboutExpertAttachment.expert_id == expert_id)
|
||||
).all()
|
||||
for link in links:
|
||||
db.delete(link)
|
||||
db.delete(row)
|
||||
db.commit()
|
||||
|
||||
|
||||
def admin_experts(db) -> dict:
|
||||
rows = db.scalars(
|
||||
select(AboutExpert).order_by(AboutExpert.sort_order.asc(), AboutExpert.id.asc())
|
||||
).all()
|
||||
items = []
|
||||
for row in rows:
|
||||
files = _expert_attachments(db, row.id, editor=True)
|
||||
items.append(
|
||||
{
|
||||
"id": row.id,
|
||||
"name": row.name,
|
||||
"bodyHtml": row.body_html,
|
||||
"sortOrder": row.sort_order,
|
||||
"published": bool(row.published),
|
||||
"attachmentFileIds": [item["id"] for item in files],
|
||||
"attachments": files,
|
||||
}
|
||||
)
|
||||
return {"items": items}
|
||||
|
||||
|
||||
def public_experts(db) -> dict:
|
||||
rows = db.scalars(
|
||||
select(AboutExpert)
|
||||
.where(AboutExpert.published.is_(True))
|
||||
.order_by(AboutExpert.sort_order.asc(), AboutExpert.id.asc())
|
||||
).all()
|
||||
if not rows:
|
||||
return {"placeholder": EXPERT_LIST_PLACEHOLDER}
|
||||
return {"items": [{"id": row.id, "name": row.name} for row in rows]}
|
||||
|
||||
|
||||
def public_expert(db, expert_id: int) -> dict | None:
|
||||
row = db.get(AboutExpert, expert_id)
|
||||
if row is None or not row.published:
|
||||
return None
|
||||
return {
|
||||
"id": row.id,
|
||||
"name": row.name,
|
||||
"bodyHtml": row.body_html,
|
||||
"attachments": _expert_attachments(db, row.id),
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
import json
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from sqlalchemy import DateTime, Integer, String, Text, select
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from app.db import Base
|
||||
|
||||
def _mysql_args() -> dict:
|
||||
return {"mysql_charset": "utf8mb4", "mysql_collate": "utf8mb4_unicode_ci"}
|
||||
|
||||
DEFAULTS: dict[str, str] = {
|
||||
"site_name": "甘肃省房地产价格评估行业协会",
|
||||
"logo_file_id": "",
|
||||
"banner_file_ids": "[]",
|
||||
"icp_text": "陇ICP备19001227号",
|
||||
"police_text": "甘公网安备62010202001984号",
|
||||
"friend_links": "[]",
|
||||
"link_cirea": "",
|
||||
"link_housing": "",
|
||||
"complaint_workdays": "",
|
||||
"expert_reply_workdays": "",
|
||||
"upload_max_bytes": "10485760",
|
||||
"login_max_failures": "5",
|
||||
"login_lock_minutes": "15",
|
||||
}
|
||||
|
||||
SETTING_KEYS = tuple(DEFAULTS)
|
||||
_JSON_KEYS = {"banner_file_ids", "friend_links"}
|
||||
_NUMBER_KEYS = {"upload_max_bytes", "login_max_failures", "login_lock_minutes"}
|
||||
_OPTIONAL_NUMBER_KEYS = {"complaint_workdays", "expert_reply_workdays"}
|
||||
|
||||
|
||||
def _now() -> datetime:
|
||||
return datetime.now(timezone.utc).replace(tzinfo=None)
|
||||
|
||||
|
||||
class SiteSetting(Base):
|
||||
__tablename__ = "site_setting"
|
||||
__table_args__ = _mysql_args()
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
||||
key: Mapped[str] = mapped_column(String(64), unique=True, nullable=False)
|
||||
value: Mapped[str] = mapped_column(Text, nullable=False, default="")
|
||||
|
||||
|
||||
class AdminFile(Base):
|
||||
__tablename__ = "admin_file"
|
||||
__table_args__ = _mysql_args()
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
||||
bucket: Mapped[str] = mapped_column(String(16), nullable=False, index=True)
|
||||
object_key: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
filename: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
content_type: Mapped[str] = mapped_column(String(128), nullable=False, default="")
|
||||
size: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
created_by: Mapped[int | None] = mapped_column(Integer, nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, default=_now)
|
||||
|
||||
|
||||
class SensitiveWord(Base):
|
||||
__tablename__ = "sensitive_word"
|
||||
__table_args__ = _mysql_args()
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
||||
word: Mapped[str] = mapped_column(String(64), unique=True, nullable=False)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, default=_now)
|
||||
|
||||
|
||||
def ensure_site_defaults(db) -> None:
|
||||
existing = set(db.scalars(select(SiteSetting.key)))
|
||||
missing = [
|
||||
SiteSetting(key=key, value=value)
|
||||
for key, value in DEFAULTS.items()
|
||||
if key not in existing
|
||||
]
|
||||
if not missing:
|
||||
return
|
||||
db.add_all(missing)
|
||||
try:
|
||||
db.commit()
|
||||
except IntegrityError:
|
||||
db.rollback()
|
||||
|
||||
|
||||
def read_upload_limit(db) -> int | None:
|
||||
row = db.scalar(select(SiteSetting).where(SiteSetting.key == "upload_max_bytes"))
|
||||
if row is None:
|
||||
return None
|
||||
text = str(row.value).strip()
|
||||
if not text.isdigit():
|
||||
return None
|
||||
value = int(text)
|
||||
if value <= 0:
|
||||
return None
|
||||
return value
|
||||
|
||||
|
||||
def save_settings(db, values: dict[str, str]) -> None:
|
||||
ensure_site_defaults(db)
|
||||
for key, value in values.items():
|
||||
row = db.scalar(select(SiteSetting).where(SiteSetting.key == key))
|
||||
if row is None:
|
||||
db.add(SiteSetting(key=key, value=value))
|
||||
else:
|
||||
row.value = value
|
||||
db.commit()
|
||||
|
||||
|
||||
def _present(key: str, raw: str):
|
||||
if key in _JSON_KEYS:
|
||||
if not raw:
|
||||
return []
|
||||
try:
|
||||
parsed = json.loads(raw)
|
||||
except json.JSONDecodeError:
|
||||
return []
|
||||
return parsed if isinstance(parsed, list) else []
|
||||
if key in _NUMBER_KEYS:
|
||||
text = str(raw).strip()
|
||||
if text.isdigit():
|
||||
return int(text)
|
||||
return raw
|
||||
if key in _OPTIONAL_NUMBER_KEYS:
|
||||
text = "" if raw is None else str(raw).strip()
|
||||
if not text:
|
||||
return ""
|
||||
if text.isdigit():
|
||||
return int(text)
|
||||
return text
|
||||
return "" if raw is None else str(raw)
|
||||
|
||||
|
||||
def _public_urls(db, file_ids: list) -> list[str]:
|
||||
from app.services.storage import public_object_url
|
||||
|
||||
urls: list[str] = []
|
||||
for item in file_ids:
|
||||
if isinstance(item, bool):
|
||||
continue
|
||||
try:
|
||||
file_id = int(str(item).strip())
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
if file_id <= 0:
|
||||
continue
|
||||
row = db.get(AdminFile, file_id)
|
||||
if row is None or row.bucket != "public" or not row.object_key:
|
||||
continue
|
||||
urls.append(public_object_url(row.object_key))
|
||||
return urls
|
||||
|
||||
|
||||
def settings_view(db) -> dict:
|
||||
ensure_site_defaults(db)
|
||||
rows = db.scalars(select(SiteSetting)).all()
|
||||
raw = {row.key: row.value for row in rows}
|
||||
view = {key: _present(key, raw.get(key, DEFAULTS.get(key, ""))) for key in SETTING_KEYS}
|
||||
logo_id = raw.get("logo_file_id", "")
|
||||
logo_urls = _public_urls(db, [logo_id]) if str(logo_id).strip() else []
|
||||
view["logoUrl"] = logo_urls[0] if logo_urls else ""
|
||||
banners = view["banner_file_ids"] if isinstance(view["banner_file_ids"], list) else []
|
||||
view["bannerUrls"] = _public_urls(db, banners)
|
||||
return view
|
||||
@@ -0,0 +1,454 @@
|
||||
import re
|
||||
import secrets
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from sqlalchemy import DateTime, Integer, String, Text, func, select
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from app.db import Base
|
||||
|
||||
def _mysql_args() -> dict:
|
||||
return {"mysql_charset": "utf8mb4", "mysql_collate": "utf8mb4_unicode_ci"}
|
||||
|
||||
|
||||
COMPLAINT_STATUSES = ("pending", "processed")
|
||||
DEFAULT_COMPLAINT_WORKDAYS = 30
|
||||
SCOPE_EMPTY = "受理范围说明整理中"
|
||||
PROCESS_EMPTY = "处理流程整理中"
|
||||
MAX_EVIDENCE = 8
|
||||
|
||||
_MOBILE = re.compile(r"^1[3-9]\d{9}$")
|
||||
_EMAIL = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$")
|
||||
_CODE = re.compile(r"^[0-9A-F]{12}$")
|
||||
_NOTICE_PHONE = "discipline_phone"
|
||||
_NOTICE_EMAIL = "discipline_email"
|
||||
_NOTICE_SCOPE = "discipline_scope_html"
|
||||
_NOTICE_PROCESS = "discipline_process_html"
|
||||
|
||||
|
||||
def _now() -> datetime:
|
||||
return datetime.now(timezone.utc).replace(tzinfo=None)
|
||||
|
||||
|
||||
class DisciplineComplaint(Base):
|
||||
__tablename__ = "discipline_complaint"
|
||||
__table_args__ = _mysql_args()
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
||||
code: Mapped[str] = mapped_column(String(16), unique=True, nullable=False)
|
||||
title: Mapped[str] = mapped_column(String(200), nullable=False, default="")
|
||||
subject: Mapped[str] = mapped_column(String(200), nullable=False, default="")
|
||||
body: Mapped[str] = mapped_column(Text, nullable=False, default="")
|
||||
contact_name: Mapped[str] = mapped_column(String(40), nullable=False, default="")
|
||||
mobile_cipher: Mapped[str] = mapped_column(Text, nullable=False, default="")
|
||||
mobile_mask: Mapped[str] = mapped_column(String(32), nullable=False, default="")
|
||||
email_cipher: Mapped[str] = mapped_column(Text, nullable=False, default="")
|
||||
email_mask: Mapped[str] = mapped_column(String(160), nullable=False, default="")
|
||||
status: Mapped[str] = mapped_column(String(16), nullable=False, default="pending", index=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, default=_now, index=True)
|
||||
processed_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
|
||||
processed_by: Mapped[int | None] = mapped_column(Integer, nullable=True)
|
||||
|
||||
|
||||
class DisciplineComplaintFile(Base):
|
||||
__tablename__ = "discipline_complaint_file"
|
||||
__table_args__ = _mysql_args()
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
||||
complaint_id: Mapped[int] = mapped_column(Integer, nullable=False, index=True)
|
||||
file_id: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
position: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
|
||||
|
||||
|
||||
def complaint_workdays(db) -> int:
|
||||
from app.models.content import SiteSetting
|
||||
|
||||
row = db.scalar(select(SiteSetting).where(SiteSetting.key == "complaint_workdays"))
|
||||
raw = (row.value if row else "").strip()
|
||||
if not raw:
|
||||
return DEFAULT_COMPLAINT_WORKDAYS
|
||||
try:
|
||||
value = int(raw)
|
||||
except ValueError:
|
||||
return DEFAULT_COMPLAINT_WORKDAYS
|
||||
if value < 0:
|
||||
return DEFAULT_COMPLAINT_WORKDAYS
|
||||
return value
|
||||
|
||||
|
||||
def _setting(db, key: str) -> str:
|
||||
from app.models.content import SiteSetting
|
||||
|
||||
row = db.scalar(select(SiteSetting).where(SiteSetting.key == key))
|
||||
return "" if row is None or row.value is None else str(row.value)
|
||||
|
||||
|
||||
def _put_setting(db, key: str, value: str) -> None:
|
||||
from app.models.content import SiteSetting
|
||||
|
||||
row = db.scalar(select(SiteSetting).where(SiteSetting.key == key))
|
||||
if row is None:
|
||||
db.add(SiteSetting(key=key, value=value))
|
||||
else:
|
||||
row.value = value
|
||||
|
||||
|
||||
def _visible_text(html: str) -> str:
|
||||
text = re.sub(r"<[^>]+>", "", html or "")
|
||||
return text.replace(" ", " ").replace("\xa0", " ").strip()
|
||||
|
||||
|
||||
def _filter_notice_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
|
||||
|
||||
if len(html or "") > 20000:
|
||||
raise ValueError("说明内容过长")
|
||||
keys = list(db.scalars(select(AdminFile.object_key).where(AdminFile.bucket == "public")))
|
||||
cleaned = filter_html(html or "", list(keys), get_settings().minio_base_url)
|
||||
if not _visible_text(cleaned):
|
||||
return ""
|
||||
return cleaned
|
||||
|
||||
|
||||
def _notice_phone(value: str) -> str:
|
||||
from app.services.html_filter import is_javascript_url
|
||||
|
||||
text = " ".join((value or "").split())
|
||||
if len(text) > 40 or is_javascript_url(text):
|
||||
raise ValueError("举报电话不正确")
|
||||
return text
|
||||
|
||||
|
||||
def _notice_email(value: str) -> str:
|
||||
text = (value or "").strip()
|
||||
if not text:
|
||||
return ""
|
||||
if len(text) > 120 or not _EMAIL.fullmatch(text):
|
||||
raise ValueError("专用邮箱格式不正确")
|
||||
return text
|
||||
|
||||
|
||||
def public_notice(db) -> dict:
|
||||
scope = _setting(db, _NOTICE_SCOPE)
|
||||
process = _setting(db, _NOTICE_PROCESS)
|
||||
return {
|
||||
"phone": _setting(db, _NOTICE_PHONE),
|
||||
"email": _setting(db, _NOTICE_EMAIL),
|
||||
"scopeHtml": scope,
|
||||
"processHtml": process,
|
||||
"scopePlaceholder": "" if scope else SCOPE_EMPTY,
|
||||
"processPlaceholder": "" if process else PROCESS_EMPTY,
|
||||
"workdays": complaint_workdays(db),
|
||||
}
|
||||
|
||||
|
||||
def admin_notice(db) -> dict:
|
||||
return {
|
||||
"phone": _setting(db, _NOTICE_PHONE),
|
||||
"email": _setting(db, _NOTICE_EMAIL),
|
||||
"scopeHtml": _setting(db, _NOTICE_SCOPE),
|
||||
"processHtml": _setting(db, _NOTICE_PROCESS),
|
||||
"workdays": complaint_workdays(db),
|
||||
}
|
||||
|
||||
|
||||
def save_notice(db, payload: dict) -> None:
|
||||
phone = _notice_phone("" if payload.get("phone") is None else str(payload.get("phone")))
|
||||
email = _notice_email("" if payload.get("email") is None else str(payload.get("email")))
|
||||
scope = _filter_notice_html(db, "" if payload.get("scopeHtml") is None else str(payload.get("scopeHtml")))
|
||||
process = _filter_notice_html(
|
||||
db, "" if payload.get("processHtml") is None else str(payload.get("processHtml"))
|
||||
)
|
||||
_put_setting(db, _NOTICE_PHONE, phone)
|
||||
_put_setting(db, _NOTICE_EMAIL, email)
|
||||
_put_setting(db, _NOTICE_SCOPE, scope)
|
||||
_put_setting(db, _NOTICE_PROCESS, process)
|
||||
db.commit()
|
||||
|
||||
|
||||
def _plain(value, *, label: str, limit: int) -> str:
|
||||
text = "" if value is None else str(value)
|
||||
text = text.replace("\r\n", "\n").replace("\r", "\n").strip()
|
||||
if label != "违规事实":
|
||||
text = " ".join(text.split())
|
||||
if not text:
|
||||
raise ValueError(f"请填写{label}")
|
||||
if len(text) > limit:
|
||||
raise ValueError(f"{label}过长")
|
||||
return text
|
||||
|
||||
|
||||
def _mobile(value: str) -> str:
|
||||
text = re.sub(r"[\s-]", "", value or "")
|
||||
if not _MOBILE.fullmatch(text):
|
||||
raise ValueError("请填写有效的联系电话")
|
||||
return text
|
||||
|
||||
|
||||
def _reporter_email(value: str) -> str:
|
||||
text = (value or "").strip()
|
||||
if not text:
|
||||
return ""
|
||||
if len(text) > 120 or not _EMAIL.fullmatch(text):
|
||||
raise ValueError("联系邮箱格式不正确")
|
||||
return text
|
||||
|
||||
|
||||
def _reject_sensitive(db, text: str) -> None:
|
||||
from app.models.content import SensitiveWord
|
||||
|
||||
words = db.scalars(select(SensitiveWord.word)).all()
|
||||
if any(word and word in text for word in words):
|
||||
raise ValueError("内容包含敏感词,请修改后再提交")
|
||||
|
||||
|
||||
def _status_label(status: str) -> str:
|
||||
return "已处理" if status == "processed" else "待处理"
|
||||
|
||||
|
||||
def _new_code(db) -> str:
|
||||
for _ in range(5):
|
||||
code = secrets.token_hex(6).upper()
|
||||
exists = db.scalar(select(DisciplineComplaint.id).where(DisciplineComplaint.code == code))
|
||||
if exists is None:
|
||||
return code
|
||||
raise ValueError("查询码生成失败,请稍后再试")
|
||||
|
||||
|
||||
def normalize_code(value: str) -> str:
|
||||
return re.sub(r"\s+", "", value or "").upper()
|
||||
|
||||
|
||||
def _cleanup_objects(keys: list[str]) -> None:
|
||||
from app.services.storage import remove_stored_object
|
||||
|
||||
for key in keys:
|
||||
try:
|
||||
remove_stored_object("private", key)
|
||||
except Exception:
|
||||
continue
|
||||
|
||||
|
||||
def create_complaint(
|
||||
db,
|
||||
*,
|
||||
title: str,
|
||||
subject: str,
|
||||
body: str,
|
||||
contact_name: str,
|
||||
mobile: str,
|
||||
email: str,
|
||||
files: list[tuple[str, str, bytes]],
|
||||
) -> dict:
|
||||
from app.core.field_crypto import encrypt_text
|
||||
from app.core.masking import mask_email, mask_mobile
|
||||
from app.models.content import AdminFile
|
||||
from app.services.storage import make_object_key, safe_filename, upload_object
|
||||
|
||||
cleaned_title = _plain(title, label="举报标题", limit=200)
|
||||
cleaned_subject = _plain(subject, label="被举报对象", limit=200)
|
||||
cleaned_body = _plain(body, label="违规事实", limit=4000)
|
||||
cleaned_name = _plain(contact_name, label="联系人", limit=40)
|
||||
cleaned_mobile = _mobile(mobile)
|
||||
cleaned_email = _reporter_email(email)
|
||||
_reject_sensitive(db, "\n".join([cleaned_title, cleaned_subject, cleaned_body, cleaned_name]))
|
||||
if not files:
|
||||
raise ValueError("请上传证据材料")
|
||||
if len(files) > MAX_EVIDENCE:
|
||||
raise ValueError("证据材料不能超过 8 个")
|
||||
for filename, _content_type, data in files:
|
||||
if not data:
|
||||
raise ValueError("证据材料不能为空")
|
||||
if not safe_filename(filename):
|
||||
raise ValueError("证据材料文件名不正确")
|
||||
|
||||
mobile_cipher = encrypt_text(cleaned_mobile)
|
||||
email_cipher = encrypt_text(cleaned_email) if cleaned_email else ""
|
||||
stored: list[str] = []
|
||||
try:
|
||||
file_rows = []
|
||||
for filename, content_type, data in files:
|
||||
object_key = make_object_key(filename)
|
||||
upload_object("private", object_key, data, content_type or "application/octet-stream")
|
||||
stored.append(object_key)
|
||||
row = AdminFile(
|
||||
bucket="private",
|
||||
object_key=object_key,
|
||||
filename=safe_filename(filename),
|
||||
content_type=(content_type or "")[:128],
|
||||
size=len(data),
|
||||
created_by=None,
|
||||
)
|
||||
db.add(row)
|
||||
db.flush()
|
||||
file_rows.append(row)
|
||||
complaint = DisciplineComplaint(
|
||||
code=_new_code(db),
|
||||
title=cleaned_title,
|
||||
subject=cleaned_subject,
|
||||
body=cleaned_body,
|
||||
contact_name=cleaned_name,
|
||||
mobile_cipher=mobile_cipher,
|
||||
mobile_mask=mask_mobile(cleaned_mobile),
|
||||
email_cipher=email_cipher,
|
||||
email_mask=mask_email(cleaned_email),
|
||||
status="pending",
|
||||
created_at=_now(),
|
||||
)
|
||||
db.add(complaint)
|
||||
db.flush()
|
||||
for index, row in enumerate(file_rows):
|
||||
db.add(
|
||||
DisciplineComplaintFile(
|
||||
complaint_id=complaint.id,
|
||||
file_id=row.id,
|
||||
position=index,
|
||||
)
|
||||
)
|
||||
db.commit()
|
||||
db.refresh(complaint)
|
||||
except Exception:
|
||||
db.rollback()
|
||||
_cleanup_objects(stored)
|
||||
raise
|
||||
return {
|
||||
"code": complaint.code,
|
||||
"status": complaint.status,
|
||||
"statusLabel": _status_label(complaint.status),
|
||||
"workdays": complaint_workdays(db),
|
||||
}
|
||||
|
||||
|
||||
def _overdue(row: DisciplineComplaint, days: int) -> bool:
|
||||
from app.models.expert import is_overdue
|
||||
|
||||
if row.status != "pending":
|
||||
return False
|
||||
return bool(is_overdue(row.created_at, days))
|
||||
|
||||
|
||||
def _list_item(row: DisciplineComplaint, *, days: int, attachment_count: int) -> dict:
|
||||
return {
|
||||
"id": row.id,
|
||||
"code": row.code,
|
||||
"title": row.title,
|
||||
"subject": row.subject,
|
||||
"contactName": row.contact_name,
|
||||
"mobileMask": row.mobile_mask,
|
||||
"emailMask": row.email_mask,
|
||||
"status": row.status,
|
||||
"statusLabel": _status_label(row.status),
|
||||
"createdAt": row.created_at.isoformat(timespec="seconds") if row.created_at else "",
|
||||
"processedAt": row.processed_at.isoformat(timespec="seconds") if row.processed_at else "",
|
||||
"overdue": _overdue(row, days),
|
||||
"attachmentCount": attachment_count,
|
||||
}
|
||||
|
||||
|
||||
def admin_complaints(db, *, status: str | None = None) -> dict:
|
||||
chosen = (status or "").strip()
|
||||
if chosen and chosen not in COMPLAINT_STATUSES:
|
||||
raise ValueError("状态不正确")
|
||||
days = complaint_workdays(db)
|
||||
filters = []
|
||||
if chosen:
|
||||
filters.append(DisciplineComplaint.status == chosen)
|
||||
rows = db.scalars(
|
||||
select(DisciplineComplaint)
|
||||
.where(*filters)
|
||||
.order_by(DisciplineComplaint.created_at.desc(), DisciplineComplaint.id.desc())
|
||||
).all()
|
||||
counts = dict(
|
||||
db.execute(
|
||||
select(DisciplineComplaintFile.complaint_id, func.count())
|
||||
.group_by(DisciplineComplaintFile.complaint_id)
|
||||
).all()
|
||||
)
|
||||
pending = db.scalar(
|
||||
select(func.count())
|
||||
.select_from(DisciplineComplaint)
|
||||
.where(DisciplineComplaint.status == "pending")
|
||||
) or 0
|
||||
return {
|
||||
"items": [
|
||||
_list_item(row, days=days, attachment_count=int(counts.get(row.id, 0)))
|
||||
for row in rows
|
||||
],
|
||||
"pendingCount": int(pending),
|
||||
"workdays": days,
|
||||
}
|
||||
|
||||
|
||||
def _attachments(db, complaint_id: int) -> list[dict]:
|
||||
from app.models.content import AdminFile
|
||||
from app.services.storage import private_object_url
|
||||
|
||||
links = db.scalars(
|
||||
select(DisciplineComplaintFile)
|
||||
.where(DisciplineComplaintFile.complaint_id == complaint_id)
|
||||
.order_by(DisciplineComplaintFile.position.asc(), DisciplineComplaintFile.id.asc())
|
||||
).all()
|
||||
items = []
|
||||
for link in links:
|
||||
row = db.get(AdminFile, link.file_id)
|
||||
if row is None or row.bucket != "private":
|
||||
continue
|
||||
url, expires_at = private_object_url(row.object_key)
|
||||
items.append(
|
||||
{
|
||||
"id": row.id,
|
||||
"filename": row.filename,
|
||||
"contentType": row.content_type or "",
|
||||
"url": url,
|
||||
"expiresAt": expires_at.isoformat(),
|
||||
}
|
||||
)
|
||||
return items
|
||||
|
||||
|
||||
def admin_complaint(db, complaint_id: int) -> dict | None:
|
||||
from app.core.field_crypto import decrypt_text
|
||||
|
||||
row = db.get(DisciplineComplaint, complaint_id)
|
||||
if row is None:
|
||||
return None
|
||||
days = complaint_workdays(db)
|
||||
item = _list_item(row, days=days, attachment_count=0)
|
||||
item["body"] = row.body
|
||||
item["mobile"] = decrypt_text(row.mobile_cipher)
|
||||
item["email"] = decrypt_text(row.email_cipher) if row.email_cipher else ""
|
||||
item["attachments"] = _attachments(db, row.id)
|
||||
item["attachmentCount"] = len(item["attachments"])
|
||||
return item
|
||||
|
||||
|
||||
def mark_processed(db, complaint_id: int, *, staff_id: int) -> None:
|
||||
row = db.get(DisciplineComplaint, complaint_id)
|
||||
if row is None:
|
||||
raise ValueError("投诉不存在")
|
||||
if row.status != "processed":
|
||||
row.status = "processed"
|
||||
row.processed_at = _now()
|
||||
row.processed_by = staff_id
|
||||
db.commit()
|
||||
|
||||
|
||||
def public_complaint_status(db, code: str) -> dict | None:
|
||||
normalized = normalize_code(code)
|
||||
if not _CODE.fullmatch(normalized):
|
||||
return None
|
||||
row = db.scalar(select(DisciplineComplaint).where(DisciplineComplaint.code == normalized))
|
||||
if row is None:
|
||||
return None
|
||||
days = complaint_workdays(db)
|
||||
created_on = row.created_at.date().isoformat() if row.created_at else ""
|
||||
return {
|
||||
"code": row.code,
|
||||
"status": row.status,
|
||||
"statusLabel": _status_label(row.status),
|
||||
"createdOn": created_on,
|
||||
"workdays": days,
|
||||
"overdue": _overdue(row, days),
|
||||
}
|
||||
@@ -0,0 +1,322 @@
|
||||
from datetime import date, datetime, timedelta, timezone
|
||||
|
||||
from sqlalchemy import DateTime, Integer, String, Text, func, select
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from app.db import Base
|
||||
|
||||
|
||||
def _mysql_args() -> dict:
|
||||
return {"mysql_charset": "utf8mb4", "mysql_collate": "utf8mb4_unicode_ci"}
|
||||
|
||||
|
||||
QUESTION_STATUSES = ("pending", "replied")
|
||||
DEFAULT_REPLY_WORKDAYS = 3
|
||||
|
||||
|
||||
def _now() -> datetime:
|
||||
return datetime.now(timezone.utc).replace(tzinfo=None)
|
||||
|
||||
|
||||
class ExpertQuestion(Base):
|
||||
__tablename__ = "expert_question"
|
||||
__table_args__ = _mysql_args()
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
||||
member_id: Mapped[int] = mapped_column(Integer, nullable=False, index=True)
|
||||
title: Mapped[str] = mapped_column(String(200), nullable=False, default="")
|
||||
body: Mapped[str] = mapped_column(Text, nullable=False, default="")
|
||||
status: Mapped[str] = mapped_column(String(16), nullable=False, default="pending", index=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, default=_now, index=True)
|
||||
replied_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
|
||||
|
||||
|
||||
class ExpertQuestionAttachment(Base):
|
||||
__tablename__ = "expert_question_attachment"
|
||||
__table_args__ = _mysql_args()
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
||||
question_id: Mapped[int] = mapped_column(Integer, nullable=False, index=True)
|
||||
file_id: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
position: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
|
||||
|
||||
|
||||
class ExpertReply(Base):
|
||||
__tablename__ = "expert_reply"
|
||||
__table_args__ = _mysql_args()
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
||||
question_id: Mapped[int] = mapped_column(Integer, unique=True, nullable=False)
|
||||
body_html: Mapped[str] = mapped_column(Text, nullable=False, default="")
|
||||
staff_id: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, default=_now)
|
||||
|
||||
|
||||
class ExpertReplyAttachment(Base):
|
||||
__tablename__ = "expert_reply_attachment"
|
||||
__table_args__ = _mysql_args()
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
||||
reply_id: Mapped[int] = mapped_column(Integer, nullable=False, index=True)
|
||||
file_id: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
position: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
|
||||
|
||||
|
||||
def reply_workdays(db) -> int:
|
||||
from app.models.content import SiteSetting
|
||||
|
||||
row = db.scalar(select(SiteSetting).where(SiteSetting.key == "expert_reply_workdays"))
|
||||
raw = (row.value if row else "").strip()
|
||||
if not raw:
|
||||
return DEFAULT_REPLY_WORKDAYS
|
||||
try:
|
||||
value = int(raw)
|
||||
except ValueError:
|
||||
return DEFAULT_REPLY_WORKDAYS
|
||||
return value if value > 0 else DEFAULT_REPLY_WORKDAYS
|
||||
|
||||
|
||||
def workday_deadline(start: datetime | date, days: int) -> date:
|
||||
current = start.date() if isinstance(start, datetime) else start
|
||||
remaining = max(int(days), 0)
|
||||
while remaining > 0:
|
||||
current = current + timedelta(days=1)
|
||||
if current.weekday() < 5:
|
||||
remaining -= 1
|
||||
return current
|
||||
|
||||
|
||||
def is_overdue(created_at: datetime, days: int, *, now: datetime | None = None) -> bool:
|
||||
if created_at is None:
|
||||
return False
|
||||
current = now or _now()
|
||||
return current.date() > workday_deadline(created_at, days)
|
||||
|
||||
|
||||
def _private_file(db, file_id: int):
|
||||
from app.models.content import AdminFile
|
||||
|
||||
if file_id is None:
|
||||
return None
|
||||
row = db.get(AdminFile, file_id)
|
||||
if row is None or row.bucket != "private":
|
||||
return None
|
||||
return row
|
||||
|
||||
|
||||
def _attachment_payload(db, file_id: int) -> dict | None:
|
||||
from app.services.storage import private_object_url
|
||||
|
||||
row = _private_file(db, file_id)
|
||||
if row is None:
|
||||
return None
|
||||
url, expires_at = private_object_url(row.object_key)
|
||||
return {
|
||||
"id": row.id,
|
||||
"filename": row.filename,
|
||||
"contentType": row.content_type or "",
|
||||
"url": url,
|
||||
"expiresAt": expires_at.isoformat(),
|
||||
}
|
||||
|
||||
|
||||
def _question_attachments(db, question_id: int) -> list[dict]:
|
||||
links = db.scalars(
|
||||
select(ExpertQuestionAttachment)
|
||||
.where(ExpertQuestionAttachment.question_id == question_id)
|
||||
.order_by(ExpertQuestionAttachment.position.asc(), ExpertQuestionAttachment.id.asc())
|
||||
).all()
|
||||
items = []
|
||||
for link in links:
|
||||
payload = _attachment_payload(db, link.file_id)
|
||||
if payload is not None:
|
||||
items.append(payload)
|
||||
return items
|
||||
|
||||
|
||||
def _reply_attachments(db, reply_id: int) -> list[dict]:
|
||||
links = db.scalars(
|
||||
select(ExpertReplyAttachment)
|
||||
.where(ExpertReplyAttachment.reply_id == reply_id)
|
||||
.order_by(ExpertReplyAttachment.position.asc(), ExpertReplyAttachment.id.asc())
|
||||
).all()
|
||||
items = []
|
||||
for link in links:
|
||||
payload = _attachment_payload(db, link.file_id)
|
||||
if payload is not None:
|
||||
items.append(payload)
|
||||
return items
|
||||
|
||||
|
||||
def _question_list_item(db, row: ExpertQuestion, *, days: int, include_member: bool = False) -> dict:
|
||||
from app.models.member import get_member_by_id
|
||||
|
||||
item = {
|
||||
"id": row.id,
|
||||
"title": row.title,
|
||||
"status": row.status,
|
||||
"statusLabel": "已回复" if row.status == "replied" else "待回复",
|
||||
"createdAt": row.created_at.isoformat(timespec="seconds") if row.created_at else "",
|
||||
"repliedAt": row.replied_at.isoformat(timespec="seconds") if row.replied_at else "",
|
||||
"overdue": bool(row.status == "pending" and is_overdue(row.created_at, days)),
|
||||
}
|
||||
if include_member:
|
||||
member = get_member_by_id(db, row.member_id)
|
||||
item["memberId"] = row.member_id
|
||||
item["memberEmail"] = member.email if member else ""
|
||||
return item
|
||||
|
||||
|
||||
def create_question(db, *, member_id: int, title: str, body: str, attachment_file_ids: list[int]) -> int:
|
||||
cleaned_title = (title or "").strip()
|
||||
cleaned_body = (body or "").strip()
|
||||
if not cleaned_title:
|
||||
raise ValueError("标题不能为空")
|
||||
if not cleaned_body:
|
||||
raise ValueError("正文不能为空")
|
||||
if len(cleaned_title) > 200:
|
||||
raise ValueError("标题过长")
|
||||
files = []
|
||||
for file_id in attachment_file_ids or []:
|
||||
row = _private_file(db, file_id)
|
||||
if row is None:
|
||||
raise ValueError("附件必须是已上传的私有文件")
|
||||
files.append(row)
|
||||
question = ExpertQuestion(
|
||||
member_id=member_id,
|
||||
title=cleaned_title,
|
||||
body=cleaned_body,
|
||||
status="pending",
|
||||
created_at=_now(),
|
||||
)
|
||||
db.add(question)
|
||||
db.flush()
|
||||
for index, file_row in enumerate(files):
|
||||
db.add(
|
||||
ExpertQuestionAttachment(
|
||||
question_id=question.id,
|
||||
file_id=file_row.id,
|
||||
position=index,
|
||||
)
|
||||
)
|
||||
db.commit()
|
||||
db.refresh(question)
|
||||
return question.id
|
||||
|
||||
|
||||
def member_questions(db, member_id: int) -> dict:
|
||||
days = reply_workdays(db)
|
||||
rows = db.scalars(
|
||||
select(ExpertQuestion)
|
||||
.where(ExpertQuestion.member_id == member_id)
|
||||
.order_by(ExpertQuestion.created_at.desc(), ExpertQuestion.id.desc())
|
||||
).all()
|
||||
return {"items": [_question_list_item(db, row, days=days) for row in rows]}
|
||||
|
||||
|
||||
def member_question(db, member_id: int, question_id: int) -> dict | None:
|
||||
row = db.get(ExpertQuestion, question_id)
|
||||
if row is None or row.member_id != member_id:
|
||||
return None
|
||||
days = reply_workdays(db)
|
||||
body = _question_list_item(db, row, days=days)
|
||||
body["body"] = row.body
|
||||
body["attachments"] = _question_attachments(db, row.id)
|
||||
reply = db.scalar(select(ExpertReply).where(ExpertReply.question_id == row.id))
|
||||
if reply is not None:
|
||||
body["reply"] = {
|
||||
"bodyHtml": reply.body_html,
|
||||
"createdAt": reply.created_at.isoformat(timespec="seconds") if reply.created_at else "",
|
||||
"attachments": _reply_attachments(db, reply.id),
|
||||
}
|
||||
return body
|
||||
|
||||
|
||||
def pending_count(db) -> int:
|
||||
return int(
|
||||
db.scalar(
|
||||
select(func.count())
|
||||
.select_from(ExpertQuestion)
|
||||
.where(ExpertQuestion.status == "pending")
|
||||
)
|
||||
or 0
|
||||
)
|
||||
|
||||
|
||||
def admin_questions(db, *, status: str | None = None) -> dict:
|
||||
days = reply_workdays(db)
|
||||
stmt = select(ExpertQuestion).order_by(ExpertQuestion.created_at.desc(), ExpertQuestion.id.desc())
|
||||
if status in QUESTION_STATUSES:
|
||||
stmt = stmt.where(ExpertQuestion.status == status)
|
||||
rows = db.scalars(stmt).all()
|
||||
return {
|
||||
"items": [_question_list_item(db, row, days=days, include_member=True) for row in rows],
|
||||
"pendingCount": pending_count(db),
|
||||
"replyWorkdays": days,
|
||||
}
|
||||
|
||||
|
||||
def admin_question(db, question_id: int) -> dict | None:
|
||||
row = db.get(ExpertQuestion, question_id)
|
||||
if row is None:
|
||||
return None
|
||||
days = reply_workdays(db)
|
||||
body = _question_list_item(db, row, days=days, include_member=True)
|
||||
body["body"] = row.body
|
||||
body["attachments"] = _question_attachments(db, row.id)
|
||||
reply = db.scalar(select(ExpertReply).where(ExpertReply.question_id == row.id))
|
||||
if reply is not None:
|
||||
body["reply"] = {
|
||||
"bodyHtml": reply.body_html,
|
||||
"createdAt": reply.created_at.isoformat(timespec="seconds") if reply.created_at else "",
|
||||
"attachments": _reply_attachments(db, reply.id),
|
||||
}
|
||||
return body
|
||||
|
||||
|
||||
def reply_question(
|
||||
db,
|
||||
*,
|
||||
question_id: int,
|
||||
staff_id: int,
|
||||
body_html: str,
|
||||
attachment_file_ids: list[int],
|
||||
) -> None:
|
||||
from app.core.config import get_settings
|
||||
from app.models.content import AdminFile
|
||||
from app.services.html_filter import filter_html
|
||||
|
||||
question = db.get(ExpertQuestion, question_id)
|
||||
if question is None:
|
||||
raise ValueError("提问不存在")
|
||||
if question.status != "pending":
|
||||
raise ValueError("该提问已回复")
|
||||
files = []
|
||||
for file_id in attachment_file_ids or []:
|
||||
row = _private_file(db, file_id)
|
||||
if row is None:
|
||||
raise ValueError("附件必须是已上传的私有文件")
|
||||
files.append(row)
|
||||
keys = list(db.scalars(select(AdminFile.object_key).where(AdminFile.bucket == "public")))
|
||||
cleaned = filter_html(body_html or "", list(keys), get_settings().minio_base_url)
|
||||
if not cleaned.strip():
|
||||
raise ValueError("回复正文不能为空")
|
||||
reply = ExpertReply(
|
||||
question_id=question.id,
|
||||
body_html=cleaned,
|
||||
staff_id=staff_id,
|
||||
created_at=_now(),
|
||||
)
|
||||
db.add(reply)
|
||||
db.flush()
|
||||
for index, file_row in enumerate(files):
|
||||
db.add(
|
||||
ExpertReplyAttachment(
|
||||
reply_id=reply.id,
|
||||
file_id=file_row.id,
|
||||
position=index,
|
||||
)
|
||||
)
|
||||
question.status = "replied"
|
||||
question.replied_at = _now()
|
||||
db.commit()
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,104 @@
|
||||
"""合规正文:隐私政策、使用条款、网站声明。"""
|
||||
|
||||
from sqlalchemy import Boolean, String, Text, select
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from app.db import Base
|
||||
|
||||
|
||||
def _mysql_args() -> dict:
|
||||
return {"mysql_charset": "utf8mb4", "mysql_collate": "utf8mb4_unicode_ci"}
|
||||
|
||||
|
||||
LEGAL_PAGE_KEYS = ("privacy", "terms", "statement")
|
||||
LEGAL_PAGE_TITLES = {
|
||||
"privacy": "隐私政策",
|
||||
"terms": "使用条款",
|
||||
"statement": "网站声明",
|
||||
}
|
||||
LEGAL_PAGE_PLACEHOLDERS = {
|
||||
"privacy": "隐私政策整理中",
|
||||
"terms": "使用条款整理中",
|
||||
"statement": "网站声明整理中",
|
||||
}
|
||||
LEGAL_PAGE_PATHS = {
|
||||
"privacy": "/legal/privacy",
|
||||
"terms": "/legal/terms",
|
||||
"statement": "/legal/statement",
|
||||
}
|
||||
|
||||
|
||||
class LegalPage(Base):
|
||||
__tablename__ = "legal_page"
|
||||
__table_args__ = _mysql_args()
|
||||
|
||||
page_key: Mapped[str] = mapped_column(String(32), primary_key=True)
|
||||
body_html: Mapped[str] = mapped_column(Text, nullable=False, default="")
|
||||
published: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)
|
||||
|
||||
|
||||
def save_legal_page(db, page_key: str, payload: dict) -> None:
|
||||
if page_key not in LEGAL_PAGE_KEYS:
|
||||
raise ValueError("合规页键不正确")
|
||||
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")))
|
||||
cleaned = filter_html(
|
||||
payload.get("bodyHtml") or "",
|
||||
list(keys),
|
||||
get_settings().minio_base_url,
|
||||
)
|
||||
row = db.get(LegalPage, page_key)
|
||||
if row is None:
|
||||
row = LegalPage(page_key=page_key)
|
||||
db.add(row)
|
||||
row.body_html = cleaned
|
||||
row.published = bool(payload.get("published", False))
|
||||
db.commit()
|
||||
|
||||
|
||||
def admin_legal_page(db, page_key: str) -> dict | None:
|
||||
if page_key not in LEGAL_PAGE_KEYS:
|
||||
return None
|
||||
row = db.get(LegalPage, page_key)
|
||||
return {
|
||||
"key": page_key,
|
||||
"title": LEGAL_PAGE_TITLES[page_key],
|
||||
"published": bool(row.published) if row else False,
|
||||
"bodyHtml": row.body_html if row else "",
|
||||
}
|
||||
|
||||
|
||||
def public_legal_page(db, page_key: str) -> dict | None:
|
||||
if page_key not in LEGAL_PAGE_KEYS:
|
||||
return None
|
||||
placeholder = LEGAL_PAGE_PLACEHOLDERS[page_key]
|
||||
row = db.get(LegalPage, page_key)
|
||||
body = (row.body_html if row else "").strip()
|
||||
if row is None or not row.published or not body:
|
||||
return {
|
||||
"key": page_key,
|
||||
"title": LEGAL_PAGE_TITLES[page_key],
|
||||
"placeholder": placeholder,
|
||||
}
|
||||
return {
|
||||
"key": page_key,
|
||||
"title": LEGAL_PAGE_TITLES[page_key],
|
||||
"bodyHtml": row.body_html,
|
||||
}
|
||||
|
||||
|
||||
def public_compliance_links() -> dict:
|
||||
"""页脚固定三项,链到站内合规正文页。"""
|
||||
return {
|
||||
"links": [
|
||||
{
|
||||
"label": LEGAL_PAGE_TITLES[key],
|
||||
"url": LEGAL_PAGE_PATHS[key],
|
||||
"navigation": "sameWindow",
|
||||
}
|
||||
for key in LEGAL_PAGE_KEYS
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from sqlalchemy import DateTime, Integer, String, select
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from app.db import Base
|
||||
|
||||
|
||||
def _mysql_args() -> dict:
|
||||
return {"mysql_charset": "utf8mb4", "mysql_collate": "utf8mb4_unicode_ci"}
|
||||
|
||||
|
||||
MEMBER_STATUSES = ("active", "disabled", "cancelled")
|
||||
|
||||
|
||||
def _now() -> datetime:
|
||||
return datetime.now(timezone.utc).replace(tzinfo=None)
|
||||
|
||||
|
||||
class SiteMember(Base):
|
||||
__tablename__ = "site_member"
|
||||
__table_args__ = _mysql_args()
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
||||
email: Mapped[str] = mapped_column(String(191), unique=True, nullable=False)
|
||||
password_hash: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
status: Mapped[str] = mapped_column(String(16), nullable=False, default="active")
|
||||
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)
|
||||
|
||||
|
||||
def get_member_by_email(db, email: str) -> SiteMember | None:
|
||||
normalized = (email or "").strip().lower()
|
||||
if not normalized:
|
||||
return None
|
||||
return db.scalar(select(SiteMember).where(SiteMember.email == normalized))
|
||||
|
||||
|
||||
def get_member_by_id(db, member_id: int) -> SiteMember | None:
|
||||
return db.get(SiteMember, member_id)
|
||||
|
||||
|
||||
def create_member(db, *, email: str, password_hash: str, privacy_accepted_at: datetime) -> SiteMember:
|
||||
row = SiteMember(
|
||||
email=email.strip().lower(),
|
||||
password_hash=password_hash,
|
||||
status="active",
|
||||
privacy_accepted_at=privacy_accepted_at,
|
||||
created_at=_now(),
|
||||
updated_at=_now(),
|
||||
)
|
||||
db.add(row)
|
||||
db.commit()
|
||||
db.refresh(row)
|
||||
return row
|
||||
|
||||
|
||||
def set_member_password(db, member: SiteMember, password_hash: str) -> None:
|
||||
member.password_hash = password_hash
|
||||
member.updated_at = _now()
|
||||
db.commit()
|
||||
@@ -0,0 +1,79 @@
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from sqlalchemy import Boolean, DateTime, ForeignKey, String, Text, UniqueConstraint
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from app.db import Base
|
||||
|
||||
|
||||
def utcnow() -> datetime:
|
||||
return datetime.now(timezone.utc)
|
||||
|
||||
|
||||
class AdminUser(Base):
|
||||
__tablename__ = "admin_user"
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True)
|
||||
username: Mapped[str] = mapped_column(String(64), unique=True, nullable=False)
|
||||
password_hash: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
display_name: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
mobile_cipher: Mapped[str | None] = mapped_column(Text, nullable=True)
|
||||
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)
|
||||
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(
|
||||
DateTime(timezone=True), nullable=False, default=utcnow, onupdate=utcnow
|
||||
)
|
||||
|
||||
|
||||
class AdminRole(Base):
|
||||
__tablename__ = "admin_role"
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True)
|
||||
code: Mapped[str] = mapped_column(String(64), unique=True, nullable=False)
|
||||
name: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
description: Mapped[str | None] = mapped_column(Text, nullable=True)
|
||||
status: Mapped[str] = mapped_column(String(16), nullable=False, default="active")
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, default=utcnow)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
DateTime(timezone=True), nullable=False, default=utcnow, onupdate=utcnow
|
||||
)
|
||||
|
||||
|
||||
class AdminResource(Base):
|
||||
__tablename__ = "admin_resource"
|
||||
__table_args__ = (
|
||||
# parent_id 为空时,MySQL 唯一索引不会拦住重复的根名称,根节点在服务层再查一次。
|
||||
UniqueConstraint("parent_id", "name", name="uq_admin_resource_parent_name"),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True)
|
||||
parent_id: Mapped[int | None] = mapped_column(ForeignKey("admin_resource.id"), nullable=True)
|
||||
type: Mapped[str] = mapped_column(String(16), nullable=False)
|
||||
name: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
title: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
path: Mapped[str] = mapped_column(String(255), nullable=False, default="")
|
||||
component: Mapped[str] = mapped_column(String(255), nullable=False, default="")
|
||||
icon: Mapped[str] = mapped_column(String(64), nullable=False, default="")
|
||||
permission: Mapped[str] = mapped_column(String(64), nullable=False, default="")
|
||||
sort: Mapped[int] = mapped_column(nullable=False, default=0)
|
||||
visible: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True)
|
||||
status: Mapped[str] = mapped_column(String(16), nullable=False, default="active")
|
||||
|
||||
|
||||
class AdminUserRole(Base):
|
||||
__tablename__ = "admin_user_role"
|
||||
|
||||
user_id: Mapped[int] = mapped_column(ForeignKey("admin_user.id", ondelete="CASCADE"), primary_key=True)
|
||||
role_id: Mapped[int] = mapped_column(ForeignKey("admin_role.id", ondelete="CASCADE"), primary_key=True)
|
||||
|
||||
|
||||
class AdminRoleResource(Base):
|
||||
__tablename__ = "admin_role_resource"
|
||||
|
||||
role_id: Mapped[int] = mapped_column(ForeignKey("admin_role.id", ondelete="CASCADE"), primary_key=True)
|
||||
resource_id: Mapped[int] = mapped_column(
|
||||
ForeignKey("admin_resource.id", ondelete="CASCADE"), primary_key=True
|
||||
)
|
||||
@@ -0,0 +1,140 @@
|
||||
"""报告备案:工作人员登记,公众按编号对照。"""
|
||||
|
||||
from datetime import date
|
||||
|
||||
from sqlalchemy import Boolean, Date, Integer, String, select
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from app.db import Base
|
||||
|
||||
FOUND_NOTICE = "以出具机构数据为准,协会结果仅供参考。"
|
||||
MISSING_NOTICE = "协会备案库没有该编号,请向出具机构核实。"
|
||||
|
||||
|
||||
def _mysql_args() -> dict:
|
||||
return {"mysql_charset": "utf8mb4", "mysql_collate": "utf8mb4_unicode_ci"}
|
||||
|
||||
|
||||
class ReportFiling(Base):
|
||||
__tablename__ = "report_filing"
|
||||
__table_args__ = _mysql_args()
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
||||
institution_name: Mapped[str] = mapped_column(String(200), nullable=False)
|
||||
report_number: Mapped[str] = mapped_column(String(64), nullable=False, unique=True)
|
||||
issued_on: Mapped[date] = mapped_column(Date, nullable=False)
|
||||
published: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)
|
||||
|
||||
|
||||
def _institution(value: str) -> str:
|
||||
if not isinstance(value, str) or not value.strip():
|
||||
raise ValueError("请填写出具机构")
|
||||
text = value.strip()
|
||||
if len(text) > 200:
|
||||
raise ValueError("出具机构过长")
|
||||
return text
|
||||
|
||||
|
||||
def _number(value: str) -> str:
|
||||
if not isinstance(value, str) or not value.strip():
|
||||
raise ValueError("请填写报告编号")
|
||||
text = value.strip()
|
||||
if len(text) > 64:
|
||||
raise ValueError("报告编号过长")
|
||||
return text
|
||||
|
||||
|
||||
def _issued_on(value: str) -> date:
|
||||
if not isinstance(value, str) or not value.strip():
|
||||
raise ValueError("请填写出具日期")
|
||||
try:
|
||||
return date.fromisoformat(value.strip())
|
||||
except ValueError as exc:
|
||||
raise ValueError("出具日期不正确") from exc
|
||||
|
||||
|
||||
def _admin_filing(row: ReportFiling) -> dict:
|
||||
return {
|
||||
"id": row.id,
|
||||
"institutionName": row.institution_name,
|
||||
"reportNumber": row.report_number,
|
||||
"issuedOn": row.issued_on.isoformat(),
|
||||
"published": bool(row.published),
|
||||
}
|
||||
|
||||
|
||||
def list_filings(db) -> dict:
|
||||
rows = db.scalars(select(ReportFiling).order_by(ReportFiling.id.desc())).all()
|
||||
return {"items": [_admin_filing(row) for row in rows]}
|
||||
|
||||
|
||||
def create_filing(db, *, institution_name: str, report_number: str, issued_on: str, published: bool) -> int:
|
||||
row = ReportFiling(
|
||||
institution_name=_institution(institution_name),
|
||||
report_number=_number(report_number),
|
||||
issued_on=_issued_on(issued_on),
|
||||
published=bool(published),
|
||||
)
|
||||
db.add(row)
|
||||
try:
|
||||
db.commit()
|
||||
except IntegrityError as exc:
|
||||
db.rollback()
|
||||
raise ValueError("报告编号已存在") from exc
|
||||
return row.id
|
||||
|
||||
|
||||
def update_filing(
|
||||
db,
|
||||
filing_id: int,
|
||||
*,
|
||||
institution_name: str,
|
||||
report_number: str,
|
||||
issued_on: str,
|
||||
published: bool,
|
||||
) -> None:
|
||||
row = db.get(ReportFiling, filing_id)
|
||||
if row is None:
|
||||
raise ValueError("备案不存在")
|
||||
number = _number(report_number)
|
||||
taken = db.scalar(select(ReportFiling.id).where(ReportFiling.report_number == number, ReportFiling.id != row.id))
|
||||
if taken is not None:
|
||||
raise ValueError("报告编号已存在")
|
||||
row.institution_name = _institution(institution_name)
|
||||
row.report_number = number
|
||||
row.issued_on = _issued_on(issued_on)
|
||||
row.published = bool(published)
|
||||
try:
|
||||
db.commit()
|
||||
except IntegrityError as exc:
|
||||
db.rollback()
|
||||
raise ValueError("报告编号已存在") from exc
|
||||
|
||||
|
||||
def delete_filing(db, filing_id: int) -> None:
|
||||
row = db.get(ReportFiling, filing_id)
|
||||
if row is None:
|
||||
raise ValueError("备案不存在")
|
||||
db.delete(row)
|
||||
db.commit()
|
||||
|
||||
|
||||
def query_filing(db, number: str) -> dict:
|
||||
if not isinstance(number, str) or not number.strip():
|
||||
raise ValueError("请填写报告编号")
|
||||
text = number.strip()
|
||||
if len(text) > 64:
|
||||
return {"found": False, "notice": MISSING_NOTICE}
|
||||
row = db.scalar(
|
||||
select(ReportFiling).where(ReportFiling.report_number == text, ReportFiling.published.is_(True))
|
||||
)
|
||||
if row is None:
|
||||
return {"found": False, "notice": MISSING_NOTICE}
|
||||
return {
|
||||
"found": True,
|
||||
"institutionName": row.institution_name,
|
||||
"reportNumber": row.report_number,
|
||||
"issuedOn": row.issued_on.isoformat(),
|
||||
"notice": FOUND_NOTICE,
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from sqlalchemy import DateTime, Index, Integer, String, func
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from app.db import Base
|
||||
|
||||
|
||||
def _utcnow() -> datetime:
|
||||
return datetime.now(timezone.utc).replace(tzinfo=None)
|
||||
|
||||
|
||||
class AdminAuditLog(Base):
|
||||
__tablename__ = "admin_audit_log"
|
||||
__table_args__ = (
|
||||
Index("ix_admin_audit_log_username", "username"),
|
||||
Index("ix_admin_audit_log_created_at", "created_at"),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
||||
user_id: Mapped[int | None] = mapped_column(Integer, nullable=True)
|
||||
username: Mapped[str | None] = mapped_column(String(64), nullable=True)
|
||||
method: Mapped[str] = mapped_column(String(16), nullable=False)
|
||||
path: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
status_code: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
ip: Mapped[str] = mapped_column(String(64), nullable=False, default="", server_default="")
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
DateTime,
|
||||
nullable=False,
|
||||
default=_utcnow,
|
||||
server_default=func.now(),
|
||||
)
|
||||
|
||||
|
||||
class AdminIpBlacklist(Base):
|
||||
__tablename__ = "admin_ip_blacklist"
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
||||
ip: Mapped[str] = mapped_column(String(64), unique=True, nullable=False)
|
||||
remark: Mapped[str] = mapped_column(String(255), nullable=False, default="", server_default="")
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
DateTime,
|
||||
nullable=False,
|
||||
default=_utcnow,
|
||||
server_default=func.now(),
|
||||
)
|
||||
@@ -0,0 +1,803 @@
|
||||
"""上传案例:会员提交的结构化记录,与案例库栏目文章分开。"""
|
||||
|
||||
import json
|
||||
from datetime import date, datetime, timezone
|
||||
from decimal import Decimal, InvalidOperation
|
||||
from pathlib import Path
|
||||
|
||||
from sqlalchemy import Date, DateTime, Integer, String, Text, or_, select
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from app.db import Base
|
||||
|
||||
PHOTO_MAX_BYTES = 5 * 1024 * 1024
|
||||
PAGE_SIZES = (10, 20, 100)
|
||||
KIND_LABELS = {
|
||||
"residential": "住宅",
|
||||
"commercial": "商业",
|
||||
"office": "办公",
|
||||
"industrial": "工业",
|
||||
}
|
||||
OPEN_KINDS = frozenset({"residential", "commercial", "office", "industrial"})
|
||||
CASE_TYPES = ("买卖成交", "拍卖成交", "月租金成交", "评估案例")
|
||||
STRUCTURES = ("钢混", "砖混", "混合", "钢结构")
|
||||
DECORATIONS = ("毛坯", "简易", "中档", "高档", "豪华")
|
||||
TOTAL_FLOORS = tuple(str(i) for i in range(1, 61))
|
||||
FLOOR_NOS = ("-4", "-3", "-2", "-1") + TOTAL_FLOORS
|
||||
PURPOSES = (
|
||||
"普通住宅",
|
||||
"公寓",
|
||||
"酒店式公寓",
|
||||
"独立别墅",
|
||||
"双拼别墅",
|
||||
"联排别墅",
|
||||
"停车位",
|
||||
"地下室",
|
||||
"其他",
|
||||
)
|
||||
LAYOUT_STRUCTURES = ("平面", "复式", "跃式", "错层", "LOFT")
|
||||
OFFICE_LAYOUT_STRUCTURES = ("办公楼(中间过道两边办公室)", "写字楼(大开间)")
|
||||
LAYOUTS = (
|
||||
"单间",
|
||||
"单身公寓",
|
||||
"一室一厅",
|
||||
"两室一厅",
|
||||
"两室两厅",
|
||||
"三室一厅",
|
||||
"三室两厅",
|
||||
"四室两厅",
|
||||
"五室两厅",
|
||||
"六室两厅",
|
||||
"七室及以上",
|
||||
)
|
||||
COMMERCIAL_LAYOUTS = ("大开间", "隔档")
|
||||
STREET_FRONTAGES = ("单面临街", "双面临街", "三面临街", "十字路口拐角", "不临街(商场或市场内铺面)")
|
||||
FOOT_TRAFFICS = ("小", "较小", "一般", "较大", "大")
|
||||
SHOP_TYPES = ("住宅底商", "商业街商铺", "临街门面", "购物中心/百货内铺", "酒店宾馆内铺", "其他")
|
||||
BUSINESS_FORMATS = (
|
||||
"空置",
|
||||
"餐饮",
|
||||
"服饰鞋帽箱包",
|
||||
"休闲娱乐",
|
||||
"美容美发",
|
||||
"服务业",
|
||||
"百货",
|
||||
"酒店宾馆",
|
||||
"家居建材",
|
||||
"酒吧",
|
||||
"汽车维修美容",
|
||||
"其他",
|
||||
)
|
||||
ORIENTATIONS = ("东", "南", "西", "北", "东南", "西南", "东北", "西北", "南北", "东西")
|
||||
VALUE_INCLUDES = ("装饰装修", "家具用具", "停车位", "花园", "地下室")
|
||||
INDUSTRIAL_FLOORS = tuple(str(i) for i in range(1, 9))
|
||||
INDUSTRIAL_LAYOUTS = ("开间",)
|
||||
INDUSTRIAL_DIRECTIONS = ("南北", "东西")
|
||||
ROAD_FRONTAGES = ("主干道", "次干道", "街巷")
|
||||
INDUSTRY_TYPES = ("食品饮料加工", "机械制造", "水泥厂", "热力公司", "其他")
|
||||
INDUSTRIAL_VALUE_INCLUDES = ("装饰装修", "家具用具")
|
||||
|
||||
_REGIONS: list | None = None
|
||||
|
||||
|
||||
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 UploadedCase(Base):
|
||||
__tablename__ = "uploaded_case"
|
||||
__table_args__ = _mysql_args()
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
||||
kind: Mapped[str] = mapped_column(String(32), nullable=False, index=True)
|
||||
member_id: Mapped[int] = mapped_column(Integer, nullable=False, index=True)
|
||||
member_email: Mapped[str] = mapped_column(String(191), nullable=False, default="")
|
||||
case_type: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||
province: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
city: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
district: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
estate_name: Mapped[str] = mapped_column(String(200), nullable=False)
|
||||
structure: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||
case_date: Mapped[date] = mapped_column(Date, nullable=False)
|
||||
location: Mapped[str] = mapped_column(String(500), nullable=False)
|
||||
built_year: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
total_floors: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
floor_no: Mapped[str] = mapped_column(String(8), nullable=False)
|
||||
purpose: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||
layout_structure: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||
decoration: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||
value_includes: Mapped[str] = mapped_column(Text, nullable=False, default="[]")
|
||||
area: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||
layout: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||
orientation: Mapped[str] = mapped_column(String(16), nullable=False)
|
||||
unit_price: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||
remark: Mapped[str] = mapped_column(Text, nullable=False, default="")
|
||||
institution_name: Mapped[str] = mapped_column(String(200), nullable=False)
|
||||
street_frontage: Mapped[str] = mapped_column(String(64), nullable=False, default="")
|
||||
foot_traffic: Mapped[str] = mapped_column(String(32), nullable=False, default="")
|
||||
shop_type: Mapped[str] = mapped_column(String(64), nullable=False, default="")
|
||||
business_formats: Mapped[str] = mapped_column(Text, nullable=False, default="[]")
|
||||
heading: Mapped[str] = mapped_column(String(16), nullable=False, default="")
|
||||
road_frontage: Mapped[str] = mapped_column(String(32), nullable=False, default="")
|
||||
industry_type: Mapped[str] = mapped_column(String(32), nullable=False, default="")
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, default=_now, index=True)
|
||||
|
||||
|
||||
class UploadedCasePhoto(Base):
|
||||
__tablename__ = "uploaded_case_photo"
|
||||
__table_args__ = _mysql_args()
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
||||
case_id: Mapped[int] = mapped_column(Integer, nullable=False, index=True)
|
||||
file_id: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
position: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
|
||||
|
||||
|
||||
def regions() -> list:
|
||||
global _REGIONS
|
||||
if _REGIONS is None:
|
||||
path = Path(__file__).resolve().parents[1] / "data" / "china_regions.json"
|
||||
_REGIONS = json.loads(path.read_text(encoding="utf-8"))
|
||||
return _REGIONS
|
||||
|
||||
|
||||
def built_years(today: date | None = None) -> list[int]:
|
||||
year = (today or date.today()).year
|
||||
return list(range(1980, year + 1))
|
||||
|
||||
|
||||
def ensure_uploaded_case_columns(db) -> None:
|
||||
bind = db.get_bind()
|
||||
if bind.dialect.name != "mysql":
|
||||
return
|
||||
from sqlalchemy import inspect, text
|
||||
|
||||
names = {column["name"] for column in inspect(bind).get_columns("uploaded_case")}
|
||||
statements = []
|
||||
if "street_frontage" not in names:
|
||||
statements.append(
|
||||
"ALTER TABLE uploaded_case ADD COLUMN street_frontage VARCHAR(64) NOT NULL DEFAULT ''"
|
||||
)
|
||||
if "foot_traffic" not in names:
|
||||
statements.append(
|
||||
"ALTER TABLE uploaded_case ADD COLUMN foot_traffic VARCHAR(32) NOT NULL DEFAULT ''"
|
||||
)
|
||||
if "shop_type" not in names:
|
||||
statements.append("ALTER TABLE uploaded_case ADD COLUMN shop_type VARCHAR(64) NOT NULL DEFAULT ''")
|
||||
if "business_formats" not in names:
|
||||
statements.append("ALTER TABLE uploaded_case ADD COLUMN business_formats TEXT NULL")
|
||||
if "heading" not in names:
|
||||
statements.append("ALTER TABLE uploaded_case ADD COLUMN heading VARCHAR(16) NOT NULL DEFAULT ''")
|
||||
if "road_frontage" not in names:
|
||||
statements.append("ALTER TABLE uploaded_case ADD COLUMN road_frontage VARCHAR(32) NOT NULL DEFAULT ''")
|
||||
if "industry_type" not in names:
|
||||
statements.append("ALTER TABLE uploaded_case ADD COLUMN industry_type VARCHAR(32) NOT NULL DEFAULT ''")
|
||||
for statement in statements:
|
||||
db.execute(text(statement))
|
||||
if "business_formats" not in names:
|
||||
db.execute(text("UPDATE uploaded_case SET business_formats = '[]' WHERE business_formats IS NULL"))
|
||||
if statements:
|
||||
db.commit()
|
||||
|
||||
|
||||
def commercial_options(today: date | None = None) -> dict:
|
||||
return {
|
||||
"caseTypes": list(CASE_TYPES),
|
||||
"structures": list(STRUCTURES),
|
||||
"builtYears": built_years(today),
|
||||
"totalFloors": list(TOTAL_FLOORS),
|
||||
"floorNos": list(FLOOR_NOS),
|
||||
"layouts": list(COMMERCIAL_LAYOUTS),
|
||||
"decorations": list(DECORATIONS),
|
||||
"streetFrontages": list(STREET_FRONTAGES),
|
||||
"orientations": list(ORIENTATIONS),
|
||||
"footTraffics": list(FOOT_TRAFFICS),
|
||||
"shopTypes": list(SHOP_TYPES),
|
||||
"businessFormats": list(BUSINESS_FORMATS),
|
||||
"valueIncludes": list(VALUE_INCLUDES),
|
||||
}
|
||||
|
||||
|
||||
def office_options(today: date | None = None) -> dict:
|
||||
return {
|
||||
"caseTypes": list(CASE_TYPES),
|
||||
"structures": list(STRUCTURES),
|
||||
"builtYears": built_years(today),
|
||||
"totalFloors": list(TOTAL_FLOORS),
|
||||
"floorNos": list(FLOOR_NOS),
|
||||
"layoutStructures": list(OFFICE_LAYOUT_STRUCTURES),
|
||||
"decorations": list(DECORATIONS),
|
||||
"valueIncludes": list(VALUE_INCLUDES),
|
||||
"orientations": list(ORIENTATIONS),
|
||||
}
|
||||
|
||||
|
||||
def residential_options(today: date | None = None) -> dict:
|
||||
return {
|
||||
"caseTypes": list(CASE_TYPES),
|
||||
"structures": list(STRUCTURES),
|
||||
"builtYears": built_years(today),
|
||||
"totalFloors": list(TOTAL_FLOORS),
|
||||
"floorNos": list(FLOOR_NOS),
|
||||
"purposes": list(PURPOSES),
|
||||
"layoutStructures": list(LAYOUT_STRUCTURES),
|
||||
"decorations": list(DECORATIONS),
|
||||
"valueIncludes": list(VALUE_INCLUDES),
|
||||
"layouts": list(LAYOUTS),
|
||||
"orientations": list(ORIENTATIONS),
|
||||
}
|
||||
|
||||
|
||||
def industrial_options(today: date | None = None) -> dict:
|
||||
return {
|
||||
"caseTypes": list(CASE_TYPES),
|
||||
"structures": list(STRUCTURES),
|
||||
"builtYears": built_years(today),
|
||||
"totalFloors": list(INDUSTRIAL_FLOORS),
|
||||
"layouts": list(INDUSTRIAL_LAYOUTS),
|
||||
"headings": list(INDUSTRIAL_DIRECTIONS),
|
||||
"decorations": list(DECORATIONS),
|
||||
"roadFrontages": list(ROAD_FRONTAGES),
|
||||
"orientations": list(INDUSTRIAL_DIRECTIONS),
|
||||
"industryTypes": list(INDUSTRY_TYPES),
|
||||
"valueIncludes": list(INDUSTRIAL_VALUE_INCLUDES),
|
||||
}
|
||||
|
||||
|
||||
def _choice(value, options: tuple[str, ...] | list, label: str) -> str:
|
||||
text = str(value or "").strip()
|
||||
if text not in options:
|
||||
raise ValueError(f"{label}不正确")
|
||||
return text
|
||||
|
||||
|
||||
def _text(value, label: str, limit: int) -> str:
|
||||
text = str(value or "").strip()
|
||||
if not text:
|
||||
raise ValueError(f"请填写{label}")
|
||||
if len(text) > limit:
|
||||
raise ValueError(f"{label}过长")
|
||||
return text
|
||||
|
||||
|
||||
def _number(value, label: str) -> str:
|
||||
raw = str(value if value is not None else "").strip()
|
||||
if not raw:
|
||||
raise ValueError(f"请填写{label}")
|
||||
try:
|
||||
number = Decimal(raw)
|
||||
except InvalidOperation as exc:
|
||||
raise ValueError(f"{label}须为数字") from exc
|
||||
if not number.is_finite():
|
||||
raise ValueError(f"{label}须为数字")
|
||||
return format(number, "f")
|
||||
|
||||
|
||||
def _region(province: str, city: str, district: str) -> tuple[str, str, str]:
|
||||
province = str(province or "").strip()
|
||||
city = str(city or "").strip()
|
||||
district = str(district or "").strip()
|
||||
for item in regions():
|
||||
if item.get("name") != province:
|
||||
continue
|
||||
for child in item.get("sub") or []:
|
||||
if child.get("name") != city:
|
||||
continue
|
||||
names = [row.get("name") for row in child.get("sub") or []]
|
||||
if district not in names:
|
||||
raise ValueError("区县不正确")
|
||||
return province, city, district
|
||||
raise ValueError("城市不正确")
|
||||
raise ValueError("省份不正确")
|
||||
|
||||
|
||||
def _includes(value, options: tuple[str, ...] = VALUE_INCLUDES) -> list[str]:
|
||||
if value is None or value == "" or value == []:
|
||||
return []
|
||||
if not isinstance(value, list):
|
||||
raise ValueError("价值包含不正确")
|
||||
chosen = []
|
||||
for item in value:
|
||||
text = str(item or "").strip()
|
||||
if text not in options or text in chosen:
|
||||
raise ValueError("价值包含不正确")
|
||||
chosen.append(text)
|
||||
if len(chosen) > 3:
|
||||
raise ValueError("价值包含最多 3 项")
|
||||
return chosen
|
||||
|
||||
|
||||
def _formats(value) -> list[str]:
|
||||
if value is None or value == "" or value == []:
|
||||
raise ValueError("请选择经营业态")
|
||||
if not isinstance(value, list):
|
||||
raise ValueError("经营业态不正确")
|
||||
chosen = []
|
||||
for item in value:
|
||||
text = str(item or "").strip()
|
||||
if text not in BUSINESS_FORMATS or text in chosen:
|
||||
raise ValueError("经营业态不正确")
|
||||
chosen.append(text)
|
||||
if not chosen:
|
||||
raise ValueError("请选择经营业态")
|
||||
if len(chosen) > 3:
|
||||
raise ValueError("经营业态最多 3 项")
|
||||
return chosen
|
||||
|
||||
|
||||
def _photos(db, member_id: int, file_ids) -> list[int]:
|
||||
from app.models.content import AdminFile
|
||||
|
||||
if not isinstance(file_ids, list) or not file_ids:
|
||||
raise ValueError("请上传位置图及案例照片")
|
||||
ids: list[int] = []
|
||||
for raw in file_ids:
|
||||
try:
|
||||
file_id = int(raw)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValueError("位置图及案例照片不正确") from exc
|
||||
row = db.get(AdminFile, file_id)
|
||||
if row is None or row.bucket != "private" or row.created_by != member_id:
|
||||
raise ValueError("位置图及案例照片不正确")
|
||||
if row.size > PHOTO_MAX_BYTES:
|
||||
raise ValueError("位置图及案例照片须小于 5MB")
|
||||
if file_id not in ids:
|
||||
ids.append(file_id)
|
||||
return ids
|
||||
|
||||
|
||||
def _residential(db, member_id: int, payload: dict, today: date | None = None) -> dict:
|
||||
extra = set(payload) - {
|
||||
"kind",
|
||||
"caseType",
|
||||
"province",
|
||||
"city",
|
||||
"district",
|
||||
"estateName",
|
||||
"structure",
|
||||
"caseDate",
|
||||
"location",
|
||||
"builtYear",
|
||||
"totalFloors",
|
||||
"floorNo",
|
||||
"purpose",
|
||||
"layoutStructure",
|
||||
"decoration",
|
||||
"valueIncludes",
|
||||
"area",
|
||||
"layout",
|
||||
"orientation",
|
||||
"unitPrice",
|
||||
"remark",
|
||||
"institutionName",
|
||||
"photoFileIds",
|
||||
}
|
||||
if extra:
|
||||
raise ValueError("包含住宅没有的字段")
|
||||
province, city, district = _region(payload.get("province"), payload.get("city"), payload.get("district"))
|
||||
raw_date = str(payload.get("caseDate") or "").strip()
|
||||
try:
|
||||
case_date = datetime.strptime(raw_date, "%Y-%m-%d").date()
|
||||
except ValueError as exc:
|
||||
raise ValueError("案例时间不正确") from exc
|
||||
year = _choice(str(payload.get("builtYear") or "").strip(), [str(item) for item in built_years(today)], "建筑年代")
|
||||
remark = str(payload.get("remark") or "").strip()
|
||||
if remark and not 1 <= len(remark) <= 1000:
|
||||
raise ValueError("备注长度须在 1 到 1000")
|
||||
return {
|
||||
"case_type": _choice(payload.get("caseType"), CASE_TYPES, "案例类型"),
|
||||
"province": province,
|
||||
"city": city,
|
||||
"district": district,
|
||||
"estate_name": _text(payload.get("estateName"), "楼盘名称", 200),
|
||||
"structure": _choice(payload.get("structure"), STRUCTURES, "建筑结构"),
|
||||
"case_date": case_date,
|
||||
"location": _text(payload.get("location"), "坐落", 500),
|
||||
"built_year": int(year),
|
||||
"total_floors": int(_choice(str(payload.get("totalFloors") or "").strip(), TOTAL_FLOORS, "总层数")),
|
||||
"floor_no": _choice(str(payload.get("floorNo") or "").strip(), FLOOR_NOS, "所在层数"),
|
||||
"purpose": _choice(payload.get("purpose"), PURPOSES, "用途"),
|
||||
"layout_structure": _choice(payload.get("layoutStructure"), LAYOUT_STRUCTURES, "户型结构"),
|
||||
"decoration": _choice(payload.get("decoration"), DECORATIONS, "装修档次"),
|
||||
"value_includes": _includes(payload.get("valueIncludes")),
|
||||
"area": _number(payload.get("area"), "建筑面积"),
|
||||
"layout": _choice(payload.get("layout"), LAYOUTS, "户型"),
|
||||
"orientation": _choice(payload.get("orientation"), ORIENTATIONS, "朝向"),
|
||||
"unit_price": _number(payload.get("unitPrice"), "单价"),
|
||||
"remark": remark,
|
||||
"institution_name": _text(payload.get("institutionName"), "提交机构名称", 200),
|
||||
"photo_ids": _photos(db, member_id, payload.get("photoFileIds")),
|
||||
}
|
||||
|
||||
|
||||
def _commercial(db, member_id: int, payload: dict, today: date | None = None) -> dict:
|
||||
extra = set(payload) - {
|
||||
"kind",
|
||||
"caseType",
|
||||
"province",
|
||||
"city",
|
||||
"district",
|
||||
"estateName",
|
||||
"structure",
|
||||
"caseDate",
|
||||
"location",
|
||||
"builtYear",
|
||||
"totalFloors",
|
||||
"floorNo",
|
||||
"layout",
|
||||
"decoration",
|
||||
"streetFrontage",
|
||||
"area",
|
||||
"orientation",
|
||||
"footTraffic",
|
||||
"shopType",
|
||||
"businessFormats",
|
||||
"unitPrice",
|
||||
"valueIncludes",
|
||||
"remark",
|
||||
"institutionName",
|
||||
"photoFileIds",
|
||||
}
|
||||
if extra:
|
||||
raise ValueError("包含商业没有的字段")
|
||||
province, city, district = _region(payload.get("province"), payload.get("city"), payload.get("district"))
|
||||
raw_date = str(payload.get("caseDate") or "").strip()
|
||||
try:
|
||||
case_date = datetime.strptime(raw_date, "%Y-%m-%d").date()
|
||||
except ValueError as exc:
|
||||
raise ValueError("案例时间不正确") from exc
|
||||
year = _choice(str(payload.get("builtYear") or "").strip(), [str(item) for item in built_years(today)], "建筑年代")
|
||||
remark = str(payload.get("remark") or "").strip()
|
||||
if remark and not 1 <= len(remark) <= 1000:
|
||||
raise ValueError("备注长度须在 1 到 1000")
|
||||
return {
|
||||
"case_type": _choice(payload.get("caseType"), CASE_TYPES, "案例类型"),
|
||||
"province": province,
|
||||
"city": city,
|
||||
"district": district,
|
||||
"estate_name": _text(payload.get("estateName"), "楼盘名称", 200),
|
||||
"structure": _choice(payload.get("structure"), STRUCTURES, "建筑结构"),
|
||||
"case_date": case_date,
|
||||
"location": _text(payload.get("location"), "坐落", 500),
|
||||
"built_year": int(year),
|
||||
"total_floors": int(_choice(str(payload.get("totalFloors") or "").strip(), TOTAL_FLOORS, "总层数")),
|
||||
"floor_no": _choice(str(payload.get("floorNo") or "").strip(), FLOOR_NOS, "所在层数"),
|
||||
"purpose": "",
|
||||
"layout_structure": "",
|
||||
"decoration": _choice(payload.get("decoration"), DECORATIONS, "装修档次"),
|
||||
"value_includes": _includes(payload.get("valueIncludes")),
|
||||
"area": _number(payload.get("area"), "建筑面积"),
|
||||
"layout": _choice(payload.get("layout"), COMMERCIAL_LAYOUTS, "户型"),
|
||||
"orientation": _choice(payload.get("orientation"), ORIENTATIONS, "朝向"),
|
||||
"street_frontage": _choice(payload.get("streetFrontage"), STREET_FRONTAGES, "临街状况"),
|
||||
"foot_traffic": _choice(payload.get("footTraffic"), FOOT_TRAFFICS, "人流量"),
|
||||
"shop_type": _choice(payload.get("shopType"), SHOP_TYPES, "商铺类型"),
|
||||
"business_formats": _formats(payload.get("businessFormats")),
|
||||
"unit_price": _number(payload.get("unitPrice"), "单价"),
|
||||
"remark": remark,
|
||||
"institution_name": _text(payload.get("institutionName"), "提交机构名称", 200),
|
||||
"photo_ids": _photos(db, member_id, payload.get("photoFileIds")),
|
||||
}
|
||||
|
||||
|
||||
def _office(db, member_id: int, payload: dict, today: date | None = None) -> dict:
|
||||
extra = set(payload) - {
|
||||
"kind",
|
||||
"caseType",
|
||||
"province",
|
||||
"city",
|
||||
"district",
|
||||
"estateName",
|
||||
"structure",
|
||||
"caseDate",
|
||||
"location",
|
||||
"builtYear",
|
||||
"totalFloors",
|
||||
"floorNo",
|
||||
"layoutStructure",
|
||||
"decoration",
|
||||
"valueIncludes",
|
||||
"area",
|
||||
"orientation",
|
||||
"unitPrice",
|
||||
"remark",
|
||||
"institutionName",
|
||||
"photoFileIds",
|
||||
}
|
||||
if extra:
|
||||
raise ValueError("包含办公没有的字段")
|
||||
province, city, district = _region(payload.get("province"), payload.get("city"), payload.get("district"))
|
||||
raw_date = str(payload.get("caseDate") or "").strip()
|
||||
try:
|
||||
case_date = datetime.strptime(raw_date, "%Y-%m-%d").date()
|
||||
except ValueError as exc:
|
||||
raise ValueError("案例时间不正确") from exc
|
||||
year = _choice(str(payload.get("builtYear") or "").strip(), [str(item) for item in built_years(today)], "建筑年代")
|
||||
remark = str(payload.get("remark") or "").strip()
|
||||
if remark and not 1 <= len(remark) <= 1000:
|
||||
raise ValueError("备注长度须在 1 到 1000")
|
||||
return {
|
||||
"case_type": _choice(payload.get("caseType"), CASE_TYPES, "案例类型"),
|
||||
"province": province,
|
||||
"city": city,
|
||||
"district": district,
|
||||
"estate_name": _text(payload.get("estateName"), "楼盘名称", 200),
|
||||
"structure": _choice(payload.get("structure"), STRUCTURES, "建筑结构"),
|
||||
"case_date": case_date,
|
||||
"location": _text(payload.get("location"), "坐落", 500),
|
||||
"built_year": int(year),
|
||||
"total_floors": int(_choice(str(payload.get("totalFloors") or "").strip(), TOTAL_FLOORS, "总层数")),
|
||||
"floor_no": _choice(str(payload.get("floorNo") or "").strip(), FLOOR_NOS, "所在层数"),
|
||||
"purpose": "",
|
||||
"layout_structure": _choice(payload.get("layoutStructure"), OFFICE_LAYOUT_STRUCTURES, "户型结构"),
|
||||
"decoration": _choice(payload.get("decoration"), DECORATIONS, "装修档次"),
|
||||
"value_includes": _includes(payload.get("valueIncludes")),
|
||||
"area": _number(payload.get("area"), "建筑面积"),
|
||||
"layout": "",
|
||||
"orientation": _choice(payload.get("orientation"), ORIENTATIONS, "朝向"),
|
||||
"unit_price": _number(payload.get("unitPrice"), "单价"),
|
||||
"remark": remark,
|
||||
"institution_name": _text(payload.get("institutionName"), "提交机构名称", 200),
|
||||
"photo_ids": _photos(db, member_id, payload.get("photoFileIds")),
|
||||
}
|
||||
|
||||
|
||||
def _industrial(db, member_id: int, payload: dict, today: date | None = None) -> dict:
|
||||
extra = set(payload) - {
|
||||
"kind",
|
||||
"caseType",
|
||||
"province",
|
||||
"city",
|
||||
"district",
|
||||
"estateName",
|
||||
"structure",
|
||||
"caseDate",
|
||||
"location",
|
||||
"builtYear",
|
||||
"totalFloors",
|
||||
"layout",
|
||||
"heading",
|
||||
"decoration",
|
||||
"roadFrontage",
|
||||
"area",
|
||||
"orientation",
|
||||
"industryType",
|
||||
"unitPrice",
|
||||
"valueIncludes",
|
||||
"remark",
|
||||
"institutionName",
|
||||
"photoFileIds",
|
||||
}
|
||||
if extra:
|
||||
raise ValueError("包含工业没有的字段")
|
||||
province, city, district = _region(payload.get("province"), payload.get("city"), payload.get("district"))
|
||||
raw_date = str(payload.get("caseDate") or "").strip()
|
||||
try:
|
||||
case_date = datetime.strptime(raw_date, "%Y-%m-%d").date()
|
||||
except ValueError as exc:
|
||||
raise ValueError("案例时间不正确") from exc
|
||||
year = _choice(str(payload.get("builtYear") or "").strip(), [str(item) for item in built_years(today)], "建筑年代")
|
||||
remark = str(payload.get("remark") or "").strip()
|
||||
if remark and not 1 <= len(remark) <= 1000:
|
||||
raise ValueError("备注长度须在 1 到 1000")
|
||||
return {
|
||||
"case_type": _choice(payload.get("caseType"), CASE_TYPES, "案例类型"),
|
||||
"province": province,
|
||||
"city": city,
|
||||
"district": district,
|
||||
"estate_name": _text(payload.get("estateName"), "楼盘名称", 200),
|
||||
"structure": _choice(payload.get("structure"), STRUCTURES, "建筑结构"),
|
||||
"case_date": case_date,
|
||||
"location": _text(payload.get("location"), "坐落", 500),
|
||||
"built_year": int(year),
|
||||
"total_floors": int(_choice(str(payload.get("totalFloors") or "").strip(), INDUSTRIAL_FLOORS, "总层数")),
|
||||
"floor_no": "",
|
||||
"purpose": "",
|
||||
"layout_structure": "",
|
||||
"decoration": _choice(payload.get("decoration"), DECORATIONS, "装修档次"),
|
||||
"value_includes": _includes(payload.get("valueIncludes"), INDUSTRIAL_VALUE_INCLUDES),
|
||||
"area": _number(payload.get("area"), "建筑面积"),
|
||||
"layout": _choice(payload.get("layout"), INDUSTRIAL_LAYOUTS, "户型"),
|
||||
"heading": _choice(payload.get("heading"), INDUSTRIAL_DIRECTIONS, "走向"),
|
||||
"road_frontage": _choice(payload.get("roadFrontage"), ROAD_FRONTAGES, "临路状况"),
|
||||
"orientation": _choice(payload.get("orientation"), INDUSTRIAL_DIRECTIONS, "朝向"),
|
||||
"industry_type": _choice(payload.get("industryType"), INDUSTRY_TYPES, "工业类型"),
|
||||
"unit_price": _number(payload.get("unitPrice"), "单价"),
|
||||
"remark": remark,
|
||||
"institution_name": _text(payload.get("institutionName"), "提交机构名称", 200),
|
||||
"photo_ids": _photos(db, member_id, payload.get("photoFileIds")),
|
||||
}
|
||||
|
||||
|
||||
def create_uploaded_case(db, member, payload: dict, today: date | None = None) -> UploadedCase:
|
||||
if not isinstance(payload, dict):
|
||||
raise ValueError("提交内容不正确")
|
||||
kind = str(payload.get("kind") or "").strip()
|
||||
if kind not in KIND_LABELS:
|
||||
raise ValueError("案例种类不正确")
|
||||
if kind not in OPEN_KINDS:
|
||||
raise ValueError("该类型尚未开放")
|
||||
parsers = {
|
||||
"residential": _residential,
|
||||
"commercial": _commercial,
|
||||
"office": _office,
|
||||
"industrial": _industrial,
|
||||
}
|
||||
fields = parsers[kind](db, member.id, payload, today)
|
||||
row = UploadedCase(
|
||||
kind=kind,
|
||||
member_id=member.id,
|
||||
member_email=member.email,
|
||||
case_type=fields["case_type"],
|
||||
province=fields["province"],
|
||||
city=fields["city"],
|
||||
district=fields["district"],
|
||||
estate_name=fields["estate_name"],
|
||||
structure=fields["structure"],
|
||||
case_date=fields["case_date"],
|
||||
location=fields["location"],
|
||||
built_year=fields["built_year"],
|
||||
total_floors=fields["total_floors"],
|
||||
floor_no=fields["floor_no"],
|
||||
purpose=fields["purpose"],
|
||||
layout_structure=fields["layout_structure"],
|
||||
decoration=fields["decoration"],
|
||||
value_includes=json.dumps(fields["value_includes"], ensure_ascii=False),
|
||||
area=fields["area"],
|
||||
layout=fields["layout"],
|
||||
orientation=fields["orientation"],
|
||||
unit_price=fields["unit_price"],
|
||||
remark=fields["remark"],
|
||||
institution_name=fields["institution_name"],
|
||||
street_frontage=fields.get("street_frontage", ""),
|
||||
foot_traffic=fields.get("foot_traffic", ""),
|
||||
shop_type=fields.get("shop_type", ""),
|
||||
business_formats=json.dumps(fields.get("business_formats", []), ensure_ascii=False),
|
||||
heading=fields.get("heading", ""),
|
||||
road_frontage=fields.get("road_frontage", ""),
|
||||
industry_type=fields.get("industry_type", ""),
|
||||
created_at=_now(),
|
||||
)
|
||||
db.add(row)
|
||||
db.flush()
|
||||
for index, file_id in enumerate(fields["photo_ids"]):
|
||||
db.add(UploadedCasePhoto(case_id=row.id, file_id=file_id, position=index))
|
||||
db.commit()
|
||||
db.refresh(row)
|
||||
return row
|
||||
|
||||
|
||||
def _address(row: UploadedCase) -> str:
|
||||
return f"{row.province} {row.city} {row.district}"
|
||||
|
||||
|
||||
def _list_item(row: UploadedCase) -> dict:
|
||||
return {
|
||||
"id": row.id,
|
||||
"kind": row.kind,
|
||||
"kindLabel": KIND_LABELS.get(row.kind, row.kind),
|
||||
"estateName": row.estate_name,
|
||||
"address": _address(row),
|
||||
"caseDate": row.case_date.isoformat() if row.case_date else "",
|
||||
"institutionName": row.institution_name,
|
||||
"memberEmail": row.member_email,
|
||||
"createdAt": row.created_at.isoformat(timespec="seconds") if row.created_at else "",
|
||||
}
|
||||
|
||||
|
||||
def _photos_payload(db, case_id: int) -> list[dict]:
|
||||
from app.models.content import AdminFile
|
||||
from app.services.storage import private_object_url
|
||||
|
||||
links = db.scalars(
|
||||
select(UploadedCasePhoto)
|
||||
.where(UploadedCasePhoto.case_id == case_id)
|
||||
.order_by(UploadedCasePhoto.position.asc(), UploadedCasePhoto.id.asc())
|
||||
).all()
|
||||
items = []
|
||||
for link in links:
|
||||
file_row = db.get(AdminFile, link.file_id)
|
||||
if file_row is None or file_row.bucket != "private":
|
||||
continue
|
||||
url, expires_at = private_object_url(file_row.object_key)
|
||||
items.append(
|
||||
{
|
||||
"id": file_row.id,
|
||||
"filename": file_row.filename,
|
||||
"contentType": file_row.content_type or "",
|
||||
"url": url,
|
||||
"expiresAt": expires_at.isoformat(),
|
||||
}
|
||||
)
|
||||
return items
|
||||
|
||||
|
||||
def _like_contains(value: str) -> str:
|
||||
escaped = value.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
|
||||
return f"%{escaped}%"
|
||||
|
||||
|
||||
def list_uploaded_cases(db, *, kind: str, current: int, size: int, q: str | None = None) -> dict | None:
|
||||
if kind not in KIND_LABELS:
|
||||
return None
|
||||
page_size = size if size in PAGE_SIZES else 10
|
||||
page = current if current >= 1 else 1
|
||||
filters = [UploadedCase.kind == kind]
|
||||
keyword = (q or "").strip()[:100]
|
||||
if keyword:
|
||||
needle = _like_contains(keyword)
|
||||
filters.append(
|
||||
or_(
|
||||
UploadedCase.estate_name.like(needle, escape="\\"),
|
||||
UploadedCase.province.like(needle, escape="\\"),
|
||||
UploadedCase.city.like(needle, escape="\\"),
|
||||
UploadedCase.district.like(needle, escape="\\"),
|
||||
UploadedCase.institution_name.like(needle, escape="\\"),
|
||||
UploadedCase.member_email.like(needle, escape="\\"),
|
||||
)
|
||||
)
|
||||
total = len(db.scalars(select(UploadedCase.id).where(*filters)).all())
|
||||
rows = db.scalars(
|
||||
select(UploadedCase)
|
||||
.where(*filters)
|
||||
.order_by(UploadedCase.created_at.desc(), UploadedCase.id.desc())
|
||||
.offset((page - 1) * page_size)
|
||||
.limit(page_size)
|
||||
).all()
|
||||
return {
|
||||
"kind": kind,
|
||||
"kindLabel": KIND_LABELS[kind],
|
||||
"items": [_list_item(row) for row in rows],
|
||||
"total": total,
|
||||
"current": page,
|
||||
"size": page_size,
|
||||
}
|
||||
|
||||
|
||||
def uploaded_case_detail(db, case_id: int) -> dict | None:
|
||||
row = db.get(UploadedCase, case_id)
|
||||
if row is None:
|
||||
return None
|
||||
body = _list_item(row)
|
||||
body.update(
|
||||
{
|
||||
"caseType": row.case_type,
|
||||
"province": row.province,
|
||||
"city": row.city,
|
||||
"district": row.district,
|
||||
"structure": row.structure,
|
||||
"location": row.location,
|
||||
"builtYear": row.built_year,
|
||||
"totalFloors": row.total_floors,
|
||||
"decoration": row.decoration,
|
||||
"valueIncludes": json.loads(row.value_includes or "[]"),
|
||||
"area": row.area,
|
||||
"orientation": row.orientation,
|
||||
"unitPrice": row.unit_price,
|
||||
"remark": row.remark,
|
||||
"photos": _photos_payload(db, row.id),
|
||||
}
|
||||
)
|
||||
if row.kind != "industrial":
|
||||
body["floorNo"] = row.floor_no
|
||||
if row.kind in ("residential", "commercial", "industrial"):
|
||||
body["layout"] = row.layout
|
||||
if row.kind == "residential":
|
||||
body["purpose"] = row.purpose
|
||||
body["layoutStructure"] = row.layout_structure
|
||||
if row.kind == "office":
|
||||
body["layoutStructure"] = row.layout_structure
|
||||
if row.kind == "commercial":
|
||||
body["streetFrontage"] = row.street_frontage
|
||||
body["footTraffic"] = row.foot_traffic
|
||||
body["shopType"] = row.shop_type
|
||||
body["businessFormats"] = json.loads(row.business_formats or "[]")
|
||||
if row.kind == "industrial":
|
||||
body["heading"] = row.heading
|
||||
body["roadFrontage"] = row.road_frontage
|
||||
body["industryType"] = row.industry_type
|
||||
return body
|
||||
Reference in new issue
Block a user