migrate_crm_clue.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  1. #!/usr/bin/env python3
  2. """将 sx 库 CRM 线索相关表迁入 shanxia2.0。
  3. 顺序:crm_clue → crm_clue_follow
  4. 用户外键经 user_mapping 转换;附件 OSS ID → 目标 sys_oss 相对 URL。
  5. 用法:
  6. cd backend
  7. venv/bin/python scripts/migrate_crm_clue.py --dry-run --env-file .env.production
  8. venv/bin/python scripts/migrate_crm_clue.py --env-file .env.production
  9. """
  10. from __future__ import annotations
  11. import argparse
  12. import csv
  13. import os
  14. import sys
  15. from dataclasses import dataclass, field
  16. from datetime import datetime
  17. from pathlib import Path
  18. from typing import Any, Dict, List, Optional, Tuple
  19. from urllib.parse import urlparse, urlunparse
  20. from sqlalchemy import create_engine, text
  21. from sqlalchemy.engine import Engine
  22. BACKEND_ROOT = Path(__file__).resolve().parents[1]
  23. MIGRATION_DIR = BACKEND_ROOT / "scripts" / "migration"
  24. if str(BACKEND_ROOT) not in sys.path:
  25. sys.path.insert(0, str(BACKEND_ROOT))
  26. if str(MIGRATION_DIR) not in sys.path:
  27. sys.path.insert(0, str(MIGRATION_DIR))
  28. from minio_url import resolve_oss_id_csv # noqa: E402
  29. DEFAULT_TENANT_NO = "shanxia2.0"
  30. CRM_ADMIN_SOURCE_USER_ID = 1
  31. CUSTOMER_TYPE_MAP = {
  32. "company": "company",
  33. "person": "person",
  34. "未分类": None,
  35. "a类国央企单位": "A类国央企业",
  36. "A类国央企单位": "A类国央企业",
  37. "A类国央企业": "A类国央企业",
  38. "b类股份制企业": "B类股份制企业",
  39. "B类股份制企业": "B类股份制企业",
  40. "c类私营单位": "C类私营企业",
  41. "C类私营企业": "C类私营企业",
  42. "d外商投资企业": "D外商投资企业",
  43. "D外商投资企业": "D外商投资企业",
  44. "e类国资委企业": "5",
  45. "5": "5",
  46. }
  47. FOLLOW_TYPE_MAP = {
  48. "电话": "phone",
  49. "phone": "phone",
  50. "微信": "wechat",
  51. "wechat": "wechat",
  52. "邮件": "email",
  53. "email": "email",
  54. "拜访": "visit",
  55. "visit": "visit",
  56. "其他": "other",
  57. "other": "other",
  58. }
  59. MIGRATION_STEPS = (
  60. ("crm_clue", "clue"),
  61. ("crm_clue_follow", "clue_follow"),
  62. )
  63. @dataclass
  64. class StepStats:
  65. source_count: int = 0
  66. inserted: int = 0
  67. updated: int = 0
  68. skipped: int = 0
  69. @dataclass
  70. class MigrationStats:
  71. steps: Dict[str, StepStats] = field(default_factory=dict)
  72. warnings: List[str] = field(default_factory=list)
  73. def step(self, name: str) -> StepStats:
  74. if name not in self.steps:
  75. self.steps[name] = StepStats()
  76. return self.steps[name]
  77. def legacy_id_to_str(legacy_id: Any) -> Optional[str]:
  78. if legacy_id is None or str(legacy_id).strip() == "":
  79. return None
  80. try:
  81. return str(int(legacy_id))
  82. except (TypeError, ValueError):
  83. return str(legacy_id).strip()
  84. def derive_source_url(target_url: str, source_db: str = "sx") -> str:
  85. return urlunparse(urlparse(target_url)._replace(path=f"/{source_db}"))
  86. def load_settings_env(env_file: Optional[str]) -> None:
  87. if env_file:
  88. os.environ["ENV_FILE"] = env_file
  89. from dotenv import load_dotenv
  90. candidates: List[Path] = []
  91. if env_file:
  92. p = Path(env_file)
  93. candidates.append(p if p.is_absolute() else BACKEND_ROOT / p)
  94. candidates.extend([BACKEND_ROOT / ".env.production", BACKEND_ROOT / ".env"])
  95. for path in candidates:
  96. if path.is_file():
  97. load_dotenv(path, override=True)
  98. break
  99. def load_runtime_settings():
  100. from app.core.config import Settings
  101. return Settings()
  102. def load_user_mapping(path: Path) -> Tuple[Dict[int, str], Optional[str]]:
  103. crm_map: Dict[int, str] = {}
  104. admin_id: Optional[str] = None
  105. with path.open(encoding="utf-8-sig", newline="") as f:
  106. for row in csv.DictReader(f):
  107. new_id = (row.get("new_user_id") or "").strip()
  108. user_no = (row.get("user_no") or "").strip()
  109. crm_raw = (row.get("crm_user_id") or "").strip()
  110. if user_no == "admin" and new_id:
  111. admin_id = new_id
  112. if crm_raw and new_id:
  113. try:
  114. crm_map[int(crm_raw)] = new_id
  115. except ValueError:
  116. pass
  117. return crm_map, admin_id
  118. def fetch_portal_admin_id(target_engine: Engine) -> Optional[str]:
  119. with target_engine.connect() as conn:
  120. row = conn.execute(
  121. text("SELECT id FROM sys_user WHERE user_no='admin' AND del_flag=0 LIMIT 1")
  122. ).first()
  123. return str(row[0]) if row and row[0] else None
  124. def resolve_portal_user_id(
  125. source_user_id: Any,
  126. crm_user_map: Dict[int, str],
  127. admin_id: Optional[str],
  128. stats: MigrationStats,
  129. label: str,
  130. ) -> Optional[str]:
  131. if source_user_id is None or str(source_user_id).strip() == "":
  132. return None
  133. try:
  134. uid = int(source_user_id)
  135. except (TypeError, ValueError):
  136. stats.warnings.append(f"{label}: 非法用户 id {source_user_id!r}")
  137. return None
  138. if uid == CRM_ADMIN_SOURCE_USER_ID:
  139. return admin_id
  140. mapped = crm_user_map.get(uid)
  141. if not mapped:
  142. stats.warnings.append(f"{label}: crm_user_id={uid} 无映射")
  143. return mapped
  144. def load_oss_id_to_url(target_engine: Engine, tenant_no: str) -> Dict[str, str]:
  145. with target_engine.connect() as conn:
  146. rows = conn.execute(
  147. text("SELECT id, url FROM sys_oss WHERE tenant_no=:t AND del_flag=0"),
  148. {"t": tenant_no},
  149. ).mappings().all()
  150. return {str(r["id"]): (r["url"] or "").strip() for r in rows if r["id"]}
  151. def normalize_customer_type(raw: Any, stats: MigrationStats, label: str) -> Optional[str]:
  152. value = (str(raw).strip() if raw is not None else "") or ""
  153. if not value:
  154. return None
  155. if value in CUSTOMER_TYPE_MAP:
  156. mapped = CUSTOMER_TYPE_MAP[value]
  157. if mapped is None:
  158. stats.warnings.append(f"{label}: customer_type={value!r} 已置空")
  159. return mapped
  160. lowered = value.lower()
  161. for key, mapped in CUSTOMER_TYPE_MAP.items():
  162. if key.lower() == lowered:
  163. return mapped
  164. stats.warnings.append(f"{label}: customer_type={value!r} 未识别,已置空")
  165. return None
  166. def normalize_follow_type(raw: Any) -> str:
  167. value = (str(raw).strip() if raw is not None else "") or "other"
  168. return FOLLOW_TYPE_MAP.get(value, FOLLOW_TYPE_MAP.get(value.lower(), "other"))
  169. def _str_or_none(value: Any, max_len: int = 0) -> Optional[str]:
  170. if value is None:
  171. return None
  172. s = str(value).strip()
  173. if not s:
  174. return None
  175. return s[:max_len] if max_len else s
  176. def fetch_source_rows(engine: Engine, table: str, include_deleted: bool) -> List[dict]:
  177. where = "" if include_deleted else "WHERE del_flag = 0"
  178. sql = f"SELECT * FROM `{table}` {where} ORDER BY id ASC"
  179. with engine.connect() as conn:
  180. return [dict(r._mapping) for r in conn.execute(text(sql))]
  181. def target_row_exists(conn, table: str, row_id: str) -> bool:
  182. return int(conn.execute(text(f"SELECT COUNT(*) FROM `{table}` WHERE id=:id"), {"id": row_id}).scalar_one()) > 0
  183. def transform_clue(
  184. row: dict,
  185. tenant_no: str,
  186. crm_user_map: Dict[int, str],
  187. admin_id: Optional[str],
  188. stats: MigrationStats,
  189. ) -> dict:
  190. rid = legacy_id_to_str(row["id"])
  191. label = f"clue#{rid}"
  192. def map_user(field_val: Any) -> Optional[str]:
  193. return resolve_portal_user_id(field_val, crm_user_map, admin_id, stats, label)
  194. return {
  195. "id": rid,
  196. "clue_name": (row.get("clue_name") or "")[:100],
  197. "mobile": (row.get("mobile") or "")[:20],
  198. "company": _str_or_none(row.get("company"), 200),
  199. "customer_type": normalize_customer_type(row.get("customer_type"), stats, label),
  200. "telephone": _str_or_none(row.get("telephone"), 30),
  201. "email": _str_or_none(row.get("email"), 100),
  202. "title": _str_or_none(row.get("title"), 10),
  203. "position": _str_or_none(row.get("position"), 50),
  204. "source": (row.get("source") or "")[:20],
  205. "level": (row.get("level") or "unrated")[:10],
  206. "industry": _str_or_none(row.get("industry"), 50),
  207. "park_area": _str_or_none(row.get("park_area"), 100),
  208. "province": _str_or_none(row.get("province"), 50),
  209. "city": _str_or_none(row.get("city"), 50),
  210. "district": _str_or_none(row.get("district"), 50),
  211. "address": _str_or_none(row.get("address"), 255),
  212. "website": _str_or_none(row.get("website"), 500),
  213. "intent_products": _str_or_none(row.get("intent_products"), 500),
  214. "expect_time": row.get("expect_time"),
  215. "budget": _str_or_none(row.get("budget"), 20),
  216. "requirement": row.get("requirement"),
  217. "status": (row.get("status") or "new")[:20],
  218. "owner_user_id": map_user(row.get("owner_user_id")),
  219. "owner_user_name": _str_or_none(row.get("owner_user_name"), 50),
  220. "last_time": row.get("last_time"),
  221. "next_time": row.get("next_time"),
  222. "follow_count": int(row.get("follow_count") or 0),
  223. "is_converted": int(row.get("is_converted") or 0),
  224. "converted_time": row.get("converted_time"),
  225. "customer_id": legacy_id_to_str(row.get("customer_id")),
  226. "converted_by": map_user(row.get("converted_by")),
  227. "assign_time": row.get("assign_time"),
  228. "assign_by": map_user(row.get("assign_by")),
  229. "tenant_no": tenant_no,
  230. "order_num": 0,
  231. "remark": _str_or_none(row.get("remark"), 500),
  232. "create_by": map_user(row.get("create_by")),
  233. "create_dept_id": "",
  234. "create_time": row.get("create_time") or datetime.now(),
  235. "update_by": map_user(row.get("update_by")),
  236. "update_time": row.get("update_time") or row.get("create_time") or datetime.now(),
  237. "del_flag": int(row.get("del_flag") or 0),
  238. }
  239. def transform_clue_follow(
  240. row: dict,
  241. tenant_no: str,
  242. crm_user_map: Dict[int, str],
  243. admin_id: Optional[str],
  244. oss_map: Dict[str, str],
  245. stats: MigrationStats,
  246. ) -> dict:
  247. rid = legacy_id_to_str(row["id"])
  248. label = f"clue_follow#{rid}"
  249. owner_id = resolve_portal_user_id(row.get("create_by"), crm_user_map, admin_id, stats, label)
  250. return {
  251. "id": rid,
  252. "clue_id": legacy_id_to_str(row.get("clue_id")),
  253. "clue_name": _str_or_none(row.get("clue_name"), 100),
  254. "follow_type": normalize_follow_type(row.get("follow_type")),
  255. "follow_content": row.get("follow_content") or "",
  256. "next_time": row.get("next_time"),
  257. "attachments": resolve_oss_id_csv(row.get("attachments"), oss_map) or None,
  258. "create_by_name": _str_or_none(row.get("create_by_name"), 50),
  259. "tenant_no": tenant_no,
  260. "order_num": 0,
  261. "remark": _str_or_none(row.get("remark"), 500),
  262. "create_by": owner_id,
  263. "create_dept_id": "",
  264. "create_time": row.get("create_time") or datetime.now(),
  265. "update_by": resolve_portal_user_id(row.get("update_by"), crm_user_map, admin_id, stats, label),
  266. "update_time": row.get("update_time") or row.get("create_time") or datetime.now(),
  267. "del_flag": int(row.get("del_flag") or 0),
  268. }
  269. INSERT_CLUE_SQL = text(
  270. """
  271. INSERT INTO crm_clue (
  272. id, clue_name, mobile, company, customer_type, telephone, email, title, position,
  273. source, level, industry, park_area, province, city, district, address, website,
  274. intent_products, expect_time, budget, requirement, status, owner_user_id, owner_user_name,
  275. last_time, next_time, follow_count, is_converted, converted_time, customer_id,
  276. converted_by, assign_time, assign_by, tenant_no, order_num, remark,
  277. create_by, create_dept_id, create_time, update_by, update_time, del_flag
  278. ) VALUES (
  279. :id, :clue_name, :mobile, :company, :customer_type, :telephone, :email, :title, :position,
  280. :source, :level, :industry, :park_area, :province, :city, :district, :address, :website,
  281. :intent_products, :expect_time, :budget, :requirement, :status, :owner_user_id, :owner_user_name,
  282. :last_time, :next_time, :follow_count, :is_converted, :converted_time, :customer_id,
  283. :converted_by, :assign_time, :assign_by, :tenant_no, :order_num, :remark,
  284. :create_by, :create_dept_id, :create_time, :update_by, :update_time, :del_flag
  285. )
  286. """
  287. )
  288. INSERT_CLUE_FOLLOW_SQL = text(
  289. """
  290. INSERT INTO crm_clue_follow (
  291. id, clue_id, clue_name, follow_type, follow_content, next_time, attachments,
  292. create_by_name, tenant_no, order_num, remark, create_by, create_dept_id,
  293. create_time, update_by, update_time, del_flag
  294. ) VALUES (
  295. :id, :clue_id, :clue_name, :follow_type, :follow_content, :next_time, :attachments,
  296. :create_by_name, :tenant_no, :order_num, :remark, :create_by, :create_dept_id,
  297. :create_time, :update_by, :update_time, :del_flag
  298. )
  299. """
  300. )
  301. STEP_INSERT_SQL = {
  302. "crm_clue": INSERT_CLUE_SQL,
  303. "crm_clue_follow": INSERT_CLUE_FOLLOW_SQL,
  304. }
  305. def write_mapping_csv(source_rows: List[dict], path: Path) -> None:
  306. path.parent.mkdir(parents=True, exist_ok=True)
  307. migrated_at = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
  308. with path.open("w", encoding="utf-8", newline="") as f:
  309. w = csv.DictWriter(f, fieldnames=["source_id", "new_id", "migrated_at"])
  310. w.writeheader()
  311. for row in source_rows:
  312. sid = legacy_id_to_str(row["id"])
  313. w.writerow({"source_id": sid, "new_id": sid, "migrated_at": migrated_at})
  314. def migrate_table(
  315. source_engine: Engine,
  316. target_engine: Engine,
  317. table: str,
  318. *,
  319. tenant_no: str,
  320. crm_user_map: Dict[int, str],
  321. admin_id: Optional[str],
  322. oss_map: Dict[str, str],
  323. stats: MigrationStats,
  324. dry_run: bool,
  325. update_existing: bool,
  326. include_deleted: bool,
  327. ) -> List[dict]:
  328. step = stats.step(table)
  329. source_rows = fetch_source_rows(source_engine, table, include_deleted)
  330. step.source_count = len(source_rows)
  331. transformers = {
  332. "crm_clue": lambda r: transform_clue(r, tenant_no, crm_user_map, admin_id, stats),
  333. "crm_clue_follow": lambda r: transform_clue_follow(
  334. r, tenant_no, crm_user_map, admin_id, oss_map, stats
  335. ),
  336. }
  337. payloads = [transformers[table](r) for r in source_rows]
  338. if dry_run:
  339. step.inserted = len(payloads)
  340. return source_rows
  341. insert_sql = STEP_INSERT_SQL[table]
  342. with target_engine.begin() as conn:
  343. for payload in payloads:
  344. rid = payload["id"]
  345. if target_row_exists(conn, table, rid):
  346. if update_existing:
  347. step.skipped += 1
  348. else:
  349. step.skipped += 1
  350. else:
  351. conn.execute(insert_sql, payload)
  352. step.inserted += 1
  353. return source_rows
  354. def print_report(stats: MigrationStats, dry_run: bool) -> None:
  355. mode = "DRY-RUN" if dry_run else "COMMITTED"
  356. print(f"\n=== CRM 线索表迁移 [{mode}] ===")
  357. for table, _ in MIGRATION_STEPS:
  358. s = stats.step(table)
  359. print(f"{table}: 源={s.source_count} 插入={s.inserted} 跳过={s.skipped}")
  360. if stats.warnings:
  361. print(f"警告 ({len(stats.warnings)}):")
  362. for w in stats.warnings[:20]:
  363. print(f" - {w}")
  364. if len(stats.warnings) > 20:
  365. print(f" ... 另有 {len(stats.warnings) - 20} 条")
  366. def run_migration(
  367. source_engine: Engine,
  368. target_engine: Engine,
  369. *,
  370. tenant_no: str,
  371. user_mapping_path: Path,
  372. mapping_dir: Path,
  373. dry_run: bool,
  374. update_existing: bool,
  375. include_deleted: bool,
  376. only_tables: Optional[List[str]],
  377. ) -> MigrationStats:
  378. stats = MigrationStats()
  379. crm_user_map, admin_id = load_user_mapping(user_mapping_path)
  380. if not admin_id:
  381. admin_id = fetch_portal_admin_id(target_engine)
  382. oss_map = load_oss_id_to_url(target_engine, tenant_no)
  383. print(f"sys_oss 映射条数: {len(oss_map)}")
  384. selected = [t for t, _ in MIGRATION_STEPS if not only_tables or t in only_tables]
  385. for table in selected:
  386. print(f"\n>> 迁移 {table} ...")
  387. source_rows = migrate_table(
  388. source_engine,
  389. target_engine,
  390. table,
  391. tenant_no=tenant_no,
  392. crm_user_map=crm_user_map,
  393. admin_id=admin_id,
  394. oss_map=oss_map,
  395. stats=stats,
  396. dry_run=dry_run,
  397. update_existing=update_existing,
  398. include_deleted=include_deleted,
  399. )
  400. if table == "crm_clue" and not dry_run:
  401. write_mapping_csv(source_rows, mapping_dir / "crm_clue_id_mapping.csv")
  402. print_report(stats, dry_run)
  403. return stats
  404. def main() -> int:
  405. parser = argparse.ArgumentParser(description="Migrate CRM clue tables from sx to portal")
  406. parser.add_argument("--source-url", default="")
  407. parser.add_argument("--target-url", default="")
  408. parser.add_argument("--tenant-no", default=DEFAULT_TENANT_NO)
  409. parser.add_argument(
  410. "--user-mapping",
  411. default=str(BACKEND_ROOT.parent / "docs/data-migration/mappings/user_mapping_result.csv"),
  412. )
  413. parser.add_argument("--dry-run", action="store_true")
  414. parser.add_argument("--update", action="store_true")
  415. parser.add_argument("--include-deleted", action="store_true")
  416. parser.add_argument("--tables", default="", help="逗号分隔,默认全部两表")
  417. parser.add_argument("--env-file", default=os.environ.get("ENV_FILE", ""))
  418. args = parser.parse_args()
  419. load_settings_env(args.env_file or None)
  420. settings = load_runtime_settings()
  421. target_url = args.target_url or settings.DATABASE_URL
  422. source_url = args.source_url or os.environ.get("SX_SOURCE_DATABASE_URL") or derive_source_url(target_url)
  423. only_tables = [t.strip() for t in args.tables.split(",") if t.strip()] or None
  424. print(f"源库: {urlparse(source_url).path}")
  425. print(f"目标库: {urlparse(target_url).path}")
  426. run_migration(
  427. create_engine(source_url, pool_pre_ping=True),
  428. create_engine(target_url, pool_pre_ping=True),
  429. tenant_no=args.tenant_no,
  430. user_mapping_path=Path(args.user_mapping),
  431. mapping_dir=BACKEND_ROOT.parent / "docs/data-migration/mappings",
  432. dry_run=args.dry_run,
  433. update_existing=args.update,
  434. include_deleted=args.include_deleted,
  435. only_tables=only_tables,
  436. )
  437. return 0
  438. if __name__ == "__main__":
  439. raise SystemExit(main())