seed_users.py
13.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
"""人员信息导入:把 Excel 通讯录与岗位职责导入数据库。
数据源(路径由 config.SEED_EXCEL_DIR 指定):
人员联系方式.xlsx —— 唯一用户源,449 行(架构/中心/部门/岗位/姓名/联系电话/邮箱/照片)
岗位职责.xlsx —— 岗位模板源,117 行(一级部门/二级部门/岗位/岗位职责)
驻店人员组织架构.xlsx —— 仅补「负责门店」与驻店岗位职责,206 行
总部组织架构.xlsx —— 不导入(本方案不建组织树)
已探明的数据质量问题与对策:
- 手机号 445/449 有效,4 个为「/」等空值 → 跳过并在报告中列出,由管理员手工补
- 邮箱仅 250/449 有值且有 2 个前缀重复 → 不用邮箱做账号,统一用手机号
- 岗位职责表中 20 个同名岗位分属不同部门 → 唯一键取 (一级部门, 二级部门, 岗位)
- 通讯录 103 个岗位中 13 个匹配不到模板 → 建空模板并标 template_missing
- 驻店表岗位职责是合并单元格,206 行仅 1 行非空 → 导入前 forward-fill
- 驻店 206 人手机号 100% 已被通讯录覆盖 → 用户只从通讯录导一份
幂等:按手机号 upsert,可重复执行不产生重复用户。
用法:
python scripts/seed_users.py # 正式导入
python scripts/seed_users.py --dry-run # 只输出统计,不写库
"""
import argparse
import asyncio
import os
import re
import sys
from datetime import datetime
import pandas as pd
from sqlalchemy import select
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
from config import DEFAULT_USER_PASSWORD, SEED_EXCEL_DIR # noqa: E402
from src.database.models import WikiPosition, WikiUser, WikiUserProfile # noqa: E402
from src.database.session import AsyncSessionLocal, init_db # noqa: E402
from src.services.identity.local import build_password_fields # noqa: E402
PHONE_RE = re.compile(r"^1\d{10}$")
# 源数据中出现的占位/备注文字,需与真实值区分开。
# 「读取系统」出现在驻店表的负责门店列,是一句备注而非门店名。
_PLACEHOLDERS = {"", "nan", "NaN", "—", "——", "/", "-", "读取系统", "无", "待定"}
def _clean(value) -> str:
"""把单元格值规整为去空白的字符串,NaN 与占位符统一成空串。"""
if value is None or (isinstance(value, float) and pd.isna(value)):
return ""
text = str(value).strip()
if text in _PLACEHOLDERS:
return ""
return text
def _valid_phone(value) -> str:
text = _clean(value)
# Excel 里手机号可能被读成 float(如 13800000000.0)
if text.endswith(".0"):
text = text[:-2]
return text if PHONE_RE.match(text) else ""
def load_position_templates(base_dir: str) -> dict[tuple[str, str, str], dict]:
"""读岗位职责表,返回 {(一级部门, 二级部门, 岗位): {...}}。"""
path = os.path.join(base_dir, "岗位职责.xlsx")
df = pd.read_excel(path, sheet_name="岗位职责")
templates: dict[tuple[str, str, str], dict] = {}
for _, row in df.iterrows():
name = _clean(row.get("岗位"))
if not name:
continue
key = (_clean(row.get("一级部门")), _clean(row.get("二级部门")), name)
templates[key] = {
"duty": _clean(row.get("岗位职责")),
"dept_l1": key[0],
"dept_l2": key[1],
"name": name,
}
return templates
def load_store_info(base_dir: str) -> tuple[dict[str, str], dict[str, str]]:
"""读驻店表,返回 (手机号 -> 负责门店, 岗位名 -> 岗位职责)。
两个数据陷阱:
1. 岗位职责列是合并单元格,206 行里**只有 1 行非空**(属于「门店销售」)。
不能用全表 ffill——那会把「门店销售」的职责错误地填给洗车工、贴膜技师等
后续所有岗位。正确做法是**按岗位分组取组内首个非空值**,
没有值的岗位就是真的没有模板。
2. 负责门店列同样只有 1 行非空,且取值为「读取系统」——这是备注文字而非门店名。
即该表实际上**不含可用的门店归属数据**,全部按缺失处理。
"""
path = os.path.join(base_dir, "驻店人员组织架构.xlsx")
df = pd.read_excel(path, sheet_name="外包架构人员结构")
df["岗位"] = df["岗位"].ffill()
# 按岗位分组取组内首个非空职责,避免跨岗位串味
duties: dict[str, str] = {}
for name, group in df.groupby("岗位"):
name = _clean(name)
if not name:
continue
duty = next((_clean(v) for v in group["岗位职责"] if _clean(v)), "")
if duty:
duties[name] = duty
stores: dict[str, str] = {}
for _, row in df.iterrows():
phone = _valid_phone(row.get("联系电话"))
store = _clean(row.get("负责门店"))
if phone and store:
stores[phone] = store
return stores, duties
def load_contacts(base_dir: str) -> pd.DataFrame:
path = os.path.join(base_dir, "人员联系方式.xlsx")
return pd.read_excel(path, sheet_name="通讯录")
async def upsert_positions(
templates: dict[tuple[str, str, str], dict],
store_duties: dict[str, str],
) -> dict[tuple[str, str, str], str]:
"""写入岗位表,返回 {(dept_l1, dept_l2, name): position_id}。"""
key_to_id: dict[tuple[str, str, str], str] = {}
async with AsyncSessionLocal() as session:
existing = (await session.execute(select(WikiPosition))).scalars().all()
for p in existing:
key_to_id[(p.dept_l1 or "", p.dept_l2 or "", p.name)] = p.id
for key, item in templates.items():
duty = item["duty"]
if key in key_to_id:
continue
position = WikiPosition(
name=item["name"],
dept_l1=item["dept_l1"] or None,
dept_l2=item["dept_l2"] or None,
duty_template=duty or None,
template_missing=not bool(duty),
created_at=datetime.now(),
)
session.add(position)
await session.flush()
key_to_id[key] = position.id
# 驻店岗位(门店销售、贴膜技师等)在职责表里没有,单独补一份
for name, duty in store_duties.items():
key = ("", "", name)
if key in key_to_id:
continue
position = WikiPosition(
name=name,
dept_l1=None,
dept_l2=None,
duty_template=duty or None,
template_missing=not bool(duty),
created_at=datetime.now(),
)
session.add(position)
await session.flush()
key_to_id[key] = position.id
await session.commit()
return key_to_id
def match_position(
key_to_id: dict[tuple[str, str, str], str],
center: str,
dept: str,
position_name: str,
) -> str | None:
"""岗位匹配:三元组精确 → 退化为按岗位名唯一匹配 → 未命中返回 None。"""
if not position_name:
return None
# 1) 精确匹配(中心作一级部门、部门作二级部门)
for key in ((center, dept, position_name), (center, "", position_name), ("", "", position_name)):
if key in key_to_id:
return key_to_id[key]
# 2) 退化:仅按岗位名匹配,且只有唯一命中时才采用,避免张冠李戴
candidates = [pid for (l1, l2, name), pid in key_to_id.items() if name == position_name]
if len(candidates) == 1:
return candidates[0]
return None
async def seed(dry_run: bool = False) -> dict:
base_dir = SEED_EXCEL_DIR
if not os.path.isdir(base_dir):
raise SystemExit(f"数据源目录不存在: {base_dir}")
templates = load_position_templates(base_dir)
stores, store_duties = load_store_info(base_dir)
contacts = load_contacts(base_dir)
report = {
"contacts_rows": len(contacts),
"position_templates": len(templates),
"store_positions": len(store_duties),
"created_users": 0,
"updated_users": 0,
"skipped_no_phone": [],
"position_unmatched": set(),
"created_positions": 0,
}
if dry_run:
print(f"[dry-run] 通讯录 {len(contacts)} 行")
print(f"[dry-run] 岗位模板 {len(templates)} 条,驻店岗位 {len(store_duties)} 条")
valid = sum(1 for _, r in contacts.iterrows() if _valid_phone(r.get("联系电话")))
print(f"[dry-run] 有效手机号 {valid}/{len(contacts)}")
return report
await init_db()
before = len(await _all_position_keys())
key_to_id = await upsert_positions(templates, store_duties)
report["created_positions"] = len(key_to_id) - before
password_hash, password_salt = build_password_fields(DEFAULT_USER_PASSWORD)
async with AsyncSessionLocal() as session:
existing_users = (await session.execute(select(WikiUser))).scalars().all()
by_phone = {u.phone: u for u in existing_users if u.phone}
for _, row in contacts.iterrows():
display_name = _clean(row.get("姓名"))
phone = _valid_phone(row.get("联系电话"))
if not phone:
report["skipped_no_phone"].append(display_name or "(无名)")
continue
if not display_name:
continue
center = _clean(row.get("中心"))
dept = _clean(row.get("部门"))
position_name = _clean(row.get("岗位"))
email = _clean(row.get("邮箱"))
store_name = stores.get(phone)
position_id = match_position(key_to_id, center, dept, position_name)
if position_id is None and position_name:
# 通讯录里有、职责表里没有的岗位:建空模板,交由 LLM 据岗位名兜底生成画像
position = WikiPosition(
name=position_name,
dept_l1=center or None,
dept_l2=dept or None,
duty_template=None,
template_missing=True,
created_at=datetime.now(),
)
session.add(position)
await session.flush()
position_id = position.id
key_to_id[(center, dept, position_name)] = position_id
report["position_unmatched"].add(position_name)
report["created_positions"] += 1
user = by_phone.get(phone)
if user is None:
user = WikiUser(
username=phone,
phone=phone,
display_name=display_name,
email=email or None,
password_hash=password_hash,
password_salt=password_salt,
position_id=position_id,
store_name=store_name,
role="user",
status="active",
created_at=datetime.now(),
)
session.add(user)
await session.flush()
session.add(WikiUserProfile(user_id=user.id, profile_generated=False))
report["created_users"] += 1
else:
# 幂等更新:只补业务属性,**不重置密码**(用户可能已改过)
user.display_name = display_name
user.email = email or user.email
user.position_id = position_id or user.position_id
user.store_name = store_name or user.store_name
report["updated_users"] += 1
await session.commit()
report["position_unmatched"] = sorted(report["position_unmatched"])
return report
async def _all_position_keys() -> list:
async with AsyncSessionLocal() as session:
rows = (await session.execute(select(WikiPosition.id))).scalars().all()
return list(rows)
def print_report(report: dict) -> None:
print()
print("=" * 60)
print("人员导入报告")
print("=" * 60)
print(f" 通讯录总行数 : {report['contacts_rows']}")
print(f" 岗位模板条数 : {report['position_templates']}")
print(f" 驻店岗位条数 : {report['store_positions']}")
print(f" 新建岗位 : {report['created_positions']}")
print(f" 新建用户 : {report['created_users']}")
print(f" 更新用户 : {report['updated_users']}")
print(f" 跳过(无有效手机): {len(report['skipped_no_phone'])}")
for name in report["skipped_no_phone"]:
print(f" - {name}(需管理员手工补手机号)")
unmatched = report["position_unmatched"]
print(f" 无职责模板的岗位 : {len(unmatched)}")
for name in unmatched:
print(f" - {name}")
print("=" * 60)
print(f" 所有新建用户的初始密码为: {DEFAULT_USER_PASSWORD}")
print()
def main() -> None:
parser = argparse.ArgumentParser(description="导入人员信息到数据库")
parser.add_argument("--dry-run", action="store_true", help="只统计不写库")
args = parser.parse_args()
report = asyncio.run(seed(dry_run=args.dry_run))
if not args.dry_run:
print_report(report)
if __name__ == "__main__":
main()