#!/usr/bin/env python3 """将 sx 库 CRM 线索相关表迁入 shanxia2.0。 顺序:crm_clue → crm_clue_follow 用户外键经 user_mapping 转换;附件 OSS ID → 目标 sys_oss 相对 URL。 用法: cd backend venv/bin/python scripts/migrate_crm_clue.py --dry-run --env-file .env.production venv/bin/python scripts/migrate_crm_clue.py --env-file .env.production """ from __future__ import annotations import argparse import csv import os import sys from dataclasses import dataclass, field from datetime import datetime from pathlib import Path from typing import Any, Dict, List, Optional, Tuple from urllib.parse import urlparse, urlunparse from sqlalchemy import create_engine, text from sqlalchemy.engine import Engine BACKEND_ROOT = Path(__file__).resolve().parents[1] MIGRATION_DIR = BACKEND_ROOT / "scripts" / "migration" if str(BACKEND_ROOT) not in sys.path: sys.path.insert(0, str(BACKEND_ROOT)) if str(MIGRATION_DIR) not in sys.path: sys.path.insert(0, str(MIGRATION_DIR)) from minio_url import resolve_oss_id_csv # noqa: E402 DEFAULT_TENANT_NO = "shanxia2.0" CRM_ADMIN_SOURCE_USER_ID = 1 CUSTOMER_TYPE_MAP = { "company": "company", "person": "person", "未分类": None, "a类国央企单位": "A类国央企业", "A类国央企单位": "A类国央企业", "A类国央企业": "A类国央企业", "b类股份制企业": "B类股份制企业", "B类股份制企业": "B类股份制企业", "c类私营单位": "C类私营企业", "C类私营企业": "C类私营企业", "d外商投资企业": "D外商投资企业", "D外商投资企业": "D外商投资企业", "e类国资委企业": "5", "5": "5", } FOLLOW_TYPE_MAP = { "电话": "phone", "phone": "phone", "微信": "wechat", "wechat": "wechat", "邮件": "email", "email": "email", "拜访": "visit", "visit": "visit", "其他": "other", "other": "other", } MIGRATION_STEPS = ( ("crm_clue", "clue"), ("crm_clue_follow", "clue_follow"), ) @dataclass class StepStats: source_count: int = 0 inserted: int = 0 updated: int = 0 skipped: int = 0 @dataclass class MigrationStats: steps: Dict[str, StepStats] = field(default_factory=dict) warnings: List[str] = field(default_factory=list) def step(self, name: str) -> StepStats: if name not in self.steps: self.steps[name] = StepStats() return self.steps[name] def legacy_id_to_str(legacy_id: Any) -> Optional[str]: if legacy_id is None or str(legacy_id).strip() == "": return None try: return str(int(legacy_id)) except (TypeError, ValueError): return str(legacy_id).strip() def derive_source_url(target_url: str, source_db: str = "sx") -> str: return urlunparse(urlparse(target_url)._replace(path=f"/{source_db}")) def load_settings_env(env_file: Optional[str]) -> None: if env_file: os.environ["ENV_FILE"] = env_file from dotenv import load_dotenv candidates: List[Path] = [] if env_file: p = Path(env_file) candidates.append(p if p.is_absolute() else BACKEND_ROOT / p) candidates.extend([BACKEND_ROOT / ".env.production", BACKEND_ROOT / ".env"]) for path in candidates: if path.is_file(): load_dotenv(path, override=True) break def load_runtime_settings(): from app.core.config import Settings return Settings() def load_user_mapping(path: Path) -> Tuple[Dict[int, str], Optional[str]]: crm_map: Dict[int, str] = {} admin_id: Optional[str] = None with path.open(encoding="utf-8-sig", newline="") as f: for row in csv.DictReader(f): new_id = (row.get("new_user_id") or "").strip() user_no = (row.get("user_no") or "").strip() crm_raw = (row.get("crm_user_id") or "").strip() if user_no == "admin" and new_id: admin_id = new_id if crm_raw and new_id: try: crm_map[int(crm_raw)] = new_id except ValueError: pass return crm_map, admin_id def fetch_portal_admin_id(target_engine: Engine) -> Optional[str]: with target_engine.connect() as conn: row = conn.execute( text("SELECT id FROM sys_user WHERE user_no='admin' AND del_flag=0 LIMIT 1") ).first() return str(row[0]) if row and row[0] else None def resolve_portal_user_id( source_user_id: Any, crm_user_map: Dict[int, str], admin_id: Optional[str], stats: MigrationStats, label: str, ) -> Optional[str]: if source_user_id is None or str(source_user_id).strip() == "": return None try: uid = int(source_user_id) except (TypeError, ValueError): stats.warnings.append(f"{label}: 非法用户 id {source_user_id!r}") return None if uid == CRM_ADMIN_SOURCE_USER_ID: return admin_id mapped = crm_user_map.get(uid) if not mapped: stats.warnings.append(f"{label}: crm_user_id={uid} 无映射") return mapped def load_oss_id_to_url(target_engine: Engine, tenant_no: str) -> Dict[str, str]: with target_engine.connect() as conn: rows = conn.execute( text("SELECT id, url FROM sys_oss WHERE tenant_no=:t AND del_flag=0"), {"t": tenant_no}, ).mappings().all() return {str(r["id"]): (r["url"] or "").strip() for r in rows if r["id"]} def normalize_customer_type(raw: Any, stats: MigrationStats, label: str) -> Optional[str]: value = (str(raw).strip() if raw is not None else "") or "" if not value: return None if value in CUSTOMER_TYPE_MAP: mapped = CUSTOMER_TYPE_MAP[value] if mapped is None: stats.warnings.append(f"{label}: customer_type={value!r} 已置空") return mapped lowered = value.lower() for key, mapped in CUSTOMER_TYPE_MAP.items(): if key.lower() == lowered: return mapped stats.warnings.append(f"{label}: customer_type={value!r} 未识别,已置空") return None def normalize_follow_type(raw: Any) -> str: value = (str(raw).strip() if raw is not None else "") or "other" return FOLLOW_TYPE_MAP.get(value, FOLLOW_TYPE_MAP.get(value.lower(), "other")) def _str_or_none(value: Any, max_len: int = 0) -> Optional[str]: if value is None: return None s = str(value).strip() if not s: return None return s[:max_len] if max_len else s def fetch_source_rows(engine: Engine, table: str, include_deleted: bool) -> List[dict]: where = "" if include_deleted else "WHERE del_flag = 0" sql = f"SELECT * FROM `{table}` {where} ORDER BY id ASC" with engine.connect() as conn: return [dict(r._mapping) for r in conn.execute(text(sql))] def target_row_exists(conn, table: str, row_id: str) -> bool: return int(conn.execute(text(f"SELECT COUNT(*) FROM `{table}` WHERE id=:id"), {"id": row_id}).scalar_one()) > 0 def transform_clue( row: dict, tenant_no: str, crm_user_map: Dict[int, str], admin_id: Optional[str], stats: MigrationStats, ) -> dict: rid = legacy_id_to_str(row["id"]) label = f"clue#{rid}" def map_user(field_val: Any) -> Optional[str]: return resolve_portal_user_id(field_val, crm_user_map, admin_id, stats, label) return { "id": rid, "clue_name": (row.get("clue_name") or "")[:100], "mobile": (row.get("mobile") or "")[:20], "company": _str_or_none(row.get("company"), 200), "customer_type": normalize_customer_type(row.get("customer_type"), stats, label), "telephone": _str_or_none(row.get("telephone"), 30), "email": _str_or_none(row.get("email"), 100), "title": _str_or_none(row.get("title"), 10), "position": _str_or_none(row.get("position"), 50), "source": (row.get("source") or "")[:20], "level": (row.get("level") or "unrated")[:10], "industry": _str_or_none(row.get("industry"), 50), "park_area": _str_or_none(row.get("park_area"), 100), "province": _str_or_none(row.get("province"), 50), "city": _str_or_none(row.get("city"), 50), "district": _str_or_none(row.get("district"), 50), "address": _str_or_none(row.get("address"), 255), "website": _str_or_none(row.get("website"), 500), "intent_products": _str_or_none(row.get("intent_products"), 500), "expect_time": row.get("expect_time"), "budget": _str_or_none(row.get("budget"), 20), "requirement": row.get("requirement"), "status": (row.get("status") or "new")[:20], "owner_user_id": map_user(row.get("owner_user_id")), "owner_user_name": _str_or_none(row.get("owner_user_name"), 50), "last_time": row.get("last_time"), "next_time": row.get("next_time"), "follow_count": int(row.get("follow_count") or 0), "is_converted": int(row.get("is_converted") or 0), "converted_time": row.get("converted_time"), "customer_id": legacy_id_to_str(row.get("customer_id")), "converted_by": map_user(row.get("converted_by")), "assign_time": row.get("assign_time"), "assign_by": map_user(row.get("assign_by")), "tenant_no": tenant_no, "order_num": 0, "remark": _str_or_none(row.get("remark"), 500), "create_by": map_user(row.get("create_by")), "create_dept_id": "", "create_time": row.get("create_time") or datetime.now(), "update_by": map_user(row.get("update_by")), "update_time": row.get("update_time") or row.get("create_time") or datetime.now(), "del_flag": int(row.get("del_flag") or 0), } def transform_clue_follow( row: dict, tenant_no: str, crm_user_map: Dict[int, str], admin_id: Optional[str], oss_map: Dict[str, str], stats: MigrationStats, ) -> dict: rid = legacy_id_to_str(row["id"]) label = f"clue_follow#{rid}" owner_id = resolve_portal_user_id(row.get("create_by"), crm_user_map, admin_id, stats, label) return { "id": rid, "clue_id": legacy_id_to_str(row.get("clue_id")), "clue_name": _str_or_none(row.get("clue_name"), 100), "follow_type": normalize_follow_type(row.get("follow_type")), "follow_content": row.get("follow_content") or "", "next_time": row.get("next_time"), "attachments": resolve_oss_id_csv(row.get("attachments"), oss_map) or None, "create_by_name": _str_or_none(row.get("create_by_name"), 50), "tenant_no": tenant_no, "order_num": 0, "remark": _str_or_none(row.get("remark"), 500), "create_by": owner_id, "create_dept_id": "", "create_time": row.get("create_time") or datetime.now(), "update_by": resolve_portal_user_id(row.get("update_by"), crm_user_map, admin_id, stats, label), "update_time": row.get("update_time") or row.get("create_time") or datetime.now(), "del_flag": int(row.get("del_flag") or 0), } INSERT_CLUE_SQL = text( """ INSERT INTO crm_clue ( id, clue_name, mobile, company, customer_type, telephone, email, title, position, source, level, industry, park_area, province, city, district, address, website, intent_products, expect_time, budget, requirement, status, owner_user_id, owner_user_name, last_time, next_time, follow_count, is_converted, converted_time, customer_id, converted_by, assign_time, assign_by, tenant_no, order_num, remark, create_by, create_dept_id, create_time, update_by, update_time, del_flag ) VALUES ( :id, :clue_name, :mobile, :company, :customer_type, :telephone, :email, :title, :position, :source, :level, :industry, :park_area, :province, :city, :district, :address, :website, :intent_products, :expect_time, :budget, :requirement, :status, :owner_user_id, :owner_user_name, :last_time, :next_time, :follow_count, :is_converted, :converted_time, :customer_id, :converted_by, :assign_time, :assign_by, :tenant_no, :order_num, :remark, :create_by, :create_dept_id, :create_time, :update_by, :update_time, :del_flag ) """ ) INSERT_CLUE_FOLLOW_SQL = text( """ INSERT INTO crm_clue_follow ( id, clue_id, clue_name, follow_type, follow_content, next_time, attachments, create_by_name, tenant_no, order_num, remark, create_by, create_dept_id, create_time, update_by, update_time, del_flag ) VALUES ( :id, :clue_id, :clue_name, :follow_type, :follow_content, :next_time, :attachments, :create_by_name, :tenant_no, :order_num, :remark, :create_by, :create_dept_id, :create_time, :update_by, :update_time, :del_flag ) """ ) STEP_INSERT_SQL = { "crm_clue": INSERT_CLUE_SQL, "crm_clue_follow": INSERT_CLUE_FOLLOW_SQL, } def write_mapping_csv(source_rows: List[dict], path: Path) -> None: path.parent.mkdir(parents=True, exist_ok=True) migrated_at = datetime.now().strftime("%Y-%m-%d %H:%M:%S") with path.open("w", encoding="utf-8", newline="") as f: w = csv.DictWriter(f, fieldnames=["source_id", "new_id", "migrated_at"]) w.writeheader() for row in source_rows: sid = legacy_id_to_str(row["id"]) w.writerow({"source_id": sid, "new_id": sid, "migrated_at": migrated_at}) def migrate_table( source_engine: Engine, target_engine: Engine, table: str, *, tenant_no: str, crm_user_map: Dict[int, str], admin_id: Optional[str], oss_map: Dict[str, str], stats: MigrationStats, dry_run: bool, update_existing: bool, include_deleted: bool, ) -> List[dict]: step = stats.step(table) source_rows = fetch_source_rows(source_engine, table, include_deleted) step.source_count = len(source_rows) transformers = { "crm_clue": lambda r: transform_clue(r, tenant_no, crm_user_map, admin_id, stats), "crm_clue_follow": lambda r: transform_clue_follow( r, tenant_no, crm_user_map, admin_id, oss_map, stats ), } payloads = [transformers[table](r) for r in source_rows] if dry_run: step.inserted = len(payloads) return source_rows insert_sql = STEP_INSERT_SQL[table] with target_engine.begin() as conn: for payload in payloads: rid = payload["id"] if target_row_exists(conn, table, rid): if update_existing: step.skipped += 1 else: step.skipped += 1 else: conn.execute(insert_sql, payload) step.inserted += 1 return source_rows def print_report(stats: MigrationStats, dry_run: bool) -> None: mode = "DRY-RUN" if dry_run else "COMMITTED" print(f"\n=== CRM 线索表迁移 [{mode}] ===") for table, _ in MIGRATION_STEPS: s = stats.step(table) print(f"{table}: 源={s.source_count} 插入={s.inserted} 跳过={s.skipped}") if stats.warnings: print(f"警告 ({len(stats.warnings)}):") for w in stats.warnings[:20]: print(f" - {w}") if len(stats.warnings) > 20: print(f" ... 另有 {len(stats.warnings) - 20} 条") def run_migration( source_engine: Engine, target_engine: Engine, *, tenant_no: str, user_mapping_path: Path, mapping_dir: Path, dry_run: bool, update_existing: bool, include_deleted: bool, only_tables: Optional[List[str]], ) -> MigrationStats: stats = MigrationStats() crm_user_map, admin_id = load_user_mapping(user_mapping_path) if not admin_id: admin_id = fetch_portal_admin_id(target_engine) oss_map = load_oss_id_to_url(target_engine, tenant_no) print(f"sys_oss 映射条数: {len(oss_map)}") selected = [t for t, _ in MIGRATION_STEPS if not only_tables or t in only_tables] for table in selected: print(f"\n>> 迁移 {table} ...") source_rows = migrate_table( source_engine, target_engine, table, tenant_no=tenant_no, crm_user_map=crm_user_map, admin_id=admin_id, oss_map=oss_map, stats=stats, dry_run=dry_run, update_existing=update_existing, include_deleted=include_deleted, ) if table == "crm_clue" and not dry_run: write_mapping_csv(source_rows, mapping_dir / "crm_clue_id_mapping.csv") print_report(stats, dry_run) return stats def main() -> int: parser = argparse.ArgumentParser(description="Migrate CRM clue tables from sx to portal") parser.add_argument("--source-url", default="") parser.add_argument("--target-url", default="") parser.add_argument("--tenant-no", default=DEFAULT_TENANT_NO) parser.add_argument( "--user-mapping", default=str(BACKEND_ROOT.parent / "docs/data-migration/mappings/user_mapping_result.csv"), ) parser.add_argument("--dry-run", action="store_true") parser.add_argument("--update", action="store_true") parser.add_argument("--include-deleted", action="store_true") parser.add_argument("--tables", default="", help="逗号分隔,默认全部两表") parser.add_argument("--env-file", default=os.environ.get("ENV_FILE", "")) args = parser.parse_args() load_settings_env(args.env_file or None) settings = load_runtime_settings() target_url = args.target_url or settings.DATABASE_URL source_url = args.source_url or os.environ.get("SX_SOURCE_DATABASE_URL") or derive_source_url(target_url) only_tables = [t.strip() for t in args.tables.split(",") if t.strip()] or None print(f"源库: {urlparse(source_url).path}") print(f"目标库: {urlparse(target_url).path}") run_migration( create_engine(source_url, pool_pre_ping=True), create_engine(target_url, pool_pre_ping=True), tenant_no=args.tenant_no, user_mapping_path=Path(args.user_mapping), mapping_dir=BACKEND_ROOT.parent / "docs/data-migration/mappings", dry_run=args.dry_run, update_existing=args.update, include_deleted=args.include_deleted, only_tables=only_tables, ) return 0 if __name__ == "__main__": raise SystemExit(main())