migrate_crm_contract.py 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840
  1. #!/usr/bin/env python3
  2. """将 sx 库 CRM 合同相关表迁入 shanxia2.0。
  3. 顺序:crm_contract_template → crm_contract → crm_contract_product →
  4. crm_contract_product_price_tier → crm_contract_approval → crm_contract_change
  5. 用户外键经 user_mapping;附件 OSS ID / URL 规范化;attachment_files JSON 保留 ossId。
  6. 用法:
  7. cd backend
  8. venv/bin/python scripts/migrate_crm_contract.py --dry-run --env-file .env.production
  9. venv/bin/python scripts/migrate_crm_contract.py --env-file .env.production
  10. """
  11. from __future__ import annotations
  12. import argparse
  13. import csv
  14. import json
  15. import os
  16. import sys
  17. from dataclasses import dataclass, field
  18. from datetime import datetime
  19. from decimal import Decimal
  20. from pathlib import Path
  21. from typing import Any, Dict, List, Optional, Tuple
  22. from urllib.parse import urlparse, urlunparse
  23. from sqlalchemy import create_engine, text
  24. from sqlalchemy.engine import Engine
  25. BACKEND_ROOT = Path(__file__).resolve().parents[1]
  26. MIGRATION_DIR = BACKEND_ROOT / "scripts" / "migration"
  27. if str(BACKEND_ROOT) not in sys.path:
  28. sys.path.insert(0, str(BACKEND_ROOT))
  29. if str(MIGRATION_DIR) not in sys.path:
  30. sys.path.insert(0, str(MIGRATION_DIR))
  31. from minio_url import extract_minio_object_key, join_relative_urls, resolve_oss_id_csv # noqa: E402
  32. DEFAULT_TENANT_NO = "shanxia2.0"
  33. CRM_ADMIN_SOURCE_USER_ID = 1
  34. MIGRATION_STEPS = (
  35. ("crm_contract_template", "contract_template"),
  36. ("crm_contract", "contract"),
  37. ("crm_contract_product", "contract_product"),
  38. ("crm_contract_product_price_tier", "contract_product_price_tier"),
  39. ("crm_contract_approval", "contract_approval"),
  40. ("crm_contract_change", "contract_change"),
  41. )
  42. @dataclass
  43. class StepStats:
  44. source_count: int = 0
  45. inserted: int = 0
  46. updated: int = 0
  47. skipped: int = 0
  48. @dataclass
  49. class MigrationStats:
  50. steps: Dict[str, StepStats] = field(default_factory=dict)
  51. warnings: List[str] = field(default_factory=list)
  52. def step(self, name: str) -> StepStats:
  53. if name not in self.steps:
  54. self.steps[name] = StepStats()
  55. return self.steps[name]
  56. def legacy_id_to_str(legacy_id: Any) -> Optional[str]:
  57. if legacy_id is None or str(legacy_id).strip() == "":
  58. return None
  59. try:
  60. return str(int(legacy_id))
  61. except (TypeError, ValueError):
  62. return str(legacy_id).strip()
  63. def derive_source_url(target_url: str, source_db: str = "sx") -> str:
  64. return urlunparse(urlparse(target_url)._replace(path=f"/{source_db}"))
  65. def load_settings_env(env_file: Optional[str]) -> None:
  66. if env_file:
  67. os.environ["ENV_FILE"] = env_file
  68. from dotenv import load_dotenv
  69. candidates: List[Path] = []
  70. if env_file:
  71. p = Path(env_file)
  72. candidates.append(p if p.is_absolute() else BACKEND_ROOT / p)
  73. candidates.extend([BACKEND_ROOT / ".env.production", BACKEND_ROOT / ".env"])
  74. for path in candidates:
  75. if path.is_file():
  76. load_dotenv(path, override=True)
  77. break
  78. def load_runtime_settings():
  79. from app.core.config import Settings
  80. return Settings()
  81. def load_user_mapping(path: Path) -> Tuple[Dict[int, str], Optional[str]]:
  82. crm_map: Dict[int, str] = {}
  83. admin_id: Optional[str] = None
  84. with path.open(encoding="utf-8-sig", newline="") as f:
  85. for row in csv.DictReader(f):
  86. new_id = (row.get("new_user_id") or "").strip()
  87. user_no = (row.get("user_no") or "").strip()
  88. crm_raw = (row.get("crm_user_id") or "").strip()
  89. if user_no == "admin" and new_id:
  90. admin_id = new_id
  91. if crm_raw and new_id:
  92. try:
  93. crm_map[int(crm_raw)] = new_id
  94. except ValueError:
  95. pass
  96. return crm_map, admin_id
  97. def fetch_portal_admin_id(target_engine: Engine) -> Optional[str]:
  98. with target_engine.connect() as conn:
  99. row = conn.execute(
  100. text("SELECT id FROM sys_user WHERE user_no='admin' AND del_flag=0 LIMIT 1")
  101. ).first()
  102. return str(row[0]) if row and row[0] else None
  103. def resolve_portal_user_id(
  104. source_user_id: Any,
  105. crm_user_map: Dict[int, str],
  106. admin_id: Optional[str],
  107. stats: MigrationStats,
  108. label: str,
  109. *,
  110. required: bool = False,
  111. ) -> Optional[str]:
  112. if source_user_id is None or str(source_user_id).strip() == "":
  113. return admin_id if required else None
  114. try:
  115. uid = int(source_user_id)
  116. except (TypeError, ValueError):
  117. stats.warnings.append(f"{label}: 非法用户 id {source_user_id!r}")
  118. return admin_id if required else None
  119. if uid == CRM_ADMIN_SOURCE_USER_ID:
  120. return admin_id
  121. mapped = crm_user_map.get(uid)
  122. if not mapped:
  123. stats.warnings.append(f"{label}: crm_user_id={uid} 无映射")
  124. return admin_id if required else None
  125. return mapped
  126. def load_oss_id_to_url(target_engine: Engine, tenant_no: str) -> Dict[str, str]:
  127. with target_engine.connect() as conn:
  128. rows = conn.execute(
  129. text("SELECT id, url FROM sys_oss WHERE tenant_no=:t AND del_flag=0"),
  130. {"t": tenant_no},
  131. ).mappings().all()
  132. return {str(r["id"]): (r["url"] or "").strip() for r in rows if r["id"]}
  133. def normalize_attachment_csv(raw: Any, oss_map: Dict[str, str]) -> Optional[str]:
  134. if raw is None or str(raw).strip() == "":
  135. return None
  136. oss_resolved = resolve_oss_id_csv(raw, oss_map)
  137. if oss_resolved:
  138. return oss_resolved
  139. parts: List[str] = []
  140. for token in str(raw).split(","):
  141. token = token.strip()
  142. if not token:
  143. continue
  144. if token.isdigit() and token in oss_map:
  145. parts.append(oss_map[token])
  146. else:
  147. key = extract_minio_object_key(token)
  148. if key:
  149. parts.append(key)
  150. joined = join_relative_urls(parts)
  151. return joined or None
  152. def normalize_contract_attachment_files(raw: Any, oss_map: Dict[str, str]) -> Optional[str]:
  153. if raw is None or str(raw).strip() == "":
  154. return None
  155. value = str(raw).strip()
  156. if value.startswith("["):
  157. try:
  158. parsed = json.loads(value)
  159. if isinstance(parsed, list):
  160. out: List[dict] = []
  161. for item in parsed:
  162. if not isinstance(item, dict):
  163. continue
  164. oss_id = legacy_id_to_str(item.get("ossId") or item.get("oss_id"))
  165. if not oss_id:
  166. continue
  167. out.append({"ossId": oss_id, "category": item.get("category") or "other"})
  168. if out:
  169. return json.dumps(out, ensure_ascii=False)
  170. except json.JSONDecodeError:
  171. pass
  172. return normalize_attachment_csv(raw, oss_map)
  173. def normalize_file_path(raw: Any, oss_map: Dict[str, str]) -> Optional[str]:
  174. if raw is None or str(raw).strip() == "":
  175. return None
  176. value = str(raw).strip()
  177. if value.isdigit() and value in oss_map:
  178. return oss_map[value]
  179. key = extract_minio_object_key(value)
  180. return key or None
  181. def _dec(value: Any, default: Optional[Decimal] = None) -> Optional[Decimal]:
  182. if value is None or value == "":
  183. return default
  184. return Decimal(str(value))
  185. def _str_or_none(value: Any, max_len: int = 0) -> Optional[str]:
  186. if value is None:
  187. return None
  188. s = str(value).strip()
  189. if not s:
  190. return None
  191. return s[:max_len] if max_len else s
  192. def fetch_source_rows(engine: Engine, table: str, include_deleted: bool) -> List[dict]:
  193. where = "" if include_deleted else "WHERE del_flag = 0"
  194. sql = f"SELECT * FROM `{table}` {where} ORDER BY id ASC"
  195. with engine.connect() as conn:
  196. return [dict(r._mapping) for r in conn.execute(text(sql))]
  197. def target_row_exists(conn, table: str, row_id: str) -> bool:
  198. return int(conn.execute(text(f"SELECT COUNT(*) FROM `{table}` WHERE id=:id"), {"id": row_id}).scalar_one()) > 0
  199. def transform_contract_template(
  200. row: dict,
  201. tenant_no: str,
  202. crm_user_map: Dict[int, str],
  203. admin_id: Optional[str],
  204. stats: MigrationStats,
  205. ) -> dict:
  206. rid = legacy_id_to_str(row["id"])
  207. label = f"contract_template#{rid}"
  208. def map_user(field_val: Any) -> Optional[str]:
  209. return resolve_portal_user_id(field_val, crm_user_map, admin_id, stats, label)
  210. return {
  211. "id": rid,
  212. "template_no": (row.get("template_no") or "")[:50],
  213. "template_name": (row.get("template_name") or "")[:200],
  214. "contract_type": _str_or_none(row.get("contract_type"), 20),
  215. "template_content": row.get("template_content"),
  216. "payment_terms": row.get("payment_terms"),
  217. "delivery_terms": row.get("delivery_terms"),
  218. "contract_terms": row.get("contract_terms"),
  219. "party_b": _str_or_none(row.get("party_b"), 200),
  220. "party_b_address": _str_or_none(row.get("party_b_address"), 255),
  221. "party_b_contact": _str_or_none(row.get("party_b_contact"), 50),
  222. "party_b_mobile": _str_or_none(row.get("party_b_mobile"), 20),
  223. "default_currency": (row.get("default_currency") or "CNY")[:10],
  224. "default_tax_rate": _dec(row.get("default_tax_rate"), Decimal("6.00")),
  225. "default_period": int(row.get("default_period") or 12),
  226. "is_active": int(row.get("is_active") if row.get("is_active") is not None else 1),
  227. "usage_count": int(row.get("usage_count") or 0),
  228. "sort": int(row.get("sort") or 0),
  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_contract(
  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"contract#{rid}"
  249. def map_user(field_val: Any, *, required: bool = False) -> Optional[str]:
  250. return resolve_portal_user_id(field_val, crm_user_map, admin_id, stats, label, required=required)
  251. owner_id = map_user(row.get("owner_user_id"), required=True)
  252. return {
  253. "id": rid,
  254. "contract_no": (row.get("contract_no") or "")[:50],
  255. "contract_name": (row.get("contract_name") or "")[:200],
  256. "customer_id": legacy_id_to_str(row.get("customer_id")) or "",
  257. "customer_name": _str_or_none(row.get("customer_name"), 200),
  258. "opportunity_id": legacy_id_to_str(row.get("opportunity_id")),
  259. "quote_id": legacy_id_to_str(row.get("quote_id")),
  260. "parent_contract_id": legacy_id_to_str(row.get("parent_contract_id")),
  261. "renewal_count": int(row.get("renewal_count") or 0),
  262. "template_id": legacy_id_to_str(row.get("template_id")),
  263. "contract_template": (row.get("contract_template") or "shanxia")[:50],
  264. "contact_id": legacy_id_to_str(row.get("contact_id")),
  265. "contact_name": _str_or_none(row.get("contact_name"), 50),
  266. "contact_mobile": _str_or_none(row.get("contact_mobile"), 20),
  267. "contract_type": (row.get("contract_type") or "sale")[:20],
  268. "contract_nature": (row.get("contract_nature") or "new")[:20],
  269. "amount": _dec(row.get("amount"), Decimal("0.00")),
  270. "currency": (row.get("currency") or "CNY")[:10],
  271. "tax_rate": _dec(row.get("tax_rate"), Decimal("6.00")),
  272. "amount_with_tax": _dec(row.get("amount_with_tax"), Decimal("0.00")),
  273. "status": (row.get("status") or "draft")[:20],
  274. "performance_status": (row.get("performance_status") or "normal")[:20],
  275. "performance_rate": _dec(row.get("performance_rate"), Decimal("0.00")),
  276. "customer_satisfaction": int(row["customer_satisfaction"]) if row.get("customer_satisfaction") is not None else None,
  277. "approval_status": _str_or_none(row.get("approval_status"), 20),
  278. "approval_flow_id": legacy_id_to_str(row.get("approval_flow_id")),
  279. "contract_file": normalize_file_path(row.get("contract_file"), oss_map),
  280. "attachment_files": normalize_contract_attachment_files(row.get("attachment_files"), oss_map),
  281. "sign_date": row.get("sign_date"),
  282. "actual_sign_date": row.get("actual_sign_date"),
  283. "start_date": row.get("start_date"),
  284. "end_date": row.get("end_date"),
  285. "contract_period": int(row["contract_period"]) if row.get("contract_period") is not None else None,
  286. "owner_user_id": owner_id or "",
  287. "owner_user_name": _str_or_none(row.get("owner_user_name"), 50),
  288. "received_amount": _dec(row.get("received_amount"), Decimal("0.00")),
  289. "unreceived_amount": _dec(row.get("unreceived_amount"), Decimal("0.00")),
  290. "invoice_amount": _dec(row.get("invoice_amount"), Decimal("0.00")),
  291. "uninvoice_amount": _dec(row.get("uninvoice_amount"), Decimal("0.00")),
  292. "party_a": _str_or_none(row.get("party_a"), 200),
  293. "party_a_address": _str_or_none(row.get("party_a_address"), 255),
  294. "party_a_contact": _str_or_none(row.get("party_a_contact"), 50),
  295. "party_a_mobile": _str_or_none(row.get("party_a_mobile"), 20),
  296. "party_a_legal_person": _str_or_none(row.get("party_a_legal_person"), 50),
  297. "party_a_agent": _str_or_none(row.get("party_a_agent"), 50),
  298. "party_a_phone_fax": _str_or_none(row.get("party_a_phone_fax"), 50),
  299. "party_a_bank": _str_or_none(row.get("party_a_bank"), 100),
  300. "party_a_account": _str_or_none(row.get("party_a_account"), 50),
  301. "party_b": _str_or_none(row.get("party_b"), 200),
  302. "party_b_address": _str_or_none(row.get("party_b_address"), 255),
  303. "party_b_contact": _str_or_none(row.get("party_b_contact"), 50),
  304. "party_b_mobile": _str_or_none(row.get("party_b_mobile"), 20),
  305. "party_b_legal_person": _str_or_none(row.get("party_b_legal_person"), 100),
  306. "party_b_agent": _str_or_none(row.get("party_b_agent"), 100),
  307. "party_b_phone_fax": _str_or_none(row.get("party_b_phone_fax"), 100),
  308. "party_b_bank": _str_or_none(row.get("party_b_bank"), 200),
  309. "party_b_account": _str_or_none(row.get("party_b_account"), 100),
  310. "payment_terms": row.get("payment_terms"),
  311. "delivery_terms": row.get("delivery_terms"),
  312. "contract_terms": row.get("contract_terms"),
  313. "settlement_method": _str_or_none(row.get("settlement_method"), 50),
  314. "template_content": row.get("template_content"),
  315. "settlement_clause_drafts": row.get("settlement_clause_drafts"),
  316. "invalid_reason": _str_or_none(row.get("invalid_reason"), 500),
  317. "invalid_time": row.get("invalid_time"),
  318. "version_no": int(row.get("version_no") if row.get("version_no") is not None else row.get("version") or 0),
  319. "supplier_id": legacy_id_to_str(row.get("supplier_id")),
  320. "tenant_no": tenant_no,
  321. "order_num": 0,
  322. "remark": _str_or_none(row.get("remark"), 512),
  323. "create_by": map_user(row.get("create_by")),
  324. "create_dept_id": "",
  325. "create_time": row.get("create_time") or datetime.now(),
  326. "update_by": map_user(row.get("update_by")),
  327. "update_time": row.get("update_time") or row.get("create_time") or datetime.now(),
  328. "del_flag": int(row.get("del_flag") or 0),
  329. }
  330. def transform_contract_product(
  331. row: dict,
  332. tenant_no: str,
  333. crm_user_map: Dict[int, str],
  334. admin_id: Optional[str],
  335. stats: MigrationStats,
  336. ) -> dict:
  337. rid = legacy_id_to_str(row["id"])
  338. label = f"contract_product#{rid}"
  339. def map_user(field_val: Any) -> Optional[str]:
  340. return resolve_portal_user_id(field_val, crm_user_map, admin_id, stats, label)
  341. return {
  342. "id": rid,
  343. "contract_id": legacy_id_to_str(row.get("contract_id")) or "",
  344. "product_id": legacy_id_to_str(row.get("product_id")) or "",
  345. "product_name": (row.get("product_name") or "")[:200],
  346. "product_no": _str_or_none(row.get("product_no"), 50),
  347. "category_id": legacy_id_to_str(row.get("category_id")),
  348. "category_name": _str_or_none(row.get("category_name"), 100),
  349. "model": _str_or_none(row.get("model"), 100),
  350. "unit": (row.get("unit") or "件")[:20],
  351. "quantity": _dec(row.get("quantity"), Decimal("0")),
  352. "price": _dec(row.get("price"), Decimal("0.00")),
  353. "discount": _dec(row.get("discount"), Decimal("0.00")),
  354. "tax_rate": _dec(row.get("tax_rate"), Decimal("6.00")),
  355. "tax_amount": _dec(row.get("tax_amount"), Decimal("0.00")),
  356. "subtotal": _dec(row.get("subtotal"), Decimal("0.00")),
  357. "delivery_date": row.get("delivery_date"),
  358. "delivery_status": (row.get("delivery_status") or "pending")[:20],
  359. "delivered_quantity": _dec(row.get("delivered_quantity"), Decimal("0")),
  360. "description": _str_or_none(row.get("description"), 1000),
  361. "package_spec": _str_or_none(row.get("package_spec"), 200),
  362. "delivery_method": _str_or_none(row.get("delivery_method"), 100),
  363. "sort": int(row.get("sort") or 0),
  364. "tenant_no": tenant_no,
  365. "order_num": 0,
  366. "remark": _str_or_none(row.get("remark"), 500),
  367. "create_by": map_user(row.get("create_by")),
  368. "create_dept_id": "",
  369. "create_time": row.get("create_time") or datetime.now(),
  370. "update_by": map_user(row.get("update_by")),
  371. "update_time": row.get("update_time") or row.get("create_time") or datetime.now(),
  372. "del_flag": int(row.get("del_flag") or 0),
  373. }
  374. def transform_contract_price_tier(
  375. row: dict,
  376. tenant_no: str,
  377. crm_user_map: Dict[int, str],
  378. admin_id: Optional[str],
  379. stats: MigrationStats,
  380. ) -> dict:
  381. rid = legacy_id_to_str(row["id"])
  382. label = f"contract_price_tier#{rid}"
  383. def map_user(field_val: Any) -> Optional[str]:
  384. return resolve_portal_user_id(field_val, crm_user_map, admin_id, stats, label)
  385. letter_oss_ids = row.get("letter_oss_ids")
  386. letter_oss_id = legacy_id_to_str(row.get("letter_oss_id"))
  387. return {
  388. "id": rid,
  389. "contract_id": legacy_id_to_str(row.get("contract_id")) or "",
  390. "contract_product_id": legacy_id_to_str(row.get("contract_product_id")) or "",
  391. "start_date": row.get("start_date"),
  392. "end_date": row.get("end_date"),
  393. "price": _dec(row.get("price"), Decimal("0")),
  394. "letter_oss_ids": letter_oss_ids if letter_oss_ids else None,
  395. "letter_oss_id": letter_oss_id,
  396. "sort": int(row.get("sort") or 0),
  397. "tenant_no": tenant_no,
  398. "order_num": 0,
  399. "remark": _str_or_none(row.get("remark"), 500),
  400. "create_by": map_user(row.get("create_by")),
  401. "create_dept_id": "",
  402. "create_time": row.get("create_time") or datetime.now(),
  403. "update_by": map_user(row.get("update_by")),
  404. "update_time": row.get("update_time") or row.get("create_time") or datetime.now(),
  405. "del_flag": int(row.get("del_flag") or 0),
  406. }
  407. def transform_contract_approval(
  408. row: dict,
  409. tenant_no: str,
  410. crm_user_map: Dict[int, str],
  411. admin_id: Optional[str],
  412. oss_map: Dict[str, str],
  413. stats: MigrationStats,
  414. ) -> dict:
  415. rid = legacy_id_to_str(row["id"])
  416. label = f"contract_approval#{rid}"
  417. def map_user(field_val: Any, *, required: bool = False) -> Optional[str]:
  418. return resolve_portal_user_id(field_val, crm_user_map, admin_id, stats, label, required=required)
  419. return {
  420. "id": rid,
  421. "contract_id": legacy_id_to_str(row.get("contract_id")) or "",
  422. "flow_id": legacy_id_to_str(row.get("flow_id")),
  423. "step": int(row.get("step") or 1),
  424. "step_name": _str_or_none(row.get("step_name"), 100),
  425. "approver_id": map_user(row.get("approver_id"), required=True) or "",
  426. "approver_name": _str_or_none(row.get("approver_name"), 50),
  427. "approver_dept": _str_or_none(row.get("approver_dept"), 100),
  428. "approval_result": (row.get("approval_result") or "pending")[:20],
  429. "approval_opinion": row.get("approval_opinion"),
  430. "approval_time": row.get("approval_time"),
  431. "approval_duration": int(row["approval_duration"]) if row.get("approval_duration") is not None else None,
  432. "attachments": normalize_attachment_csv(row.get("attachments"), oss_map),
  433. "is_current": int(row.get("is_current") if row.get("is_current") is not None else 1),
  434. "sort": int(row.get("sort") or 0),
  435. "tenant_no": tenant_no,
  436. "order_num": 0,
  437. "remark": _str_or_none(row.get("remark"), 500),
  438. "create_by": map_user(row.get("create_by")),
  439. "create_dept_id": "",
  440. "create_time": row.get("create_time") or datetime.now(),
  441. "update_by": map_user(row.get("update_by")),
  442. "update_time": row.get("update_time") or row.get("create_time") or datetime.now(),
  443. "del_flag": int(row.get("del_flag") or 0),
  444. }
  445. def transform_contract_change(
  446. row: dict,
  447. tenant_no: str,
  448. crm_user_map: Dict[int, str],
  449. admin_id: Optional[str],
  450. oss_map: Dict[str, str],
  451. stats: MigrationStats,
  452. ) -> dict:
  453. rid = legacy_id_to_str(row["id"])
  454. label = f"contract_change#{rid}"
  455. def map_user(field_val: Any) -> Optional[str]:
  456. return resolve_portal_user_id(field_val, crm_user_map, admin_id, stats, label)
  457. return {
  458. "id": rid,
  459. "contract_id": legacy_id_to_str(row.get("contract_id")) or "",
  460. "contract_no": _str_or_none(row.get("contract_no"), 50),
  461. "change_type": (row.get("change_type") or "")[:50],
  462. "change_reason": (row.get("change_reason") or "")[:500],
  463. "change_content": row.get("change_content"),
  464. "old_value": row.get("old_value"),
  465. "new_value": row.get("new_value"),
  466. "change_amount": _dec(row.get("change_amount")),
  467. "approval_status": (row.get("approval_status") or "pending")[:20],
  468. "approver_id": map_user(row.get("approver_id")),
  469. "approver_name": _str_or_none(row.get("approver_name"), 50),
  470. "approval_time": row.get("approval_time"),
  471. "approval_opinion": _str_or_none(row.get("approval_opinion"), 500),
  472. "attachment_files": normalize_contract_attachment_files(row.get("attachment_files"), oss_map),
  473. "tenant_no": tenant_no,
  474. "order_num": 0,
  475. "remark": _str_or_none(row.get("remark"), 500),
  476. "create_by": map_user(row.get("create_by")),
  477. "create_dept_id": "",
  478. "create_time": row.get("create_time") or datetime.now(),
  479. "update_by": map_user(row.get("update_by")),
  480. "update_time": row.get("update_time") or row.get("create_time") or datetime.now(),
  481. "del_flag": int(row.get("del_flag") or 0),
  482. }
  483. INSERT_CONTRACT_TEMPLATE_SQL = text(
  484. """
  485. INSERT INTO crm_contract_template (
  486. id, template_no, template_name, contract_type, template_content, payment_terms,
  487. delivery_terms, contract_terms, party_b, party_b_address, party_b_contact, party_b_mobile,
  488. default_currency, default_tax_rate, default_period, is_active, usage_count, sort,
  489. tenant_no, order_num, remark, create_by, create_dept_id, create_time, update_by, update_time, del_flag
  490. ) VALUES (
  491. :id, :template_no, :template_name, :contract_type, :template_content, :payment_terms,
  492. :delivery_terms, :contract_terms, :party_b, :party_b_address, :party_b_contact, :party_b_mobile,
  493. :default_currency, :default_tax_rate, :default_period, :is_active, :usage_count, :sort,
  494. :tenant_no, :order_num, :remark, :create_by, :create_dept_id, :create_time, :update_by, :update_time, :del_flag
  495. )
  496. """
  497. )
  498. INSERT_CONTRACT_SQL = text(
  499. """
  500. INSERT INTO crm_contract (
  501. id, contract_no, contract_name, customer_id, customer_name, opportunity_id, quote_id,
  502. parent_contract_id, renewal_count, template_id, contract_template, contact_id, contact_name,
  503. contact_mobile, contract_type, contract_nature, amount, currency, tax_rate, amount_with_tax,
  504. status, performance_status, performance_rate, customer_satisfaction, approval_status,
  505. approval_flow_id, contract_file, attachment_files, sign_date, actual_sign_date, start_date,
  506. end_date, contract_period, owner_user_id, owner_user_name, received_amount, unreceived_amount,
  507. invoice_amount, uninvoice_amount, party_a, party_a_address, party_a_contact, party_a_mobile,
  508. party_a_legal_person, party_a_agent, party_a_phone_fax, party_a_bank, party_a_account,
  509. party_b, party_b_address, party_b_contact, party_b_mobile, party_b_legal_person, party_b_agent,
  510. party_b_phone_fax, party_b_bank, party_b_account, payment_terms, delivery_terms, contract_terms,
  511. settlement_method, template_content, settlement_clause_drafts, invalid_reason, invalid_time,
  512. version_no, supplier_id, tenant_no, order_num, remark, create_by, create_dept_id, create_time,
  513. update_by, update_time, del_flag
  514. ) VALUES (
  515. :id, :contract_no, :contract_name, :customer_id, :customer_name, :opportunity_id, :quote_id,
  516. :parent_contract_id, :renewal_count, :template_id, :contract_template, :contact_id, :contact_name,
  517. :contact_mobile, :contract_type, :contract_nature, :amount, :currency, :tax_rate, :amount_with_tax,
  518. :status, :performance_status, :performance_rate, :customer_satisfaction, :approval_status,
  519. :approval_flow_id, :contract_file, :attachment_files, :sign_date, :actual_sign_date, :start_date,
  520. :end_date, :contract_period, :owner_user_id, :owner_user_name, :received_amount, :unreceived_amount,
  521. :invoice_amount, :uninvoice_amount, :party_a, :party_a_address, :party_a_contact, :party_a_mobile,
  522. :party_a_legal_person, :party_a_agent, :party_a_phone_fax, :party_a_bank, :party_a_account,
  523. :party_b, :party_b_address, :party_b_contact, :party_b_mobile, :party_b_legal_person, :party_b_agent,
  524. :party_b_phone_fax, :party_b_bank, :party_b_account, :payment_terms, :delivery_terms, :contract_terms,
  525. :settlement_method, :template_content, :settlement_clause_drafts, :invalid_reason, :invalid_time,
  526. :version_no, :supplier_id, :tenant_no, :order_num, :remark, :create_by, :create_dept_id, :create_time,
  527. :update_by, :update_time, :del_flag
  528. )
  529. """
  530. )
  531. INSERT_CONTRACT_PRODUCT_SQL = text(
  532. """
  533. INSERT INTO crm_contract_product (
  534. id, contract_id, product_id, product_name, product_no, category_id, category_name,
  535. model, unit, quantity, price, discount, tax_rate, tax_amount, subtotal,
  536. delivery_date, delivery_status, delivered_quantity, description, package_spec,
  537. delivery_method, sort, tenant_no, order_num, remark, create_by, create_dept_id,
  538. create_time, update_by, update_time, del_flag
  539. ) VALUES (
  540. :id, :contract_id, :product_id, :product_name, :product_no, :category_id, :category_name,
  541. :model, :unit, :quantity, :price, :discount, :tax_rate, :tax_amount, :subtotal,
  542. :delivery_date, :delivery_status, :delivered_quantity, :description, :package_spec,
  543. :delivery_method, :sort, :tenant_no, :order_num, :remark, :create_by, :create_dept_id,
  544. :create_time, :update_by, :update_time, :del_flag
  545. )
  546. """
  547. )
  548. INSERT_CONTRACT_PRICE_TIER_SQL = text(
  549. """
  550. INSERT INTO crm_contract_product_price_tier (
  551. id, contract_id, contract_product_id, start_date, end_date, price,
  552. letter_oss_ids, letter_oss_id, sort, tenant_no, order_num, remark,
  553. create_by, create_dept_id, create_time, update_by, update_time, del_flag
  554. ) VALUES (
  555. :id, :contract_id, :contract_product_id, :start_date, :end_date, :price,
  556. :letter_oss_ids, :letter_oss_id, :sort, :tenant_no, :order_num, :remark,
  557. :create_by, :create_dept_id, :create_time, :update_by, :update_time, :del_flag
  558. )
  559. """
  560. )
  561. INSERT_CONTRACT_APPROVAL_SQL = text(
  562. """
  563. INSERT INTO crm_contract_approval (
  564. id, contract_id, flow_id, step, step_name, approver_id, approver_name, approver_dept,
  565. approval_result, approval_opinion, approval_time, approval_duration, attachments,
  566. is_current, sort, tenant_no, order_num, remark, create_by, create_dept_id,
  567. create_time, update_by, update_time, del_flag
  568. ) VALUES (
  569. :id, :contract_id, :flow_id, :step, :step_name, :approver_id, :approver_name, :approver_dept,
  570. :approval_result, :approval_opinion, :approval_time, :approval_duration, :attachments,
  571. :is_current, :sort, :tenant_no, :order_num, :remark, :create_by, :create_dept_id,
  572. :create_time, :update_by, :update_time, :del_flag
  573. )
  574. """
  575. )
  576. INSERT_CONTRACT_CHANGE_SQL = text(
  577. """
  578. INSERT INTO crm_contract_change (
  579. id, contract_id, contract_no, change_type, change_reason, change_content, old_value,
  580. new_value, change_amount, approval_status, approver_id, approver_name, approval_time,
  581. approval_opinion, attachment_files, tenant_no, order_num, remark, create_by, create_dept_id,
  582. create_time, update_by, update_time, del_flag
  583. ) VALUES (
  584. :id, :contract_id, :contract_no, :change_type, :change_reason, :change_content, :old_value,
  585. :new_value, :change_amount, :approval_status, :approver_id, :approver_name, :approval_time,
  586. :approval_opinion, :attachment_files, :tenant_no, :order_num, :remark, :create_by, :create_dept_id,
  587. :create_time, :update_by, :update_time, :del_flag
  588. )
  589. """
  590. )
  591. STEP_INSERT_SQL = {
  592. "crm_contract_template": INSERT_CONTRACT_TEMPLATE_SQL,
  593. "crm_contract": INSERT_CONTRACT_SQL,
  594. "crm_contract_product": INSERT_CONTRACT_PRODUCT_SQL,
  595. "crm_contract_product_price_tier": INSERT_CONTRACT_PRICE_TIER_SQL,
  596. "crm_contract_approval": INSERT_CONTRACT_APPROVAL_SQL,
  597. "crm_contract_change": INSERT_CONTRACT_CHANGE_SQL,
  598. }
  599. def write_mapping_csv(source_rows: List[dict], path: Path) -> None:
  600. path.parent.mkdir(parents=True, exist_ok=True)
  601. migrated_at = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
  602. with path.open("w", encoding="utf-8", newline="") as f:
  603. w = csv.DictWriter(f, fieldnames=["source_id", "new_id", "migrated_at"])
  604. w.writeheader()
  605. for row in source_rows:
  606. sid = legacy_id_to_str(row["id"])
  607. w.writerow({"source_id": sid, "new_id": sid, "migrated_at": migrated_at})
  608. def migrate_table(
  609. source_engine: Engine,
  610. target_engine: Engine,
  611. table: str,
  612. *,
  613. tenant_no: str,
  614. crm_user_map: Dict[int, str],
  615. admin_id: Optional[str],
  616. oss_map: Dict[str, str],
  617. stats: MigrationStats,
  618. dry_run: bool,
  619. update_existing: bool,
  620. include_deleted: bool,
  621. ) -> List[dict]:
  622. step = stats.step(table)
  623. source_rows = fetch_source_rows(source_engine, table, include_deleted)
  624. step.source_count = len(source_rows)
  625. transformers = {
  626. "crm_contract_template": lambda r: transform_contract_template(r, tenant_no, crm_user_map, admin_id, stats),
  627. "crm_contract": lambda r: transform_contract(r, tenant_no, crm_user_map, admin_id, oss_map, stats),
  628. "crm_contract_product": lambda r: transform_contract_product(r, tenant_no, crm_user_map, admin_id, stats),
  629. "crm_contract_product_price_tier": lambda r: transform_contract_price_tier(
  630. r, tenant_no, crm_user_map, admin_id, stats
  631. ),
  632. "crm_contract_approval": lambda r: transform_contract_approval(
  633. r, tenant_no, crm_user_map, admin_id, oss_map, stats
  634. ),
  635. "crm_contract_change": lambda r: transform_contract_change(
  636. r, tenant_no, crm_user_map, admin_id, oss_map, stats
  637. ),
  638. }
  639. payloads = [transformers[table](r) for r in source_rows]
  640. if dry_run:
  641. step.inserted = len(payloads)
  642. return source_rows
  643. insert_sql = STEP_INSERT_SQL[table]
  644. with target_engine.begin() as conn:
  645. for payload in payloads:
  646. rid = payload["id"]
  647. if target_row_exists(conn, table, rid):
  648. if update_existing:
  649. step.skipped += 1
  650. else:
  651. step.skipped += 1
  652. else:
  653. conn.execute(insert_sql, payload)
  654. step.inserted += 1
  655. return source_rows
  656. def print_report(stats: MigrationStats, dry_run: bool) -> None:
  657. mode = "DRY-RUN" if dry_run else "COMMITTED"
  658. print(f"\n=== CRM 合同迁移 [{mode}] ===")
  659. for table, _ in MIGRATION_STEPS:
  660. s = stats.step(table)
  661. print(f"{table}: 源={s.source_count} 插入={s.inserted} 跳过={s.skipped}")
  662. if stats.warnings:
  663. print(f"警告 ({len(stats.warnings)}):")
  664. for w in stats.warnings[:20]:
  665. print(f" - {w}")
  666. if len(stats.warnings) > 20:
  667. print(f" ... 另有 {len(stats.warnings) - 20} 条")
  668. def run_migration(
  669. source_engine: Engine,
  670. target_engine: Engine,
  671. *,
  672. tenant_no: str,
  673. user_mapping_path: Path,
  674. mapping_dir: Path,
  675. dry_run: bool,
  676. update_existing: bool,
  677. include_deleted: bool,
  678. only_tables: Optional[List[str]],
  679. ) -> MigrationStats:
  680. stats = MigrationStats()
  681. crm_user_map, admin_id = load_user_mapping(user_mapping_path)
  682. if not admin_id:
  683. admin_id = fetch_portal_admin_id(target_engine)
  684. oss_map = load_oss_id_to_url(target_engine, tenant_no)
  685. print(f"sys_oss 映射条数: {len(oss_map)}")
  686. selected = [t for t, _ in MIGRATION_STEPS if not only_tables or t in only_tables]
  687. for table in selected:
  688. print(f"\n>> 迁移 {table} ...")
  689. source_rows = migrate_table(
  690. source_engine,
  691. target_engine,
  692. table,
  693. tenant_no=tenant_no,
  694. crm_user_map=crm_user_map,
  695. admin_id=admin_id,
  696. oss_map=oss_map,
  697. stats=stats,
  698. dry_run=dry_run,
  699. update_existing=update_existing,
  700. include_deleted=include_deleted,
  701. )
  702. if table == "crm_contract" and not dry_run:
  703. write_mapping_csv(source_rows, mapping_dir / "crm_contract_id_mapping.csv")
  704. print_report(stats, dry_run)
  705. return stats
  706. def main() -> int:
  707. parser = argparse.ArgumentParser(description="Migrate CRM contract tables from sx to portal")
  708. parser.add_argument("--source-url", default="")
  709. parser.add_argument("--target-url", default="")
  710. parser.add_argument("--tenant-no", default=DEFAULT_TENANT_NO)
  711. parser.add_argument(
  712. "--user-mapping",
  713. default=str(BACKEND_ROOT.parent / "docs/data-migration/mappings/user_mapping_result.csv"),
  714. )
  715. parser.add_argument("--dry-run", action="store_true")
  716. parser.add_argument("--update", action="store_true")
  717. parser.add_argument("--include-deleted", action="store_true")
  718. parser.add_argument("--tables", default="", help="逗号分隔,默认全部六表")
  719. parser.add_argument("--env-file", default=os.environ.get("ENV_FILE", ""))
  720. args = parser.parse_args()
  721. load_settings_env(args.env_file or None)
  722. settings = load_runtime_settings()
  723. target_url = args.target_url or settings.DATABASE_URL
  724. source_url = args.source_url or os.environ.get("SX_SOURCE_DATABASE_URL") or derive_source_url(target_url)
  725. only_tables = [t.strip() for t in args.tables.split(",") if t.strip()] or None
  726. print(f"源库: {urlparse(source_url).path}")
  727. print(f"目标库: {urlparse(target_url).path}")
  728. run_migration(
  729. create_engine(source_url, pool_pre_ping=True),
  730. create_engine(target_url, pool_pre_ping=True),
  731. tenant_no=args.tenant_no,
  732. user_mapping_path=Path(args.user_mapping),
  733. mapping_dir=BACKEND_ROOT.parent / "docs/data-migration/mappings",
  734. dry_run=args.dry_run,
  735. update_existing=args.update,
  736. include_deleted=args.include_deleted,
  737. only_tables=only_tables,
  738. )
  739. return 0
  740. if __name__ == "__main__":
  741. raise SystemExit(main())