unis-oa/backend/app/seed.py

1145 lines
57 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

"""Bootstrap data: organization, an admin account and two demo processes.
Idempotent: it only inserts what is missing, so it is safe on every boot.
"""
from __future__ import annotations
import logging
import random
import shutil
import uuid
from datetime import datetime, timedelta
from pathlib import Path
from sqlalchemy import func, or_, select, text
from sqlalchemy.orm import Session
from . import models, permissions
from .config import DEFAULT_ADMIN_ACCOUNT, settings
from .security import hash_password
from .service import org
logger = logging.getLogger("unisoa.seed")
FORM_LEAVE = {
"fields": [
{"key": "reason", "label": "请假事由", "type": "textarea", "required": True, "span": 24},
{
"key": "leave_type", "label": "请假类型", "type": "select", "required": True, "span": 12,
"options": [
{"value": "annual", "label": "年假"},
{"value": "sick", "label": "病假"},
{"value": "personal", "label": "事假"},
{"value": "marriage", "label": "婚假"},
],
},
{"key": "days", "label": "请假天数", "type": "number", "required": True, "span": 12, "min": 0.5, "step": 0.5},
{"key": "start_date", "label": "开始日期", "type": "date", "required": True, "span": 12},
{"key": "end_date", "label": "结束日期", "type": "date", "required": True, "span": 12},
{"key": "handover", "label": "工作交接人", "type": "text", "required": False, "span": 12},
{"key": "attachments", "label": "附件", "type": "attachment", "required": False, "span": 24},
],
"layout": {"columns": 2, "label_width": 110},
}
FORM_EXPENSE = {
"fields": [
{"key": "title", "label": "报销事项", "type": "text", "required": True, "span": 24},
{"key": "amount", "label": "报销金额(元)", "type": "number", "required": True, "span": 12, "min": 0, "precision": 2},
{"key": "expense_type", "label": "费用类型", "type": "select", "required": True, "span": 12,
"options": [
{"value": "travel", "label": "差旅费"},
{"value": "office", "label": "办公用品"},
{"value": "entertain", "label": "业务招待"},
{"value": "other", "label": "其他"},
]},
{"key": "invoice_count", "label": "发票张数", "type": "number", "required": False, "span": 12, "min": 0},
{"key": "remark", "label": "备注说明", "type": "textarea", "required": False, "span": 24},
{"key": "attachments", "label": "票据附件", "type": "attachment", "required": False, "span": 24},
],
"layout": {"columns": 2, "label_width": 110},
}
#: Marker so the one-off clock repair never runs twice.
_CLOCK_MARKER = "system.timestamp_clock"
#: 内置超管当前用的是哪个登录账号。改名迁移靠它对账,见 ``_align_admin_account``。
_ADMIN_ACCOUNT_MARKER = "system.admin_account"
def run(db: Session) -> None:
# JSON 容器列要先洗:后面每一步都要用 ORM 读这些表,脏值会让查询当场抛错
_repair_json_list_columns(db)
_repair_utc_timestamps(db)
# 先对齐内置超管的登录账号,再让「应急账号」名单跟着它走
previous_admin, admin_account = _align_admin_account(db)
_align_hub_local_accounts(db, previous=previous_admin, admin_account=admin_account)
persons = int(db.execute(select(func.count(models.User.id))).scalar() or 0)
if persons == 0:
_seed_organization(db)
if int(db.execute(select(func.count(models.Category.id))).scalar() or 0) == 0:
_seed_categories(db)
# The session disables autoflush, so earlier rows must be flushed before the
# process seed looks categories/roles up by name.
db.flush()
if int(db.execute(select(func.count(models.Process.id))).scalar() or 0) == 0:
_seed_processes(db)
_seed_dicts(db)
_backfill_process_categories(db)
_backfill_default_forms(db)
_repair_dangling_unit_links(db)
if settings.seed_demo:
_ensure_reporting_lines(db)
# 首页演示内容(信息资讯、会议、日程、网盘示例文件)会真的往 MinIO 落盘,
# 共享存储不通时一次启动能磨上好几分钟,所以吃 OA_SEED_DEMO=false 这个开关跳过。
if settings.seed_demo:
_seed_portal(db)
_seed_auth_roles(db)
_reset_legacy_approval_config(db)
db.commit()
#: 早期版本出厂就把「发起人不重复审批 + 审批人去重」一起打开。前者会让发起当场
#: 吞掉「填写申请」这一环:发起人手上没有待办,退回来也没有落点。默认值已经改回
#: 关,这里把还是老配方、且没人动过的演示流程一并纠正。
LEGACY_DEMO_ALIASES = ("leave", "expense")
LEGACY_APPROVAL_CONFIG = {"skipStarter": True, "dedup": "all"}
def _reset_legacy_approval_config(db: Session) -> None:
rows = db.execute(
select(models.Process).where(models.Process.alias.in_(LEGACY_DEMO_ALIASES))
).scalars().all()
for row in rows:
if dict(row.approval_config or {}) != LEGACY_APPROVAL_CONFIG:
continue
row.approval_config = dict(DEFAULT_APPROVAL_CONFIG)
logger.warning(
"历史数据修复:演示流程「%s」的审批规则还是旧出厂配方(发起人不重复审批),"
"已改回默认关闭,否则「填写申请」环节会被自动通过",
row.name,
)
#: 这几列是 JSON 数组,但早期版本的默认值写成了空对象 ``{}``,存量行读出来会让
#: ORM 直接抛错(点开任一已办详情都是 500)。列名写死,不做通配扫描。
JSON_LIST_COLUMNS: tuple[tuple[str, str], ...] = (
("oa_task_completed", "attachments"),
("oa_work_comment", "attachments"),
)
def _repair_json_list_columns(db: Session) -> None:
"""把 JSON 数组列里的对象洗成数组:空对象 -> ``[]``,单个对象 -> ``[obj]``。
走裸 SQL:这几行恰恰是 ORM 读不动的行,用 ORM 反倒在原地炸。判定用 MySQL 的
``JSON_TYPE``;每张表套一个 SAVEPOINT,某张表结构不对就只回滚那一条语句,
既不挡启动也不牵连同一趟种子里的其它改动。
"""
for table, column in JSON_LIST_COLUMNS:
where = f"WHERE JSON_TYPE(`{column}`) <> 'ARRAY'"
try:
with db.begin_nested():
stale = int(db.execute(text(f"SELECT COUNT(*) FROM `{table}` {where}")).scalar() or 0)
if not stale:
continue
db.execute(
text(
f"UPDATE `{table}` SET `{column}` = "
f"CASE WHEN JSON_LENGTH(`{column}`) = 0 THEN JSON_ARRAY() "
f"ELSE JSON_ARRAY(`{column}`) END {where}"
)
)
logger.warning(
"历史数据修复:%s.%s 有 %d 行 JSON 不是数组,已就地改成数组", table, column, stale
)
except Exception as exc: # noqa: BLE001 - 修不动也不能挡启动
logger.warning("历史数据修复跳过 %s.%s:%s", table, column, exc)
def _repair_utc_timestamps(db: Session) -> None:
"""Shift legacy UTC ``create_time`` / ``update_time`` values onto local time.
``TimestampMixin`` used to default to UTC while the engine wrote naive local
datetimes, so audit columns displayed 8 hours early. Runs at most once: the
marker is written whether or not a shift was needed.
"""
from datetime import timedelta
if db.get(models.SystemSetting, _CLOCK_MARKER) is not None:
return
offset = int((datetime.now() - datetime.utcnow()).total_seconds())
columns = [
(table, column)
for table in models.Base.metadata.tables.values()
for column in ("create_time", "update_time")
if column in table.c
]
if not columns:
return
probe_table = columns[0][0]
latest = db.execute(select(func.max(probe_table.c.create_time))).scalar()
if latest is not None and (datetime.now() - latest) > timedelta(hours=1):
for table, column in columns:
# Table/column names come from SQLAlchemy metadata, never from input.
db.execute(
text(f"UPDATE `{table.name}` SET `{column}` = TIMESTAMPADD(SECOND, :offset, `{column}`)"),
{"offset": offset},
)
logger.info("shifted legacy UTC timestamps by %s seconds", offset)
db.add(
models.SystemSetting(
key=_CLOCK_MARKER,
value={"shift_seconds": offset, "note": "audit columns normalised to local time"},
description="时间基准修复标记",
)
)
db.flush()
def _record_admin_account(db: Session, marker: models.SystemSetting | None, value: dict) -> None:
"""记下"内置超管现在用哪个登录账号"。标记已存在就改值,别再按同一个主键插一遍。"""
if marker is None:
db.add(
models.SystemSetting(
key=_ADMIN_ACCOUNT_MARKER,
value=value,
description="内置超管当前使用的登录账号(改 [seed] admin_account 时按它对齐)",
)
)
else:
marker.value = value
db.flush()
def _align_admin_account(db: Session) -> None:
"""对齐内置超管的登录账号,需要改名时把身份与审批引用一起搬走。
本地管理员账号**住在数据库里**(``system.admin_account`` 这一行就是它的户口),
配置文件不用写 ``[seed] admin_account``:配置文件与环境变量里点名了一个名字,
才当作"要把内置超管改成这个名"来处理;没点名就以库里记着的那个为准。
内置超管是**按账号名**认的(``org.system_account_names()`` 取的就是这一项):账号名
跟配置对不上,它既会从"应急通道"名单里掉出去(``[hub] local_accounts`` 写的是新名字),
又会作为普通员工出现在组织架构树上。把内置账号让给统一身份(例如本地这个改名
``localadmin``,把 ``admin`` 腾给 Hub 同步进来的人)就是靠这一项配置完成的。
保守得很:只搬"上次记着的那个账号",目标名字被人占着、或者按老名字找不出唯一一行,
就只写日志不动数据;库里第一次对账时,只认那个还没被统一身份认领的默认名本地管理员。
返回 ``(改名前的账号, 现在生效的账号)``:改名没做成时两个是同一个名字,
调用方据此判断要不要跟着改「应急账号」名单。
"""
from .config import bootstrap_explicit, forget_admin_account_cache
# 配置文件/环境变量里点名要用的名字;没写就是空串,表示"这一项配置文件不管"
named = str(bootstrap_explicit("admin_account") or "").strip()
marker = db.get(models.SystemSetting, _ADMIN_ACCOUNT_MARKER)
current = str((marker.value or {}).get("account") or "").strip() if marker is not None else ""
if not current:
legacy = db.execute(
select(models.User).where(
models.User.account == DEFAULT_ADMIN_ACCOUNT,
models.User.role == models.ROLE_ADMIN,
models.User.source == models.AccountSource.LOCAL,
models.User.hub_user_id.is_(None),
)
).scalars().all()
if len(legacy) == 1:
current = DEFAULT_ADMIN_ACCOUNT
elif named:
current = named
else:
# 库里没户口、配置文件也不管:只能认那个"本地建的、还没被统一身份认领"的管理员
lone = db.execute(
select(models.User).where(
models.User.role == models.ROLE_ADMIN,
models.User.source == models.AccountSource.LOCAL,
models.User.hub_user_id.is_(None),
)
).scalars().all()
current = str(lone[0].account or "").strip() if len(lone) == 1 else DEFAULT_ADMIN_ACCOUNT
wanted = named or current
if not wanted:
return "", ""
if current == wanted:
_record_admin_account(db, marker, {"account": wanted})
return current, wanted
rows = db.execute(select(models.User).where(models.User.account == current)).scalars().all()
taken = db.execute(select(models.User.id).where(models.User.account == wanted)).scalar()
if taken is not None:
logger.warning("内置超管账号 %s -> %s 没改:%s 已被别的账号占用", current, wanted, wanted)
return current, current
if len(rows) != 1:
logger.warning("内置超管账号 %s -> %s 没改:按 %s 找到 %d 行,不能确定改哪一行",
current, wanted, current, len(rows))
return current, current
person = rows[0]
from .service import hub_refs
dn_map: dict[str, str] = {}
for identity in db.execute(
select(models.Identity).where(models.Identity.person_id == person.id)
).scalars().all():
old_dn = str(identity.distinguished_name or "")
parts = [part for part in old_dn.split("\\") if part]
# 内置账号的身份 DN 尾巴就是登录账号,换名要连着换,否则审批引用还指着老 DN
if not parts or parts[-1] != current:
continue
new_dn = "\\".join(parts[:-1] + [wanted])[:512]
identity.distinguished_name = new_dn
if old_dn != new_dn:
dn_map[old_dn] = new_dn
person.account = wanted
# 登录是按 账号 或 邮箱 找人的:邮箱还留着老账号名,等于给老账号名留了一条
# 走进内置超管的暗道(Hub 模式下问不到人时会回退本地口令),一起搬走。
if str(person.email or "") == current:
person.email = wanted
db.flush()
report = hub_refs.rewrite(db, hub_refs.build_maps(account_map={current: wanted}, dn_map=dn_map))
_record_admin_account(db, marker, {"account": wanted, "from": current, "references": report.rewritten})
forget_admin_account_cache()
logger.info(
"内置超管登录账号已按配置改名:%s -> %s(连带搬走 %d 处按账号/身份 DN 存的引用)",
current, wanted, report.rewritten,
)
return current, wanted
def _align_hub_local_accounts(db: Session, *, previous: str, admin_account: str) -> None:
"""让「应急账号」名单跟着内置超管的账号名走,并且真的落在库里。
这份名单(``config:hub.hub_local_accounts``)是"这些账号不去问统一身份、只用本地
口令登录"的应急通道,口径上以数据库为准。修之前的毛病是这一项从来没落过库:
出厂默认写死 ``admin``,于是内置超管按配置改名(典型场景:本地这个改成
``localadmin``,把 ``admin`` 腾给同步进来的人)之后,界面上那条名单还指着
``admin`` —— 而名单里的账号走本地口令,等于给那个统一身份账号留了一道本地口令的门。
内置超管本身永远走本地口令(见 ``hubconfig.local_only_accounts``),所以这道门不会因为
"名单里没有它"而关不上,缺的只是把名单写对。
做法保守:库里这一项还没存过 → 按现在生效的账号建一份;存过且里面还留着改名前
那个名字 → 只把那个名字换成新名字。别人自己往里加的应急账号一概不动。
"""
from . import dbconfig
admin_account = str(admin_account or "").strip().lower()
if not admin_account:
return
previous = str(previous or "").strip().lower()
row = dbconfig._row_for(db, "hub", create=False)
stored = dict((row.value or {}) if row is not None else {})
listed = dbconfig._clean_accounts(stored.get("hub_local_accounts", ""))
if "hub_local_accounts" not in stored:
# 内置超管还叫出厂那个名字时一行都不写:这一栏本来就该空着(内置超管走本地
# 口令由 hubconfig 保证,不靠这里),干净实例也不必凭空多出一行"界面上保存过
# 的配置"。只有名字被改过(把出厂名腾给统一身份同步进来的人)才需要落库。
if admin_account == DEFAULT_ADMIN_ACCOUNT.strip().lower():
return
value = admin_account
else:
names = [one for one in listed.split(",") if one]
if previous and previous != admin_account and previous in names:
names = [admin_account if one == previous else one for one in names]
elif admin_account in names:
return # 名单已经跟着现名字了,不插手
else:
return # 这份名单是人家自己配的,不替他改
value = dbconfig._clean_accounts(names)
if value == listed:
return
payload = dict(stored)
payload["hub_local_accounts"] = value
if row is None:
row = models.SystemSetting(key=f"{dbconfig.DB_KEY_PREFIX}hub", value=payload,
description=f"运行配置:{dbconfig.group_label('hub')}")
db.add(row)
else:
row.value = payload
db.flush()
# 另外的进程/本进程的读缓存都要跟上,否则界面上还看着老默认值
dbconfig.invalidate()
logger.info("应急账号名单已对齐内置超管:%s -> %s(%shub.hub_local_accounts)",
listed or "(空)", value or "(空)", dbconfig.DB_KEY_PREFIX)
def _backfill_process_categories(db: Session) -> None:
"""Attach demo processes to their category (older seeds left this empty)."""
wanted = {"请假申请": "人事管理", "费用报销": "财务管理"}
categories = {c.name: c for c in db.execute(select(models.Category)).scalars().all()}
for process in db.execute(select(models.Process)).scalars().all():
name = wanted.get(process.name)
if process.category or not name:
continue
category = categories.get(name)
if category is not None:
process.category = category.id
process.category_name = category.name
logger.info("seed completed")
def _backfill_default_forms(db: Session) -> None:
"""把「有自己表单却没绑默认表单」的老流程接上。
发起页与引擎都只认 ``latest_form``,早期流程是靠表单列表的第一条兜底渲染的,
不补这一步,这些流程发起时会看不见表单。
"""
owned: dict[str, list[models.FormElement]] = {}
for form in db.execute(
select(models.FormElement)
.where(models.FormElement.process != "")
.order_by(models.FormElement.order_number, models.FormElement.name)
).scalars().all():
owned.setdefault(form.process, []).append(form)
for process in db.execute(select(models.Process)).scalars().all():
if process.latest_form:
continue
candidates = owned.get(process.id) or []
if not candidates:
continue
process.latest_form = candidates[0].id
process.latest_form_name = candidates[0].name
def _seed_organization(db: Session) -> None:
company = models.Unit(name="优尼森科技", alias="UNIS", description="集团公司")
db.add(company)
db.flush()
company.path = "优尼森科技\\"
company.distinguished_name = "o=优尼森科技"
departments = ["综合管理部", "研发中心", "市场部", "财务部"]
units: dict[str, models.Unit] = {"优尼森科技": company}
for index, name in enumerate(departments):
unit = models.Unit(name=name, alias=name, parent_id=company.id, order_number=index)
db.add(unit)
db.flush()
unit.parent_name = company.name
unit.path = f"{company.path}{name}\\"
unit.distinguished_name = f"o={unit.path[:-1]}"
units[name] = unit
admin_account = settings.admin_account
roster = [
(admin_account, "系统管理员", "综合管理部", models.ROLE_ADMIN, admin_account, settings.admin_password),
("zhaoliu", "赵六", "综合管理部", models.ROLE_MEMBER, "zhaoliu@unissense.com", "123456"),
("zhangsan", "张三", "研发中心", models.ROLE_MEMBER, "zhangsan@unissense.com", "123456"),
("lisi", "李四", "研发中心", models.ROLE_MEMBER, "lisi@unissense.com", "123456"),
("wangwu", "王五", "市场部", models.ROLE_MEMBER, "wangwu@unissense.com", "123456"),
("sunqi", "孙七", "财务部", models.ROLE_MEMBER, "sunqi@unissense.com", "123456"),
("zhouba", "周八", "研发中心", models.ROLE_MEMBER, "zhouba@unissense.com", "123456"),
]
created: dict[str, models.User] = {}
for account, name, unit_name, role, email, password in roster:
unit = units[unit_name]
person = models.User(
account=account, display_name=name, password_hash=hash_password(password),
email=email, organization_id=unit.id, role=role,
status=models.UserStatus.ACTIVE,
)
db.add(person)
db.flush()
db.add(
models.Identity(
name=name, person_id=person.id, person_name=name,
unit_id=unit.id, unit_name=unit.name, unit_path=unit.path[:-1],
distinguished_name=org.dn_for(unit.path[:-1], name, account), is_default=True,
)
)
created[account] = person
manager_identity = _identity_dn(created["zhaoliu"])
finance_identity = _identity_dn(created["sunqi"])
dev_lead_identity = _identity_dn(created["lisi"])
db.add_all(
[
models.Role(name="部门负责人", description="各部门负责人", list_auth=[manager_identity, dev_lead_identity]),
models.Role(name="财务", description="财务人员", list_auth=[finance_identity]),
models.Role(name="总经理", description="公司总经理", list_auth=[_identity_dn(created[admin_account])]),
models.Group(
name="研发全员", description="研发中心成员",
list_identity=[_identity_dn(created[a]) for a in ("zhangsan", "lisi", "zhouba")],
),
]
)
#: 演示组织的汇报线:部门 -> 负责人账号,人员 -> 直属上级账号。
#: 只填当前为空的字段,真实客户的数据(含 Hub 同步来的组织)不会被覆盖。
DEMO_UNIT_MANAGERS = {
"优尼森科技": "admin",
"综合管理部": "zhaoliu",
"研发中心": "lisi",
"财务部": "sunqi",
# 市场部故意不负责人:用来演示「本级没设负责人时逐级向上兜底」。
}
DEMO_LEADERS = {
"zhangsan": "lisi",
"zhouba": "lisi",
"lisi": "admin",
"zhaoliu": "admin",
"sunqi": "admin",
# wangwu 故意不设直属上级:解析时会退回所在部门负责人,兜到公司负责人。
}
def _demo_account(account: str) -> str:
"""演示数据里写死的内置超管账号 -> 当前 ``[seed] admin_account``。
内置超管改名部署(比如让位给统一身份的 admin,本地这个改叫 localadmin)之后,
演示汇报线还得指向它,不能指向一个已经不存在的账号。
"""
return settings.admin_account if account == DEFAULT_ADMIN_ACCOUNT else account
def _ensure_reporting_lines(db: Session) -> None:
"""补上演示组织的部门负责人与直属上级。
「按发起人部门解析审批人」这条链路要先有组织层级数据才演示得起来;
这里是幂等的:只把 NULL 填上,管理员在界面上改过的值一律不动。
"""
wanted = {_demo_account(a) for a in set(DEMO_UNIT_MANAGERS.values()) | set(DEMO_LEADERS) | set(DEMO_LEADERS.values())}
accounts = {
row.account: row
for row in db.execute(select(models.User).where(models.User.account.in_(sorted(wanted)))).scalars().all()
}
for unit in db.execute(select(models.Unit)).scalars().all():
account = DEMO_UNIT_MANAGERS.get(unit.name)
if not account or unit.manager_person_id:
continue
person = accounts.get(_demo_account(account))
if person is not None:
unit.manager_person_id = person.id
for account, leader_account in DEMO_LEADERS.items():
person, leader = accounts.get(_demo_account(account)), accounts.get(_demo_account(leader_account))
if person is None or leader is None or person.leader_id or person.id == leader.id:
continue
person.leader_id = leader.id
def _repair_dangling_unit_links(db: Session) -> None:
"""身份挂在已删除的部门上时,按身份 DN 里的部门路径把部门链补回来。
删部门、导错数据、统一身份换树都会留下「身份还在、部门没了」的悬空状态:
``users.organization_id`` 被外键置空,``oa_identity.unit_id`` 却没有外键,
依旧指向不存在的行。而「发起人部门负责人 / 逐级上级」这些审批人来源全靠部门
链算人,链一断就悄悄解析不出人,环节最后兜底派回发起人自己,比报错更难查。
只处理 unit_id 明确指向缺失部门的人员,不做任何猜测式改动。
两种情况明确**不补**:
* **系统账号**(内置管理员):它是登录账号,不是公司里的人,没有部门才是对的。
以前给它补出来的部门在界面上删掉后身份仍旧悬着,下次启动又原地长出一棵树,
删了又冒出来。这里反过来把悬空链接解掉,DN 原样留着(审批引用认的是 DN 字符串,
不受影响)。
* **整条路径在本地都不存在**:那说明这个人所属的组织整体换了(典型是换成统一身份
那棵树),补出来的是一棵有自己根节点、永远不会有人维护的平行组织树。补链只补
现有部门底下的那一段,补不了就在日志里点名,交回人工把人归到现有部门。
"""
rows = db.execute(
select(models.Identity).where(models.Identity.unit_id.isnot(None))
).scalars().all()
dangling = [row for row in rows if row.unit_id and db.get(models.Unit, row.unit_id) is None]
if not dangling:
return
cache: dict[str, models.Unit | None] = {}
abandoned: list[str] = []
def unit_for(path_str: str) -> models.Unit | None:
if path_str in cache:
return cache[path_str]
unit = db.execute(
select(models.Unit).where(or_(models.Unit.path == f"{path_str}\\", models.Unit.path == path_str))
).scalar_one_or_none()
if unit is None:
head, _, tail = path_str.rpartition("\\")
# 路径顶端就没有这个部门,补它等于新造一棵树;父级补不出来时子级也一并放弃
parent = unit_for(head) if head else None
if parent is None:
cache[path_str] = None
return None
unit = models.Unit(
name=tail or path_str,
alias=tail or path_str,
description="由身份记录补建",
parent_id=parent.id,
)
db.add(unit)
db.flush()
unit.parent_name = parent.name
unit.path = f"{path_str}\\"
unit.distinguished_name = f"o={path_str}"
unit.short_name = unit.name
db.flush()
cache[path_str] = unit
return unit
for row in dangling:
person = db.get(models.User, row.person_id)
if org.is_system_account(person):
row.unit_id = None
row.unit_name = ""
row.unit_path = ""
logger.info("系统账号 %s 的身份不再挂到补建部门上,悬空链接已解掉(DN 保留:%s)", person.account, row.distinguished_name)
continue
path_str = org.identity_unit(row.distinguished_name or "")
if not path_str:
continue
unit = unit_for(path_str)
if unit is None:
abandoned.append(row.distinguished_name)
continue
row.unit_id = unit.id
row.unit_name = unit.name
row.unit_path = unit.path[:-1]
if person is not None and not person.organization_id and getattr(row, "is_default", False):
person.organization_id = unit.id
if abandoned:
logger.warning(
"%d 条身份的部门整链都不在本地,补链会凭空多出一棵组织树,已跳过;"
"请在人员管理里把这些人归到现有部门:%s",
len(abandoned),
"、".join(abandoned[:5]) + ("…" if len(abandoned) > 5 else ""),
)
def _identity_dn(person: models.User) -> str:
return org.dn_for(person.organization_path, person.display_name, person.account)
def _pid(person: models.User | None) -> str:
"""流程/门户表里的 ``person`` 列是字符串,统一存 ``users.id`` 的字符串形式."""
return str(person.id) if person is not None else ""
def _seed_categories(db: Session) -> None:
items = [
("人事管理", "请假、出差、入职离职等人事类流程", 0),
("财务管理", "报销、付款、借款等财务类流程", 1),
("行政办公", "用章、用车、物品领用等行政流程", 2),
]
for name, description, order in items:
db.add(models.Category(name=name, description=description, order_number=order))
def _seed_processes(db: Session) -> None:
categories = {
c.name: c for c in db.execute(select(models.Category)).scalars().all()
}
roles = {r.name: r for r in db.execute(select(models.Role)).scalars().all()}
hr = categories.get("人事管理")
finance = categories.get("财务管理")
admin = db.execute(select(models.User).where(models.User.account == settings.admin_account)).scalar_one_or_none()
creator_id = _pid(admin)
creator_name = admin.display_name if admin else "系统管理员"
leave_form = models.FormElement(
name="请假申请单", alias="leave_form", description="员工请假申请表单",
content=FORM_LEAVE, editable="edit", order_number=0, person=creator_id,
)
expense_form = models.FormElement(
name="费用报销单", alias="expense_form", description="员工费用报销表单",
content=FORM_EXPENSE, editable="edit", order_number=1, person=creator_id,
)
db.add_all([leave_form, expense_form])
db.flush()
manager_dn = roles["部门负责人"].list_auth[0] if "部门负责人" in roles and roles["部门负责人"].list_auth else ""
finance_dn = roles["财务"].list_auth[0] if "财务" in roles and roles["财务"].list_auth else ""
leave = models.Process(
name="请假申请", alias="leave", description="员工请假审批流程:部门负责人审批,超过 3 天加签总经理。",
category=hr.id if hr else "", category_name=hr.name if hr else "",
latest_form=leave_form.id, latest_form_name=leave_form.name,
enabled=True, published=True, version=1, icon="CalendarClock", color="#2563eb",
order_number=0, creator=creator_id, creator_name=creator_name,
data_template={},
approval_config=dict(DEFAULT_APPROVAL_CONFIG),
)
db.add(leave)
db.flush()
leave_form.process = leave.id
leave_activities = {
"开始": ("begin", 80, 200, {}),
"填写申请": ("manual", 260, 200, {"mode": "any", "first": True, "taskValues": [{"type": "creator", "data": []}]}),
"条件分支": ("choice", 440, 200, {}),
"部门审批": ("manual", 640, 120, {
"mode": "any",
"taskValues": [{"type": "role", "data": ["部门负责人"]}],
"allowGoBack": True, "allowAddTask": True,
"goBackConfig": {"type": "prev", "way": "step"},
"expireType": "day", "expireValue": 2,
}),
"总经理审批": ("manual", 640, 300, {
"mode": "any",
"taskValues": [{"type": "role", "data": ["总经理"]}],
"allowGoBack": True, "allowAddTask": True,
"goBackConfig": {"type": "prev", "way": "step"},
}),
"人事备案": ("manual", 860, 200, {
"mode": "any",
"taskValues": [{"type": "role", "data": ["部门负责人"]}],
"allowGoBack": False, "allowAddTask": True,
}),
"结束": ("end", 1050, 200, {}),
}
nodes = _create_activities(db, leave.id, leave_activities)
db.add_all([
models.Route(process=leave.id, name="提交", alias="提交", from_activity=nodes["开始"], to_activity=nodes["填写申请"], order_number=0),
models.Route(process=leave.id, name="提交审批", alias="提交审批", from_activity=nodes["填写申请"], to_activity=nodes["条件分支"], order_number=0),
models.Route(process=leave.id, name="三天以上", alias="三天以上", from_activity=nodes["条件分支"], to_activity=nodes["总经理审批"],
expression="float(data.get('days') or 0) > 3", order_number=0),
models.Route(process=leave.id, name="三天以内", alias="三天以内", from_activity=nodes["条件分支"], to_activity=nodes["部门审批"], order_number=1),
models.Route(process=leave.id, name="同意", alias="同意", from_activity=nodes["部门审批"], to_activity=nodes["人事备案"], order_number=0),
models.Route(process=leave.id, name="退回", alias="退回", from_activity=nodes["部门审批"], to_activity=nodes["填写申请"], decision="goBack", order_number=1),
models.Route(process=leave.id, name="同意", alias="同意", from_activity=nodes["总经理审批"], to_activity=nodes["人事备案"], order_number=0),
models.Route(process=leave.id, name="退回", alias="退回", from_activity=nodes["总经理审批"], to_activity=nodes["填写申请"], decision="goBack", order_number=1),
models.Route(process=leave.id, name="备案完成", alias="备案完成", from_activity=nodes["人事备案"], to_activity=nodes["结束"], order_number=0),
])
expense = models.Process(
name="费用报销", alias="expense", description="并行会签审批:部门负责人与财务同时审批,双方都同意后出纳付款。",
category=finance.id if finance else "", category_name=finance.name if finance else "",
latest_form=expense_form.id, latest_form_name=expense_form.name,
enabled=True, published=True, version=1, icon="Wallet", color="#0d9488",
order_number=1, creator=creator_id, creator_name=creator_name,
approval_config=dict(DEFAULT_APPROVAL_CONFIG),
)
db.add(expense)
db.flush()
expense_form.process = expense.id
expense_activities = {
"开始": ("begin", 80, 220, {}),
"填写报销": ("manual", 250, 220, {"mode": "any", "first": True, "taskValues": [{"type": "creator", "data": []}]}),
"并行审批": ("parallel", 430, 220, {}),
"部门审核": ("manual", 620, 130, {"mode": "any", "taskValues": [{"type": "role", "data": ["部门负责人"]}]}),
"财务审核": ("manual", 620, 320, {"mode": "all", "taskValues": [{"type": "role", "data": ["财务"]}]}),
"汇总": ("merge", 820, 220, {}),
"金额判断": ("choice", 990, 220, {}),
"总经理复核": ("manual", 1180, 130, {"mode": "any", "taskValues": [{"type": "role", "data": ["总经理"]}]}),
"出纳付款": ("manual", 1180, 320, {"mode": "any", "taskValues": [{"type": "role", "data": ["财务"]}]}),
"结束": ("end", 1380, 220, {}),
}
enodes = _create_activities(db, expense.id, expense_activities)
db.add_all([
models.Route(process=expense.id, name="提交", from_activity=enodes["开始"], to_activity=enodes["填写报销"], order_number=0),
models.Route(process=expense.id, name="提交审批", from_activity=enodes["填写报销"], to_activity=enodes["并行审批"], order_number=0),
models.Route(process=expense.id, name="部门线", from_activity=enodes["并行审批"], to_activity=enodes["部门审核"], order_number=0),
models.Route(process=expense.id, name="财务线", from_activity=enodes["并行审批"], to_activity=enodes["财务审核"], order_number=1),
models.Route(process=expense.id, name="部门完成", from_activity=enodes["部门审核"], to_activity=enodes["汇总"], order_number=0),
models.Route(process=expense.id, name="财务完成", from_activity=enodes["财务审核"], to_activity=enodes["汇总"], order_number=1),
models.Route(process=expense.id, name="汇总", from_activity=enodes["汇总"], to_activity=enodes["金额判断"], order_number=0),
models.Route(process=expense.id, name="大额", from_activity=enodes["金额判断"], to_activity=enodes["总经理复核"],
expression="float(data.get('amount') or 0) >= 5000", order_number=0),
models.Route(process=expense.id, name="普通", from_activity=enodes["金额判断"], to_activity=enodes["出纳付款"], order_number=1),
models.Route(process=expense.id, name="同意", from_activity=enodes["总经理复核"], to_activity=enodes["出纳付款"], order_number=0),
models.Route(process=expense.id, name="付款完成", from_activity=enodes["出纳付款"], to_activity=enodes["结束"], order_number=0),
])
_ = manager_dn, finance_dn
#: 与 api/design.DEFAULT_APPROVAL 一致:演示流程出厂三条去重规则都是关的。
#: 默认开着「发起人不重复审批」会把「填写申请」连同发起人的待办一起吞掉;
#: 默认开着「审批人去重」会让演示里的第二个环节静默走过,看不出流程在流转。
DEFAULT_APPROVAL_CONFIG: dict = {"skipStarter": False, "dedup": "none", "dedupAhead": "none"}
#: 出厂演示字典:一张平表、一张层级(省→市)、一张带附加值(选物品带出单价)。
DEMO_DICTS: list[dict] = [
{
"code": "expense_cate", "name": "费用类别",
"description": "报销明细里的费用归类,表单下拉可直接引用。",
"items": [
{"value": "traffic", "label": "交通费", "extra": {"rate": "按实报销"}},
{"value": "stay", "label": "住宿费", "extra": {"rate": "限额 500/晚"}},
{"value": "meal", "label": "餐补", "extra": {"rate": "100/天"}},
],
},
{
"code": "region", "name": "省市", "tree": True,
"description": "层级字典:表单里把「市」的级联上级设成「省」就能联动。",
"items": [
{"value": "gd", "label": "广东"},
{"value": "zj", "label": "浙江"},
{"value": "sz", "label": "深圳", "parent": "gd", "extra": {"zone": "华南"}},
{"value": "gz", "label": "广州", "parent": "gd", "extra": {"zone": "华南"}},
{"value": "hz", "label": "杭州", "parent": "zj", "extra": {"zone": "华东"}},
{"value": "nb", "label": "宁波", "parent": "zj", "extra": {"zone": "华东"}},
],
},
{
"code": "supply", "name": "办公用品",
"description": "字典项带附加值,表单可用「字典带出」把单价写进明细。",
"items": [
{"value": "pen", "label": "签字笔", "extra": {"price": 3.5, "unit": "支"}},
{"value": "notebook", "label": "笔记本", "extra": {"price": 12, "unit": "本"}},
{"value": "bag", "label": "文件夹", "extra": {"price": 6, "unit": "个"}},
],
},
]
def _seed_dicts(db: Session) -> None:
"""只补缺:已经在用的字典编码不覆盖,避免把运维改过的选项打回出厂值。"""
existing = {row.code for row in db.execute(select(models.DictType)).scalars().all()}
for index, spec in enumerate(DEMO_DICTS):
code = str(spec["code"])
if code in existing:
continue
db.add(
models.DictType(
code=code,
name=str(spec["name"]),
description=str(spec.get("description") or ""),
tree=bool(spec.get("tree")),
order_number=index,
)
)
for order, item in enumerate(spec.get("items") or []):
db.add(
models.DictItem(
type=code,
value=str(item["value"]),
label=str(item.get("label") or item["value"]),
parent=str(item.get("parent") or ""),
extra=dict(item.get("extra") or {}),
order_number=order,
)
)
def _create_activities(db: Session, process_id: str, spec: dict) -> dict[str, str]:
ids: dict[str, str] = {}
for index, (name, (type_, x, y, config)) in enumerate(spec.items()):
row = models.Activity(
process=process_id, type=type_, name=name, alias=name, x=x, y=y,
order_number=index, config=config,
)
db.add(row)
db.flush()
ids[name] = row.id
return ids
# ------------------------------ 门户首页内容 ------------------------------
PORTAL_CHANNELS = [
("公司通知公告", "通知公告", "公司层面的通知公告", 10),
("新闻动态", "新闻", "公司与部门动态", 20),
("制度文件", "制度", "规章制度与流程说明", 30),
]
PORTAL_DOCUMENTS = [
{
"channel": "公司通知公告", "title": "关于 2026 年国庆节放假安排的通知",
"summary": "根据国家法定节假日安排,现将公司国庆节放假及调休安排通知如下,请各部门提前安排好工作交接。",
"body": "<p>各部门、各项目组:</p><p>根据《国务院办公厅关于放假安排的通知》,结合公司实际情况,现将放假安排通知如下:</p><ul><li>放假时间:10 月 1 日至 10 月 7 日,共 7 天。</li><li>值班安排:由综合管理部统一排班,值班人员保持手机畅通。</li><li>请假流程:节前请通过「请假申请」流程提交,确保 9 月 30 日前完成审批。</li></ul><p>特此通知。</p><p style='text-align:right'>综合管理部</p>",
"is_hot": True, "pinned": True, "days_ago": 1,
"cover": "notice-holiday.png",
},
{
"channel": "公司通知公告", "title": "新版流程审批平台 UniSOA 上线试运行",
"summary": "UniSOA 流程审批平台已完成请假申请、费用报销两条主流程的迁移,即日起进入试运行阶段。",
"body": "<p>UniSOA 流程审批平台已上线,首批开放「请假申请」与「费用报销」两条流程。</p><p>相比旧平台,新平台支持可视化流程设计、或签会签、退回加签转办、已办撤回、流程代理与待办交接,并提供流程监控与统计分析。</p><p>试运行期间如遇问题,请通过综合管理部反馈。</p>",
"is_hot": True, "pinned": False, "days_ago": 0,
"cover": "notice-unisoa.png",
},
{
"channel": "新闻动态", "title": "研发中心完成季度技术复盘,明确下季度三个方向",
"summary": "本季度复盘会确定了平台化、可观测性与研发效能三条主线,并沉淀了 12 项改进措施。",
"body": "<p>研发中心于本周召开季度技术复盘会,会议围绕系统稳定性、交付效率与人才梯队展开讨论。</p><p>会议明确下季度三个方向:平台能力沉淀、全链路可观测性建设、研发效能度量。</p>",
"is_hot": True, "pinned": False, "days_ago": 2,
"cover": "news-tech-review.png",
},
{
"channel": "新闻动态", "title": "市场部完成年度渠道伙伴大会参展",
"summary": "本次参展共触达潜在客户 180 余家,收集有效商机 46 条,已由销售团队跟进。",
"body": "<p>市场部在本次渠道伙伴大会期间共触达潜在客户 180 余家,收集有效商机 46 条。</p><p>后续将由销售团队按区域分配跟进,市场部提供物料与技术支持。</p>",
"is_hot": True, "pinned": False, "days_ago": 4,
"cover": "news-channel-show.png",
},
{
"channel": "制度文件", "title": "费用报销管理制度(2026 修订版)",
"summary": "明确差旅、招待、办公用品三类费用的标准、审批权限与报销时限,5000 元以上需总经理复核。",
"body": "<p>一、差旅费:按职级标准据实报销,需附行程单与发票。</p><p>二、招待费:单笔 2000 元以下由部门负责人审批。</p><p>三、报销时限:费用发生后 30 日内通过「费用报销」流程提交,逾期需补充说明。</p><p>四、金额 5000 元及以上需总经理复核后方可付款。</p>",
"is_hot": False, "pinned": False, "days_ago": 6,
},
{
"channel": "制度文件", "title": "信息安全与数据分级管理规范",
"summary": "对公司数据资产分级、访问授权、外发审批与审计留痕提出要求,全员需在月底前完成学习。",
"body": "<p>数据分为公开、内部、机密、绝密四级,分别设定访问与外发要求。</p><p>机密及以上数据的对外提供需走审批流程并留痕;离职人员账号在离职当日停用。</p>",
"is_hot": False, "pinned": False, "days_ago": 9,
},
{
"channel": "新闻动态", "title": "综合管理部启动岗位胜任力评估",
"summary": "评估覆盖全部管理与专业序列,结果将用于培训规划与晋升参考。",
"body": "<p>本次评估覆盖管理与专业序列全部岗位,采用自评加上级评价加同事互评的方式。</p>",
"is_hot": False, "pinned": False, "days_ago": 12,
},
]
PORTAL_FILES = [
("2026年国庆节放假通知.pdf", "pdf", "制度文件"),
("费用报销管理制度-2026修订版.docx", "docx", "制度文件"),
("季度技术复盘会议纪要.md", "md", "会议纪要"),
("渠道伙伴大会参展总结.pptx", "pptx", "会议纪要"),
("员工手册-信息安全章节.pdf", "pdf", "制度文件"),
("流程审批操作指引.md", "md", "操作指引"),
]
PORTAL_COLORS = ["#0d9488", "#2563eb", "#f59e0b", "#dc2626", "#7c3aed"]
#: 演示网盘文件在存储后端里的目录前缀
DEMO_DRIVE_ROOT = "drive/seed"
PORTAL_COVER_ASSETS = Path(__file__).resolve().parent.parent / "assets" / "portal_covers"
def upload_root() -> Path:
"""Legacy local staging folder, kept so pre-existing cover rows still resolve."""
from .storage import local_store
root = local_store().root / "portal"
root.mkdir(parents=True, exist_ok=True)
return root
def stage_cover(name: str) -> str:
"""Copy a bundled homepage cover image into upload storage.
Returns the stored file name, or an empty string when the asset is missing so
that seeding never points at a picture that does not exist. Re-copies when
``scripts/gen_portal_covers.py`` has regenerated the asset underneath us.
"""
source = PORTAL_COVER_ASSETS / name
if not name or not source.is_file():
return ""
# 封面按 [storage].portal_backend 落盘(默认 MinIO);只比文件大小判新旧,
# 够用了,而且对象存储上没有 mtime 可比。
from .storage import StorageError, store_for
key = f"portal/cover/{name}"
try:
store = store_for("portal")
location = store.uri_for(key)
if store.exists(location) and store.size(location) == source.stat().st_size:
return location
return store.save(purpose="portal/cover", name=name, data=source.read_bytes(), key=key).uri
except StorageError as exc:
logger.warning("seed: 封面 %s 存放失败(%s),退回本地目录", name, exc)
folder = upload_root() / "cover"
folder.mkdir(parents=True, exist_ok=True)
target = folder / name
stale = True
if target.is_file():
src, dst = source.stat(), target.stat()
stale = src.st_size != dst.st_size or src.st_mtime_ns > dst.st_mtime_ns
if stale:
shutil.copyfile(source, target)
return name
def _seed_auth_roles(db: Session) -> None:
"""Create the built-in permission roles and hand everybody a starting one.
Existing rows are never overwritten: an edited role stays edited across
restarts. People who already own a role keep exactly that role, so only
unassigned accounts get the default split (admin -> 超级管理员).
"""
for spec in permissions.BUILTIN_ROLES:
exists = db.execute(
select(models.AuthRole.id).where(models.AuthRole.name == spec.name)
).scalar_one_or_none()
if exists:
continue
db.add(
models.AuthRole(
name=spec.name,
description=spec.description,
permissions=list(spec.permissions),
data_scope=spec.data_scope,
builtin=True,
sort=spec.sort,
)
)
db.flush()
by_name = {
r.name: r
for r in db.execute(select(models.AuthRole)).scalars().all()
}
assigned = set(db.execute(select(models.PersonAuthRole.person_id)).scalars().all())
for person in db.execute(select(models.User).order_by(models.User.id)).scalars().all():
if person.id in assigned:
continue
role = by_name.get(
"超级管理员" if person.role == models.ROLE_ADMIN else permissions.FALLBACK_ROLE
)
if role is None:
continue
db.add(models.PersonAuthRole(person_id=person.id, role_id=role.id))
assigned.add(person.id)
def _seed_portal(db: Session) -> None:
"""Fill the homepage content sources so a fresh install is not blank."""
from .api.portal import meeting_number
persons = {p.display_name: p for p in db.execute(select(models.User)).scalars().all()}
if not persons:
return
admin = persons.get("系统管理员") or next(iter(persons.values()))
admin_dn = _identity_dn(admin) if admin else ""
def dn_of(name: str) -> str:
person = persons.get(name)
return _identity_dn(person) if person else ""
# ---- 栏目与信息 ----
if int(db.execute(select(func.count(models.CmsChannel.id))).scalar() or 0) == 0:
channels: dict[str, str] = {}
for name, alias, description, order in PORTAL_CHANNELS:
row = models.CmsChannel(name=name, alias=alias, description=description, order_number=order)
db.add(row)
db.flush()
channels[name] = row.id
for spec in PORTAL_DOCUMENTS:
publish = datetime.now() - timedelta(days=int(spec.get("days_ago", 0)))
db.add(
models.CmsDocument(
channel=channels.get(spec["channel"], ""),
channel_name=spec["channel"],
title=spec["title"],
summary=spec["summary"],
body=spec["body"],
cover=stage_cover(str(spec.get("cover") or "")),
author=admin.display_name,
author_identity=admin_dn,
status="published",
is_hot=bool(spec.get("is_hot")),
pinned=bool(spec.get("pinned")),
views=random.randint(5, 160),
publish_time=publish,
)
)
db.flush()
logger.info("seed: 门户信息与热点新闻已初始化")
# ---- 会议 ----
if int(db.execute(select(func.count(models.Meeting.id))).scalar() or 0) == 0:
today = datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)
plan = [
("研发中心周会", today + timedelta(days=1, hours=2), timedelta(hours=1), "研发中心",
"研发会议室", ["张三", "李四", "周八"], "讨论本季度三个方向的落地排期。"),
(" UniSOA 试运行问题复盘", today + timedelta(days=2, hours=5), timedelta(hours=2), "综合管理部",
"第一会议室", ["张三", "赵六", "李四"], "收集试运行期间反馈的问题并分派整改。"),
("财务月度对账会", today + timedelta(days=5, hours=3), timedelta(hours=1), "财务部",
"财务洽谈室", ["孙七", "赵六"], "核对上月费用报销与付款进度。"),
("市场商机评审会", today + timedelta(days=9, hours=6), timedelta(hours=2), "市场部",
"线上会议", ["王五", "赵六"], "逐条评审参展收集的 46 条商机。"),
]
for title, start, span, unit_name, location, attendees, content in plan:
meeting = models.Meeting(
title=title.strip(), content=content, location=location,
link="https://meeting.unissense.com/" + meeting_number() if location == "线上会议" else "",
number=meeting_number(), start_time=start, end_time=start + span,
unit=persons[attendees[0]].organization_path if attendees[0] in persons else "",
unit_name=unit_name, creator=_pid(admin), creator_person=admin.display_name,
creator_identity=admin_dn,
)
db.add(meeting)
db.flush()
db.add(
models.MeetingAttendee(
meeting=meeting.id, identity=admin_dn, person=_pid(admin),
person_name=admin.display_name,
unit_name=admin.organization_name, role="organizer", status="accepted",
answer_time=start - timedelta(days=1),
)
)
for name in attendees:
person = persons.get(name)
if person is None:
continue
db.add(
models.MeetingAttendee(
meeting=meeting.id, identity=_identity_dn(person), person=_pid(person),
person_name=person.display_name, unit_name=person.organization_name, role="attendee",
status="pending",
)
)
db.flush()
logger.info("seed: 门户会议已初始化")
# ---- 日程 ----
if int(db.execute(select(func.count(models.Schedule.id))).scalar() or 0) == 0:
owner_name = "张三" if "张三" in persons else admin.display_name
owner = persons[owner_name]
owner_dn = _identity_dn(owner)
morning = datetime.now().replace(hour=9, minute=30, second=0, microsecond=0)
plan = [
("研发晨会", morning, timedelta(minutes=30), "研发工位区", 0, ["李四", "周八"]),
("与产品对齐流程需求", morning + timedelta(hours=3), timedelta(hours=1), "线上会议", 15, []),
("提交季度报销材料", (morning + timedelta(days=2)).replace(hour=14), timedelta(hours=1), "财务部", 30, []),
("部门季度复盘", (morning + timedelta(days=5)).replace(hour=15), timedelta(hours=2), "研发中心", 60, ["赵六"]),
("制度学习截止", (morning + timedelta(days=8)).replace(hour=18), None, "", 0, []),
]
for index, (title, start, span, location, remind, shared) in enumerate(plan):
db.add(
models.Schedule(
title=title, start_time=start, end_time=start + span if span else None,
location=location, color=PORTAL_COLORS[index % len(PORTAL_COLORS)], remind=remind,
owner=owner_dn, owner_person=_pid(owner), owner_name=owner.display_name,
shared_identities=[d for d in (dn_of(n) for n in shared) if d],
)
)
db.flush()
logger.info("seed: 门户日程已初始化")
# ---- 网盘文件 ----
if int(db.execute(select(func.count(models.PortalFile.id))).scalar() or 0) == 0:
try:
from .storage import StorageError, store_for
store = store_for("drive")
except StorageError as exc:
logger.warning("seed: 网盘后端不可用,跳过演示文件:%s", exc)
store = None
for index, (name, extension, folder) in enumerate(PORTAL_FILES):
payload = (
f"# {name}\n\n这是 UniSOA 门户首页「网盘文件」面板的演示文件,"
f"可直接下载验证接口是否连通。\n\n生成时间:{datetime.now():%Y-%m-%d %H:%M:%s}\n"
).encode("utf-8")
key = f"{DEMO_DRIVE_ROOT}/演示文件/{name}"
storage_uri, size = "", len(payload)
if store is not None:
try:
saved = store.save(purpose="drive", name=name, data=payload, key=key)
storage_uri, size = saved.uri, saved.size
except StorageError as exc:
logger.warning("seed: 演示文件 %s 写入网盘失败:%s", name, exc)
if not storage_uri:
root = upload_root() / "seed"
root.mkdir(parents=True, exist_ok=True)
local = root / f"{uuid.uuid4().hex}.{extension}"
local.write_bytes(payload)
storage_uri, size = str(local), len(payload)
db.add(
models.PortalFile(
name=name, extension=extension, storage=storage_uri, length=size,
folder=folder, owner=admin_dn, owner_person=_pid(admin), owner_name=admin.display_name,
unit_name=admin.organization_name, downloads=random.randint(0, 40),
shared_identities=[d for d in (dn_of(n) for n in ("张三", "李四", "赵六")) if d],
)
)
db.flush()
logger.info("seed: 门户网盘文件已初始化")