migrate_crm_opportunity.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606
  1. #!/usr/bin/env python3
  2. """将 sx 库 CRM 商机相关表迁入 shanxia2.0。
  3. 顺序:crm_opportunity → crm_opportunity_follow → crm_opportunity_product → crm_opportunity_stage_log
  4. 用户外键经 user_mapping 转换;附件 OSS ID → 目标 sys_oss 相对 URL;业务 ID 原样 str(id)。
  5. 用法:
  6. cd backend
  7. venv/bin/python scripts/migrate_crm_opportunity.py --dry-run --env-file .env.production
  8. venv/bin/python scripts/migrate_crm_opportunity.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 decimal import Decimal
  18. from pathlib import Path
  19. from typing import Any, Dict, List, Optional, Tuple
  20. from urllib.parse import urlparse, urlunparse
  21. from sqlalchemy import create_engine, text
  22. from sqlalchemy.engine import Engine
  23. BACKEND_ROOT = Path(__file__).resolve().parents[1]
  24. MIGRATION_DIR = BACKEND_ROOT / "scripts" / "migration"
  25. if str(BACKEND_ROOT) not in sys.path:
  26. sys.path.insert(0, str(BACKEND_ROOT))
  27. if str(MIGRATION_DIR) not in sys.path:
  28. sys.path.insert(0, str(MIGRATION_DIR))
  29. from minio_url import resolve_oss_id_csv # noqa: E402
  30. DEFAULT_TENANT_NO = "shanxia2.0"
  31. CRM_ADMIN_SOURCE_USER_ID = 1
  32. FOLLOW_TYPE_MAP = {
  33. "电话": "phone",
  34. "phone": "phone",
  35. "微信": "wechat",
  36. "wechat": "wechat",
  37. "邮件": "email",
  38. "email": "email",
  39. "拜访": "visit",
  40. "visit": "visit",
  41. "会议": "meeting",
  42. "meeting": "meeting",
  43. "其他": "other",
  44. "other": "other",
  45. }
  46. MIGRATION_STEPS = (
  47. ("crm_opportunity", "opportunity"),
  48. ("crm_opportunity_follow", "opportunity_follow"),
  49. ("crm_opportunity_product", "opportunity_product"),
  50. ("crm_opportunity_stage_log", "opportunity_stage_log"),
  51. )
  52. @dataclass
  53. class StepStats:
  54. source_count: int = 0
  55. inserted: int = 0
  56. updated: int = 0
  57. skipped: int = 0
  58. @dataclass
  59. class MigrationStats:
  60. steps: Dict[str, StepStats] = field(default_factory=dict)
  61. warnings: List[str] = field(default_factory=list)
  62. def step(self, name: str) -> StepStats:
  63. if name not in self.steps:
  64. self.steps[name] = StepStats()
  65. return self.steps[name]
  66. def legacy_id_to_str(legacy_id: Any) -> Optional[str]:
  67. if legacy_id is None or str(legacy_id).strip() == "":
  68. return None
  69. try:
  70. return str(int(legacy_id))
  71. except (TypeError, ValueError):
  72. return str(legacy_id).strip()
  73. def derive_source_url(target_url: str, source_db: str = "sx") -> str:
  74. return urlunparse(urlparse(target_url)._replace(path=f"/{source_db}"))
  75. def load_settings_env(env_file: Optional[str]) -> None:
  76. if env_file:
  77. os.environ["ENV_FILE"] = env_file
  78. from dotenv import load_dotenv
  79. candidates: List[Path] = []
  80. if env_file:
  81. p = Path(env_file)
  82. candidates.append(p if p.is_absolute() else BACKEND_ROOT / p)
  83. candidates.extend([BACKEND_ROOT / ".env.production", BACKEND_ROOT / ".env"])
  84. for path in candidates:
  85. if path.is_file():
  86. load_dotenv(path, override=True)
  87. break
  88. def load_runtime_settings():
  89. from app.core.config import Settings
  90. return Settings()
  91. def load_user_mapping(path: Path) -> Tuple[Dict[int, str], Optional[str]]:
  92. crm_map: Dict[int, str] = {}
  93. admin_id: Optional[str] = None
  94. with path.open(encoding="utf-8-sig", newline="") as f:
  95. for row in csv.DictReader(f):
  96. new_id = (row.get("new_user_id") or "").strip()
  97. user_no = (row.get("user_no") or "").strip()
  98. crm_raw = (row.get("crm_user_id") or "").strip()
  99. if user_no == "admin" and new_id:
  100. admin_id = new_id
  101. if crm_raw and new_id:
  102. try:
  103. crm_map[int(crm_raw)] = new_id
  104. except ValueError:
  105. pass
  106. return crm_map, admin_id
  107. def fetch_portal_admin_id(target_engine: Engine) -> Optional[str]:
  108. with target_engine.connect() as conn:
  109. row = conn.execute(
  110. text("SELECT id FROM sys_user WHERE user_no='admin' AND del_flag=0 LIMIT 1")
  111. ).first()
  112. return str(row[0]) if row and row[0] else None
  113. def resolve_portal_user_id(
  114. source_user_id: Any,
  115. crm_user_map: Dict[int, str],
  116. admin_id: Optional[str],
  117. stats: MigrationStats,
  118. label: str,
  119. ) -> Optional[str]:
  120. if source_user_id is None or str(source_user_id).strip() == "":
  121. return None
  122. try:
  123. uid = int(source_user_id)
  124. except (TypeError, ValueError):
  125. stats.warnings.append(f"{label}: 非法用户 id {source_user_id!r}")
  126. return None
  127. if uid == CRM_ADMIN_SOURCE_USER_ID:
  128. return admin_id
  129. mapped = crm_user_map.get(uid)
  130. if not mapped:
  131. stats.warnings.append(f"{label}: crm_user_id={uid} 无映射")
  132. return mapped
  133. def load_oss_id_to_url(target_engine: Engine, tenant_no: str) -> Dict[str, str]:
  134. with target_engine.connect() as conn:
  135. rows = conn.execute(
  136. text("SELECT id, url FROM sys_oss WHERE tenant_no=:t AND del_flag=0"),
  137. {"t": tenant_no},
  138. ).mappings().all()
  139. return {str(r["id"]): (r["url"] or "").strip() for r in rows if r["id"]}
  140. def normalize_follow_type(raw: Any) -> str:
  141. value = (str(raw).strip() if raw is not None else "") or "other"
  142. return FOLLOW_TYPE_MAP.get(value, FOLLOW_TYPE_MAP.get(value.lower(), "other"))
  143. def _dec(value: Any, default: Optional[Decimal] = None) -> Optional[Decimal]:
  144. if value is None or value == "":
  145. return default
  146. return Decimal(str(value))
  147. def _str_or_none(value: Any, max_len: int = 0) -> Optional[str]:
  148. if value is None:
  149. return None
  150. s = str(value).strip()
  151. if not s:
  152. return None
  153. return s[:max_len] if max_len else s
  154. def fetch_source_rows(engine: Engine, table: str, include_deleted: bool) -> List[dict]:
  155. where = "" if include_deleted else "WHERE del_flag = 0"
  156. sql = f"SELECT * FROM `{table}` {where} ORDER BY id ASC"
  157. with engine.connect() as conn:
  158. return [dict(r._mapping) for r in conn.execute(text(sql))]
  159. def target_row_exists(conn, table: str, row_id: str) -> bool:
  160. return int(conn.execute(text(f"SELECT COUNT(*) FROM `{table}` WHERE id=:id"), {"id": row_id}).scalar_one()) > 0
  161. def transform_opportunity(
  162. row: dict,
  163. tenant_no: str,
  164. crm_user_map: Dict[int, str],
  165. admin_id: Optional[str],
  166. stats: MigrationStats,
  167. ) -> dict:
  168. rid = legacy_id_to_str(row["id"])
  169. label = f"opportunity#{rid}"
  170. def map_user(field_val: Any) -> Optional[str]:
  171. return resolve_portal_user_id(field_val, crm_user_map, admin_id, stats, label)
  172. return {
  173. "id": rid,
  174. "opportunity_no": (row.get("opportunity_no") or "")[:50],
  175. "opportunity_name": (row.get("opportunity_name") or "")[:200],
  176. "customer_id": legacy_id_to_str(row.get("customer_id")) or "",
  177. "customer_name": _str_or_none(row.get("customer_name"), 200),
  178. "contact_id": legacy_id_to_str(row.get("contact_id")),
  179. "contact_name": _str_or_none(row.get("contact_name"), 50),
  180. "stage": (row.get("stage") or "initial")[:20],
  181. "stage_percent": int(row.get("stage_percent") or 10),
  182. "status": (row.get("status") or "following")[:20],
  183. "win_rate": _dec(row.get("win_rate"), Decimal("50.00")),
  184. "amount": _dec(row.get("amount"), Decimal("0.00")),
  185. "expect_deal_date": row.get("expect_deal_date"),
  186. "actual_deal_date": row.get("actual_deal_date"),
  187. "lost_reason": _str_or_none(row.get("lost_reason"), 500),
  188. "owner_user_id": map_user(row.get("owner_user_id")),
  189. "owner_user_name": _str_or_none(row.get("owner_user_name"), 50),
  190. "product_count": int(row.get("product_count") or 0),
  191. "last_time": row.get("last_time"),
  192. "next_time": row.get("next_time"),
  193. "follow_count": int(row.get("follow_count") or 0),
  194. "contract_id": legacy_id_to_str(row.get("contract_id")),
  195. "source": _str_or_none(row.get("source"), 20),
  196. "type": _str_or_none(row.get("type"), 20),
  197. "description": row.get("description"),
  198. "competitors": _str_or_none(row.get("competitors"), 500),
  199. "key_factors": _str_or_none(row.get("key_factors"), 500),
  200. "tenant_no": tenant_no,
  201. "order_num": 0,
  202. "remark": _str_or_none(row.get("remark"), 512),
  203. "create_by": map_user(row.get("create_by")),
  204. "create_dept_id": "",
  205. "create_time": row.get("create_time") or datetime.now(),
  206. "update_by": map_user(row.get("update_by")),
  207. "update_time": row.get("update_time") or row.get("create_time") or datetime.now(),
  208. "del_flag": int(row.get("del_flag") or 0),
  209. }
  210. def transform_opportunity_follow(
  211. row: dict,
  212. tenant_no: str,
  213. crm_user_map: Dict[int, str],
  214. admin_id: Optional[str],
  215. oss_map: Dict[str, str],
  216. stats: MigrationStats,
  217. ) -> dict:
  218. rid = legacy_id_to_str(row["id"])
  219. label = f"opportunity_follow#{rid}"
  220. owner_id = resolve_portal_user_id(row.get("create_by"), crm_user_map, admin_id, stats, label)
  221. follow_by = resolve_portal_user_id(row.get("follow_by"), crm_user_map, admin_id, stats, label)
  222. return {
  223. "id": rid,
  224. "opportunity_id": legacy_id_to_str(row.get("opportunity_id")) or "",
  225. "follow_type": normalize_follow_type(row.get("follow_type")),
  226. "follow_content": row.get("follow_content") or "",
  227. "follow_time": row.get("follow_time") or row.get("create_time"),
  228. "stage": _str_or_none(row.get("stage"), 20),
  229. "stage_percent": int(row["stage_percent"]) if row.get("stage_percent") is not None else None,
  230. "next_time": row.get("next_time"),
  231. "next_content": _str_or_none(row.get("next_content"), 500),
  232. "attachments": resolve_oss_id_csv(row.get("attachments"), oss_map) or None,
  233. "contact_id": legacy_id_to_str(row.get("contact_id")),
  234. "contact_name": _str_or_none(row.get("contact_name"), 50),
  235. "location": _str_or_none(row.get("location"), 200),
  236. "duration": int(row["duration"]) if row.get("duration") is not None else None,
  237. "follow_by": follow_by or owner_id,
  238. "tenant_no": tenant_no,
  239. "order_num": 0,
  240. "remark": _str_or_none(row.get("remark"), 500),
  241. "create_by": owner_id,
  242. "create_dept_id": "",
  243. "create_time": row.get("create_time") or datetime.now(),
  244. "update_by": resolve_portal_user_id(row.get("update_by"), crm_user_map, admin_id, stats, label),
  245. "update_time": row.get("update_time") or row.get("create_time") or datetime.now(),
  246. "del_flag": int(row.get("del_flag") or 0),
  247. }
  248. def transform_opportunity_product(
  249. row: dict,
  250. tenant_no: str,
  251. crm_user_map: Dict[int, str],
  252. admin_id: Optional[str],
  253. stats: MigrationStats,
  254. ) -> dict:
  255. rid = legacy_id_to_str(row["id"])
  256. label = f"opportunity_product#{rid}"
  257. def map_user(field_val: Any) -> Optional[str]:
  258. return resolve_portal_user_id(field_val, crm_user_map, admin_id, stats, label)
  259. return {
  260. "id": rid,
  261. "opportunity_id": legacy_id_to_str(row.get("opportunity_id")) or "",
  262. "product_id": legacy_id_to_str(row.get("product_id")) or "",
  263. "product_name": _str_or_none(row.get("product_name"), 200),
  264. "product_no": _str_or_none(row.get("product_no"), 50),
  265. "category_id": legacy_id_to_str(row.get("category_id")),
  266. "category_name": _str_or_none(row.get("category_name"), 100),
  267. "model": _str_or_none(row.get("model"), 100),
  268. "unit": (row.get("unit") or "件")[:20],
  269. "quantity": _dec(row.get("quantity"), Decimal("0")),
  270. "price": _dec(row.get("price"), Decimal("0.00")),
  271. "discount": _dec(row.get("discount"), Decimal("0.00")),
  272. "subtotal": _dec(row.get("subtotal"), Decimal("0.00")),
  273. "sort": int(row.get("sort") or 0),
  274. "tenant_no": tenant_no,
  275. "order_num": 0,
  276. "remark": _str_or_none(row.get("remark"), 500),
  277. "create_by": map_user(row.get("create_by")),
  278. "create_dept_id": "",
  279. "create_time": row.get("create_time") or datetime.now(),
  280. "update_by": map_user(row.get("update_by")),
  281. "update_time": row.get("update_time") or row.get("create_time") or datetime.now(),
  282. "del_flag": int(row.get("del_flag") or 0),
  283. }
  284. def transform_opportunity_stage_log(
  285. row: dict,
  286. tenant_no: str,
  287. crm_user_map: Dict[int, str],
  288. admin_id: Optional[str],
  289. stats: MigrationStats,
  290. ) -> dict:
  291. rid = legacy_id_to_str(row["id"])
  292. label = f"opportunity_stage_log#{rid}"
  293. def map_user(field_val: Any) -> Optional[str]:
  294. return resolve_portal_user_id(field_val, crm_user_map, admin_id, stats, label)
  295. return {
  296. "id": rid,
  297. "opportunity_id": legacy_id_to_str(row.get("opportunity_id")) or "",
  298. "from_stage": _str_or_none(row.get("from_stage"), 20),
  299. "from_stage_name": _str_or_none(row.get("from_stage_name"), 50),
  300. "from_percent": int(row["from_percent"]) if row.get("from_percent") is not None else None,
  301. "to_stage": (row.get("to_stage") or "")[:20],
  302. "to_stage_name": _str_or_none(row.get("to_stage_name"), 50),
  303. "to_percent": int(row["to_percent"]) if row.get("to_percent") is not None else None,
  304. "change_type": (row.get("change_type") or "forward")[:20],
  305. "change_reason": _str_or_none(row.get("change_reason"), 500),
  306. "change_amount": _dec(row.get("change_amount")),
  307. "lost_detail": _str_or_none(row.get("lost_detail"), 2000),
  308. "competitor_info": _str_or_none(row.get("competitor_info"), 1000),
  309. "improvement": _str_or_none(row.get("improvement"), 1000),
  310. "won_remark": _str_or_none(row.get("won_remark"), 2000),
  311. "tenant_no": tenant_no,
  312. "order_num": 0,
  313. "remark": _str_or_none(row.get("remark"), 500),
  314. "create_by": map_user(row.get("create_by")),
  315. "create_dept_id": "",
  316. "create_time": row.get("create_time") or datetime.now(),
  317. "update_by": map_user(row.get("update_by")),
  318. "update_time": row.get("update_time") or row.get("create_time") or datetime.now(),
  319. "del_flag": int(row.get("del_flag") or 0),
  320. }
  321. INSERT_OPPORTUNITY_SQL = text(
  322. """
  323. INSERT INTO crm_opportunity (
  324. id, opportunity_no, opportunity_name, customer_id, customer_name, contact_id, contact_name,
  325. stage, stage_percent, status, win_rate, amount, expect_deal_date, actual_deal_date, lost_reason,
  326. owner_user_id, owner_user_name, product_count, last_time, next_time, follow_count, contract_id,
  327. source, type, description, competitors, key_factors,
  328. tenant_no, order_num, remark, create_by, create_dept_id, create_time, update_by, update_time, del_flag
  329. ) VALUES (
  330. :id, :opportunity_no, :opportunity_name, :customer_id, :customer_name, :contact_id, :contact_name,
  331. :stage, :stage_percent, :status, :win_rate, :amount, :expect_deal_date, :actual_deal_date, :lost_reason,
  332. :owner_user_id, :owner_user_name, :product_count, :last_time, :next_time, :follow_count, :contract_id,
  333. :source, :type, :description, :competitors, :key_factors,
  334. :tenant_no, :order_num, :remark, :create_by, :create_dept_id, :create_time, :update_by, :update_time, :del_flag
  335. )
  336. """
  337. )
  338. INSERT_OPPORTUNITY_FOLLOW_SQL = text(
  339. """
  340. INSERT INTO crm_opportunity_follow (
  341. id, opportunity_id, follow_type, follow_content, follow_time, stage, stage_percent,
  342. next_time, next_content, attachments, contact_id, contact_name, location, duration, follow_by,
  343. tenant_no, order_num, remark, create_by, create_dept_id, create_time, update_by, update_time, del_flag
  344. ) VALUES (
  345. :id, :opportunity_id, :follow_type, :follow_content, :follow_time, :stage, :stage_percent,
  346. :next_time, :next_content, :attachments, :contact_id, :contact_name, :location, :duration, :follow_by,
  347. :tenant_no, :order_num, :remark, :create_by, :create_dept_id, :create_time, :update_by, :update_time, :del_flag
  348. )
  349. """
  350. )
  351. INSERT_OPPORTUNITY_PRODUCT_SQL = text(
  352. """
  353. INSERT INTO crm_opportunity_product (
  354. id, opportunity_id, product_id, product_name, product_no, category_id, category_name,
  355. model, unit, quantity, price, discount, subtotal, sort,
  356. tenant_no, order_num, remark, create_by, create_dept_id, create_time, update_by, update_time, del_flag
  357. ) VALUES (
  358. :id, :opportunity_id, :product_id, :product_name, :product_no, :category_id, :category_name,
  359. :model, :unit, :quantity, :price, :discount, :subtotal, :sort,
  360. :tenant_no, :order_num, :remark, :create_by, :create_dept_id, :create_time, :update_by, :update_time, :del_flag
  361. )
  362. """
  363. )
  364. INSERT_OPPORTUNITY_STAGE_LOG_SQL = text(
  365. """
  366. INSERT INTO crm_opportunity_stage_log (
  367. id, opportunity_id, from_stage, from_stage_name, from_percent, to_stage, to_stage_name, to_percent,
  368. change_type, change_reason, change_amount, lost_detail, competitor_info, improvement, won_remark,
  369. tenant_no, order_num, remark, create_by, create_dept_id, create_time, update_by, update_time, del_flag
  370. ) VALUES (
  371. :id, :opportunity_id, :from_stage, :from_stage_name, :from_percent, :to_stage, :to_stage_name, :to_percent,
  372. :change_type, :change_reason, :change_amount, :lost_detail, :competitor_info, :improvement, :won_remark,
  373. :tenant_no, :order_num, :remark, :create_by, :create_dept_id, :create_time, :update_by, :update_time, :del_flag
  374. )
  375. """
  376. )
  377. STEP_INSERT_SQL = {
  378. "crm_opportunity": INSERT_OPPORTUNITY_SQL,
  379. "crm_opportunity_follow": INSERT_OPPORTUNITY_FOLLOW_SQL,
  380. "crm_opportunity_product": INSERT_OPPORTUNITY_PRODUCT_SQL,
  381. "crm_opportunity_stage_log": INSERT_OPPORTUNITY_STAGE_LOG_SQL,
  382. }
  383. def write_mapping_csv(source_rows: List[dict], path: Path) -> None:
  384. path.parent.mkdir(parents=True, exist_ok=True)
  385. migrated_at = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
  386. with path.open("w", encoding="utf-8", newline="") as f:
  387. w = csv.DictWriter(f, fieldnames=["source_id", "new_id", "migrated_at"])
  388. w.writeheader()
  389. for row in source_rows:
  390. sid = legacy_id_to_str(row["id"])
  391. w.writerow({"source_id": sid, "new_id": sid, "migrated_at": migrated_at})
  392. def migrate_table(
  393. source_engine: Engine,
  394. target_engine: Engine,
  395. table: str,
  396. *,
  397. tenant_no: str,
  398. crm_user_map: Dict[int, str],
  399. admin_id: Optional[str],
  400. oss_map: Dict[str, str],
  401. stats: MigrationStats,
  402. dry_run: bool,
  403. update_existing: bool,
  404. include_deleted: bool,
  405. ) -> List[dict]:
  406. step = stats.step(table)
  407. source_rows = fetch_source_rows(source_engine, table, include_deleted)
  408. step.source_count = len(source_rows)
  409. transformers = {
  410. "crm_opportunity": lambda r: transform_opportunity(r, tenant_no, crm_user_map, admin_id, stats),
  411. "crm_opportunity_follow": lambda r: transform_opportunity_follow(
  412. r, tenant_no, crm_user_map, admin_id, oss_map, stats
  413. ),
  414. "crm_opportunity_product": lambda r: transform_opportunity_product(
  415. r, tenant_no, crm_user_map, admin_id, stats
  416. ),
  417. "crm_opportunity_stage_log": lambda r: transform_opportunity_stage_log(
  418. r, tenant_no, crm_user_map, admin_id, stats
  419. ),
  420. }
  421. payloads = [transformers[table](r) for r in source_rows]
  422. if dry_run:
  423. step.inserted = len(payloads)
  424. return source_rows
  425. insert_sql = STEP_INSERT_SQL[table]
  426. with target_engine.begin() as conn:
  427. for payload in payloads:
  428. rid = payload["id"]
  429. if target_row_exists(conn, table, rid):
  430. if update_existing:
  431. step.skipped += 1
  432. else:
  433. step.skipped += 1
  434. else:
  435. conn.execute(insert_sql, payload)
  436. step.inserted += 1
  437. return source_rows
  438. def print_report(stats: MigrationStats, dry_run: bool) -> None:
  439. mode = "DRY-RUN" if dry_run else "COMMITTED"
  440. print(f"\n=== CRM 商机四表迁移 [{mode}] ===")
  441. for table, _ in MIGRATION_STEPS:
  442. s = stats.step(table)
  443. print(f"{table}: 源={s.source_count} 插入={s.inserted} 跳过={s.skipped}")
  444. if stats.warnings:
  445. print(f"警告 ({len(stats.warnings)}):")
  446. for w in stats.warnings[:20]:
  447. print(f" - {w}")
  448. if len(stats.warnings) > 20:
  449. print(f" ... 另有 {len(stats.warnings) - 20} 条")
  450. def run_migration(
  451. source_engine: Engine,
  452. target_engine: Engine,
  453. *,
  454. tenant_no: str,
  455. user_mapping_path: Path,
  456. mapping_dir: Path,
  457. dry_run: bool,
  458. update_existing: bool,
  459. include_deleted: bool,
  460. only_tables: Optional[List[str]],
  461. ) -> MigrationStats:
  462. stats = MigrationStats()
  463. crm_user_map, admin_id = load_user_mapping(user_mapping_path)
  464. if not admin_id:
  465. admin_id = fetch_portal_admin_id(target_engine)
  466. oss_map = load_oss_id_to_url(target_engine, tenant_no)
  467. print(f"sys_oss 映射条数: {len(oss_map)}")
  468. selected = [t for t, _ in MIGRATION_STEPS if not only_tables or t in only_tables]
  469. for table in selected:
  470. print(f"\n>> 迁移 {table} ...")
  471. source_rows = migrate_table(
  472. source_engine,
  473. target_engine,
  474. table,
  475. tenant_no=tenant_no,
  476. crm_user_map=crm_user_map,
  477. admin_id=admin_id,
  478. oss_map=oss_map,
  479. stats=stats,
  480. dry_run=dry_run,
  481. update_existing=update_existing,
  482. include_deleted=include_deleted,
  483. )
  484. if table == "crm_opportunity" and not dry_run:
  485. write_mapping_csv(source_rows, mapping_dir / "crm_opportunity_id_mapping.csv")
  486. print_report(stats, dry_run)
  487. return stats
  488. def main() -> int:
  489. parser = argparse.ArgumentParser(description="Migrate CRM opportunity tables from sx to portal")
  490. parser.add_argument("--source-url", default="")
  491. parser.add_argument("--target-url", default="")
  492. parser.add_argument("--tenant-no", default=DEFAULT_TENANT_NO)
  493. parser.add_argument(
  494. "--user-mapping",
  495. default=str(BACKEND_ROOT.parent / "docs/data-migration/mappings/user_mapping_result.csv"),
  496. )
  497. parser.add_argument("--dry-run", action="store_true")
  498. parser.add_argument("--update", action="store_true")
  499. parser.add_argument("--include-deleted", action="store_true")
  500. parser.add_argument("--tables", default="", help="逗号分隔,默认全部四表")
  501. parser.add_argument("--env-file", default=os.environ.get("ENV_FILE", ""))
  502. args = parser.parse_args()
  503. load_settings_env(args.env_file or None)
  504. settings = load_runtime_settings()
  505. target_url = args.target_url or settings.DATABASE_URL
  506. source_url = args.source_url or os.environ.get("SX_SOURCE_DATABASE_URL") or derive_source_url(target_url)
  507. only_tables = [t.strip() for t in args.tables.split(",") if t.strip()] or None
  508. print(f"源库: {urlparse(source_url).path}")
  509. print(f"目标库: {urlparse(target_url).path}")
  510. run_migration(
  511. create_engine(source_url, pool_pre_ping=True),
  512. create_engine(target_url, pool_pre_ping=True),
  513. tenant_no=args.tenant_no,
  514. user_mapping_path=Path(args.user_mapping),
  515. mapping_dir=BACKEND_ROOT.parent / "docs/data-migration/mappings",
  516. dry_run=args.dry_run,
  517. update_existing=args.update,
  518. include_deleted=args.include_deleted,
  519. only_tables=only_tables,
  520. )
  521. return 0
  522. if __name__ == "__main__":
  523. raise SystemExit(main())