sync_measure_data.py 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359
  1. from calendar import c
  2. import mysql.connector
  3. import sqlite3
  4. import json
  5. import os
  6. import datetime
  7. import time
  8. import requests
  9. import http.client
  10. from urllib.parse import urlparse
  11. import shutil
  12. import hashlib
  13. import zipfile
  14. import base64
  15. import uuid
  16. from decimal import Decimal
  17. import sys
  18. import configparser
  19. # ========== 配置文件加载 ==========
  20. # exe / 脚本同目录下的 config.ini,首次运行自动生成,用记事本即可修改
  21. if getattr(sys, 'frozen', False):
  22. BASE_DIR = os.path.dirname(sys.executable)
  23. else:
  24. BASE_DIR = os.path.dirname(os.path.abspath(__file__))
  25. CONFIG_FILE = os.path.join(BASE_DIR, 'config.ini')
  26. DEFAULT_CONFIG = """# ============================================
  27. # 沪武档案同步玄海 - 运行配置
  28. # 修改本文件后重新运行程序即可生效,无需重新生成 exe
  29. # ============================================
  30. [mysql]
  31. # 业务数据库连接(连接失败请检查 VPN 或修改以下地址/账号)
  32. host = 172.16.10.152
  33. port = 15606
  34. user = root
  35. password = 84853032
  36. database = dnn202500200jy
  37. connect_timeout = 10
  38. [api]
  39. # 档案系统上传接口
  40. api_url = http://218.94.73.106:8081/api/eps9/tyjk/api/data/asip/HWKJLZF
  41. # 附件文件下载地址前缀(数据库中为相对路径时自动拼接)
  42. file_base_url = https://oss.dnnbuild.com
  43. [archive]
  44. # 归档单位(默认值,数据缺失时使用)
  45. archive_unit = 无锡至宜兴高速公路雪堰枢纽至西坞枢纽段扩建工程
  46. # 文件目录署名单位
  47. catalog_signing_unit = 沪武高速公路太仓至常州段扩建工程苏州段
  48. [local]
  49. # 本地 SQLite 缓存文件名(放在 exe 同目录)
  50. sqlite_db = measure_data_cache.db
  51. # EEP 包输出目录(放在 exe 同目录)
  52. output_dir = eep_packages
  53. """
  54. def load_config():
  55. """加载 config.ini;不存在时自动写入默认配置。返回 (DB_CONFIG, API_URL, FILE_BASE_URL, ARCHIVE_UNIT, CATALOG_SIGNING_UNIT, SQLITE_DB, OUTPUT_DIR)。"""
  56. if not os.path.exists(CONFIG_FILE):
  57. try:
  58. with open(CONFIG_FILE, 'w', encoding='utf-8') as f:
  59. f.write(DEFAULT_CONFIG)
  60. print(f"[配置] 未找到配置文件,已自动生成: {CONFIG_FILE}")
  61. print("[配置] 可关闭程序,用记事本修改该文件后重新运行。")
  62. print()
  63. except Exception as e:
  64. print(f"[配置][警告] 无法写入配置文件 {CONFIG_FILE}: {e},改用内置默认配置。")
  65. # interpolation=None:密码中出现 % 等特殊字符也不会报错
  66. cfg = configparser.ConfigParser(interpolation=None)
  67. cfg.optionxform = str # 保留键名大小写
  68. try:
  69. cfg.read(CONFIG_FILE, encoding='utf-8-sig')
  70. except Exception as e:
  71. print(f"[配置][警告] 读取配置文件失败({e}),改用内置默认配置。")
  72. cfg = configparser.ConfigParser(interpolation=None)
  73. cfg.optionxform = str
  74. cfg.read_string(DEFAULT_CONFIG)
  75. def get(section, key, fallback):
  76. try:
  77. value = cfg.get(section, key)
  78. return value if value != '' else fallback
  79. except Exception:
  80. return fallback
  81. db_config = {
  82. 'user': get('mysql', 'user', 'root'),
  83. 'password': get('mysql', 'password', '84853032'),
  84. 'host': get('mysql', 'host', '172.16.10.152'),
  85. 'port': int(get('mysql', 'port', '15606')),
  86. 'database': get('mysql', 'database', 'dnn202500200jy'),
  87. 'use_pure': True,
  88. 'connect_timeout': int(get('mysql', 'connect_timeout', '10')),
  89. }
  90. api_url = get('api', 'api_url', "http://218.94.73.106:8081/api/eps9/tyjk/api/data/asip/HWKJLZF")
  91. file_base_url = get('api', 'file_base_url', "https://oss.dnnbuild.com")
  92. archive_unit = get('archive', 'archive_unit', "无锡至宜兴高速公路雪堰枢纽至西坞枢纽段扩建工程")
  93. catalog_signing_unit = get('archive', 'catalog_signing_unit', "沪武高速公路太仓至常州段扩建工程苏州段")
  94. sqlite_db = get('local', 'sqlite_db', 'measure_data_cache.db')
  95. output_dir = get('local', 'output_dir', 'eep_packages')
  96. if not os.path.isabs(sqlite_db):
  97. sqlite_db = os.path.join(BASE_DIR, sqlite_db)
  98. if not os.path.isabs(output_dir):
  99. output_dir = os.path.join(BASE_DIR, output_dir)
  100. return db_config, api_url, file_base_url, archive_unit, catalog_signing_unit, sqlite_db, output_dir
  101. (DB_CONFIG, API_URL, FILE_BASE_URL, ARCHIVE_UNIT, CATALOG_SIGNING_UNIT,
  102. SQLITE_DB, OUTPUT_DIR) = load_config()
  103. # XML 模板
  104. XML_DESC_TEMPLATE = """<?xml version="1.0" encoding="UTF-8"?>
  105. <文件说明>
  106. <载体编号>{archive_id}</载体编号>
  107. <载体类型>在线</载体类型>
  108. <载体容量>{size}</载体容量>
  109. <制作时间>{date}</制作时间>
  110. <载体制作单位名称>沪武高速公路太仓至常州段扩建工程苏州段</载体制作单位名称>
  111. <载体保管单位名称>沪武高速公路太仓至常州段扩建工程苏州段</载体保管单位名称>
  112. <载体检查单位名称>沪武高速公路太仓至常州段扩建工程苏州段</载体检查单位名称>
  113. <载体申请单位名称>沪武高速公路太仓至常州段扩建工程苏州段</载体申请单位名称>
  114. <年度>{year}</年度>
  115. <归档文件数量>{file_count}</归档文件数量>
  116. <归档类型>文件</归档类型>
  117. <起始件号></起始件号>
  118. <截至件号></截至件号>
  119. <信息系统名称>档案综合利用平台</信息系统名称>
  120. {process_xml}</文件说明>"""
  121. XML_PROCESS_NODE_TEMPLATE = """ <节点>
  122. <节点标识>{node_id}</节点标识>
  123. <节点名称>{name}</节点名称>
  124. <类型>{type}</类型>
  125. <机构名称>{org_name}</机构名称>
  126. <办理人>{operator_name}</办理人>
  127. <创建时间>{created_time}</创建时间>
  128. <办理时间>{operate_time}</办理时间>
  129. <审核意见>{opinion}</审核意见>
  130. <审核结论>{conclusion}</审核结论>
  131. </节点>"""
  132. XML_CATALOG_TEMPLATE = """<?xml version="1.0" encoding="UTF-8"?>
  133. <文件目录>
  134. <归档文件>
  135. <处理部门></处理部门>
  136. <公文标识></公文标识>
  137. <文件类型>发文</文件类型>
  138. <份号></份号>
  139. <密级和保密期限>普通</密级和保密期限>
  140. <紧急程度>内部资料</紧急程度>
  141. <发文机关标志></发文机关标志>
  142. <发文字号>{doc_num}</发文字号>
  143. <签发人>null</签发人>
  144. <标题>{title}</标题>
  145. <主送机关></主送机关>
  146. <附件说明></附件说明>
  147. <发文机关或签发人署名>{signing_unit}</发文机关或签发人署名>
  148. <成文日期>{date_compact}</成文日期>
  149. <附注></附注>
  150. <抄送机关></抄送机关>
  151. <印发机关></印发机关>
  152. <印发日期></印发日期>
  153. <发布层次></发布层次>
  154. <档号>{archive_id}</档号>
  155. <年度>{year}</年度>
  156. <保管期限></保管期限>
  157. <机构或问题></机构或问题>
  158. <当前计量期>{current_period}</当前计量期>
  159. <计量号>{measure_number}</计量号>
  160. <起始日期>{period_start}</起始日期>
  161. <终止日期>{period_end}</终止日期>
  162. <制表人标识>{tabulator_id}</制表人标识>
  163. <制表人名称>{tabulator_name}</制表人名称>
  164. <制表日期>{tabulation_date}</制表日期>
  165. <到上期末累计完成额>{completed_last_period}</到上期末累计完成额>
  166. <本期完成额>{current_period_amount}</本期完成额>
  167. <本期末累计额>{completed_cumulative}</本期末累计额>
  168. <数字对象标识></数字对象标识>
  169. <环境信息></环境信息>
  170. <软件环境></软件环境>
  171. <硬件环境></硬件环境>
  172. <处理类型></处理类型>
  173. <处理者></处理者>
  174. <处理时间></处理时间>
  175. <处理结果></处理结果>
  176. <文件>
  177. {file_details}
  178. </文件>
  179. </归档文件>
  180. </文件目录>"""
  181. XML_FILE_DETAIL_TEMPLATE = """ <文件详情>
  182. <文件路径>{path}</文件路径>
  183. <文件大小>{size}</文件大小>
  184. <数字摘要>{md5}</数字摘要>
  185. <文件单位>B</文件单位>
  186. <文件名称>{name}</文件名称>
  187. <文件类型>{type}</文件类型>
  188. </文件详情>"""
  189. XML_METADATA_TEMPLATE = """<?xml version="1.0" encoding="UTF-8"?>
  190. <电子文件封装包 name="M201">
  191. <封装包格式描述 name="M202">本EEP根据中华人民共和国档案行业标准DA/T 48-2009《基于XML的电子文件封装规范》生成</封装包格式描述>
  192. <版本 name="M203">2009</版本>
  193. <被签名对象 name="M204">
  194. <封装包类型 name="M205" />
  195. <封装包类型描述 name="M206" />
  196. <封装包创建时间 name="M207">{date}</封装包创建时间>
  197. <封装包创建单位 name="M208">{archive_unit}</封装包创建单位>
  198. <封装内容 name="M209">
  199. <文件实体块 name="M210">
  200. <文件实体 name="M211">
  201. <聚合层次 name="M1" />
  202. <来源 name="M2">
  203. <档案馆名称 name="M3">xx</档案馆名称>
  204. <档案馆代码 name="M4" />
  205. <全宗名称 name="M5">{archive_unit}</全宗名称>
  206. <立档单位名称 name="M6">{archive_unit}</立档单位名称>
  207. </来源>
  208. <电子文件号 name="M7" />
  209. <档号 name="M8">
  210. <全宗号 name="M9">XYK</全宗号>
  211. <目录号 name="M10" />
  212. <年度 name="M11">{year}</年度>
  213. <保管期限 name="M12">永久</保管期限>
  214. <机构或问题 name="M13" />
  215. <类别号 name="M14" />
  216. <室编案卷号 name="M15" />
  217. <馆编案卷号 name="M16" />
  218. <室编件号 name="M17" />
  219. <文档序号 name="M19" />
  220. <页号 name="M20" />
  221. </档号>
  222. <内容描述 name="M21">
  223. <题名 name="M22">{title}</题名>
  224. <并列题名 name="M23" />
  225. <副题名 name="M24" />
  226. <说明题名文字 name="M25" />
  227. <主题词 name="M26" />
  228. <关键词 name="M27" />
  229. <人名 name="M28" />
  230. <摘要 name="M29" />
  231. <分类号 name="M30" />
  232. <文件编号 name="M31" />
  233. <责任者 name="M32" />
  234. <日期 name="M33">{date_compact}</日期>
  235. <文种 name="M34" />
  236. <紧急程度 name="M35" />
  237. <主送 name="M36" />
  238. <抄送 name="M37" />
  239. <密级 name="M38" />
  240. <保管期限 name="M39" />
  241. </内容描述>
  242. <形式特征 name="M41">
  243. <文件组合类型 name="M42" />
  244. <件数 name="M43" />
  245. <页数 name="M44" />
  246. <语种 name="M45" />
  247. <稿本 name="M46" />
  248. </形式特征>
  249. <附注 name="M75" />
  250. <文件数据 name="M213">
  251. {docs}
  252. </文件数据>
  253. </文件实体>
  254. <文件实体关系 name="M222">
  255. <文件标识符 name="M223">{file_id}</文件标识符>
  256. <被关联文件标识符 name="M224" />
  257. <关系类型 name="M87" />
  258. <关系 name="M87" />
  259. <关系描述 name="M88" />
  260. </文件实体关系>
  261. </文件实体块>
  262. <业务实体块 name="M225">
  263. {business_entities_xml}
  264. </业务实体块>
  265. <机构人员实体块 name="M229">
  266. {person_entities_xml}
  267. </机构人员实体块>
  268. </封装内容>
  269. </被签名对象>
  270. <电子签名块 name="M201">
  271. <电子签名 name="M57">
  272. <签名标识符 name="M234" />
  273. <签名规则 name="M58" />
  274. <签名时间 name="M59" />
  275. <签名人 name="M60" />
  276. <签名结果 name="M61" />
  277. <签名算法标识 name="M64" />
  278. </电子签名>
  279. </电子签名块>
  280. <锁定签名 name="M201">
  281. <被锁定签名标识符 name="M237" />
  282. <签名规则 name="M58" />
  283. <签名时间 name="M59" />
  284. <签名人 name="M60" />
  285. <签名结果 name="M61" />
  286. <证书块 name="M235">
  287. <证书 name="M62" />
  288. <证书引证 name="M63" />
  289. </证书块>
  290. <签名算法标识 name="M64" />
  291. </锁定签名>
  292. </电子文件封装包>"""
  293. XML_DOC_TEMPLATE = """ <文档>
  294. <文档标识符 name="M215">{md5}</文档标识符>
  295. <文档序号 name="M19" />
  296. <文档主从声明 name="M216" />
  297. <题名 name="M22">{doc_title}</题名>
  298. <文档数据 name="M217">
  299. <编码 name="M218">
  300. <电子属性 name="M46">
  301. <格式信息 name="M47">{ext}</格式信息>
  302. <计算机文件名 name="M48">{filename}</计算机文件名>
  303. <计算机文件大小 name="M49">{size}</计算机文件大小>
  304. <文档创建程序 name="M50" />
  305. <信息系统描述 name="M51" />
  306. <计算机文件创建时间 name="M101">{date_compact}</计算机文件创建时间>
  307. </电子属性>
  308. <数字化属性 name="M52">
  309. <数字化对象形态 name="M53" />
  310. <扫描分辨率 name="M54" />
  311. <扫描色彩模式 name="M55" />
  312. <图像压缩方案 name="M56" />
  313. </数字化属性>
  314. <编码描述 name="M219" />
  315. <反编码关键字 name="M220" />
  316. <编码数据 name="M221" />
  317. </编码>
  318. <电子签名 name="M57">
  319. <签名规则 name="M58" />
  320. <签名时间 name="M59" />
  321. <签名人 name="M60" />
  322. <签名结果 name="M61" />
  323. <签名算法标识 name="M64" />
  324. </电子签名>
  325. <存储位置 name="M65">
  326. <当前位置 name="M66">{path}</当前位置>
  327. <脱机载体编号 name="M67" />
  328. <脱机载体存址 name="M68" />
  329. <缩微号 name="M69" />
  330. </存储位置>
  331. <权限管理 name="M70">
  332. <知识产权说明 name="M71" />
  333. <控制标识 name="M74" />
  334. </权限管理>
  335. </文档数据>
  336. <固化信息块 name="P16">
  337. <固化信息 name="P17">
  338. <类型 name="P18" />
  339. <值 name="P19" />
  340. </固化信息>
  341. </固化信息块>
  342. </文档>"""
  343. XML_BUSINESS_ENTITY_TEMPLATE = """ <业务实体 name="M226">
  344. <业务标识符 name="M227">{business_id}</业务标识符>
  345. <机构人员标识符 name="M228">{operator_id}</机构人员标识符>
  346. <文件标识符 name="M223">{file_id}</文件标识符>
  347. <业务状态 name="M80">历史行为</业务状态>
  348. <业务行为 name="M81">审批</业务行为>
  349. <行为时间 name="M82">{action_time}</行为时间>
  350. <行为依据 name="M83">{action_basis}</行为依据>
  351. <行为描述 name="M84">{description}</行为描述>
  352. <机构人员名称 name="M77">{operator_name}</机构人员名称>
  353. <组织机构代码 name="M78">{org_name}</组织机构代码>
  354. </业务实体>"""
  355. XML_PERSON_ENTITY_TEMPLATE = """ <机构人员实体 name="M230">
  356. <机构人员标识符 name="M210">{operator_id}</机构人员标识符>
  357. <机构人员类型 name="M76">经办人</机构人员类型>
  358. <机构人员名称 name="M77">{operator_name}</机构人员名称>
  359. <组织机构代码 name="M78">{org_name}</组织机构代码>
  360. <个人职位 name="M79" />
  361. </机构人员实体>"""
  362. XML_PERSON_RELATION_TEMPLATE = """ <机构人员实体关系 name="M231">
  363. <机构人员标识符 name="M228">{operator_id}</机构人员标识符>
  364. <被关联机构人员标识符 name="M76" />
  365. <关系类型 name="M77" />
  366. <关系 name="M78" />
  367. <关系描述 name="M79" />
  368. </机构人员实体关系>"""
  369. # 流程节点 operateType -> 审核结论 映射 (参考 FlowProcessServiceImpl.resolveHisActivityStatus)
  370. OPERATE_TYPE_CONCLUSION = {
  371. 'pass': '通过',
  372. 'agree': '通过',
  373. 'start': '通过',
  374. 'reject': '驳回',
  375. 'deliver': '转办',
  376. 'stop': '终止',
  377. 'read': '已阅',
  378. 'addAssignee': '后加签',
  379. 'insertAssignee': '前加签',
  380. 'assignReject': '指定回退',
  381. }
  382. # 流程节点查询 SQL: 从 Flowable 历史表还原 /api/flow/process/flow/detail 的 historyFlows 数据
  383. QUERY_FLOW_NODES = """
  384. SELECT ai.ID_ AS node_id,
  385. ai.TASK_ID_ AS task_id,
  386. ai.ACT_ID_ AS task_def_key,
  387. ai.ACT_NAME_ AS task_name,
  388. ai.START_TIME_ AS create_time,
  389. ai.END_TIME_ AS end_time,
  390. ai.ASSIGNEE_ AS assignee,
  391. u.account AS assignee_account,
  392. u.real_name AS assignee_name,
  393. u.dept_id AS assignee_dept_id,
  394. d.dept_name AS org_name,
  395. (SELECT v.TEXT_
  396. FROM ACT_HI_VARINST v
  397. WHERE v.TASK_ID_ = ai.TASK_ID_
  398. AND v.NAME_ = 'operateType'
  399. LIMIT 1) AS operate_type,
  400. (SELECT CONVERT(cm.FULL_MSG_ USING utf8mb4)
  401. FROM ACT_HI_COMMENT cm
  402. WHERE cm.TASK_ID_ = ai.TASK_ID_
  403. AND cm.TYPE_ = 'comment'
  404. ORDER BY cm.TIME_
  405. LIMIT 1) AS comment_msg
  406. FROM ACT_HI_ACTINST ai
  407. LEFT JOIN blade_user u ON u.id = ai.ASSIGNEE_ AND u.is_deleted = 0
  408. LEFT JOIN blade_dept d ON d.id = CAST(SUBSTRING_INDEX(u.dept_id, ',', 1) AS CHAR)
  409. WHERE ai.PROC_INST_ID_ = %s
  410. AND ai.ACT_TYPE_ = 'userTask'
  411. ORDER BY IFNULL(ai.END_TIME_, NOW()), ai.START_TIME_
  412. """
  413. def _resolve_dept_name(cursor, dept_id, cache):
  414. """按部门 id 取部门名(对应 dept/list 接口的 deptName,即 dept_name);逐级向上直到找到有效部门。"""
  415. dept_id = str(dept_id or '').strip()
  416. if not dept_id:
  417. return ''
  418. if dept_id in cache:
  419. return cache[dept_id]
  420. name = ''
  421. seen = set()
  422. current = dept_id
  423. while current and current not in seen:
  424. seen.add(current)
  425. cursor.execute(
  426. "SELECT dept_name, full_name, parent_id, is_deleted FROM blade_dept WHERE id = %s LIMIT 1",
  427. (current,)
  428. )
  429. drow = cursor.fetchone()
  430. if not drow:
  431. break
  432. if not drow.get('is_deleted'):
  433. name = drow.get('dept_name') or drow.get('full_name') or ''
  434. if name:
  435. break
  436. current = str(drow.get('parent_id') or '').strip() or None
  437. cache[dept_id] = name or ''
  438. return name or ''
  439. def fetch_flow_nodes(cursor, flow_process_inst_id):
  440. """获取计量单审核过程节点列表 (等价于 /api/flow/process/flow/detail 的 flow 数据)。
  441. 只保留已办结 (END_TIME_ 非空) 且带 operateType 的节点,与后端
  442. FlowProcessServiceImpl.resolveHisActivityStatus 的过滤逻辑一致。
  443. """
  444. if not flow_process_inst_id:
  445. return []
  446. # flow_process_inst.id -> proc_inst_id
  447. cursor.execute(
  448. "SELECT proc_inst_id FROM flow_process_inst WHERE id = %s",
  449. (flow_process_inst_id,)
  450. )
  451. inst_row = cursor.fetchone()
  452. if not inst_row or not inst_row.get('proc_inst_id'):
  453. return []
  454. cursor.execute(QUERY_FLOW_NODES, (inst_row['proc_inst_id'],))
  455. rows = cursor.fetchall()
  456. dept_cache = {}
  457. def fmt_time(value):
  458. if not value:
  459. return ''
  460. if isinstance(value, (datetime.datetime, datetime.date)):
  461. return value.isoformat(timespec='milliseconds') if isinstance(value, datetime.datetime) else value.isoformat()
  462. return str(value)
  463. nodes = []
  464. for row in rows:
  465. # 未办结节点无 operateType, 后端同样跳过
  466. if not row.get('end_time') or not row.get('operate_type'):
  467. continue
  468. operate_type = str(row['operate_type'])
  469. comment = row.get('comment_msg') or ''
  470. if isinstance(comment, (bytes, bytearray)):
  471. try:
  472. comment = comment.decode('utf-8')
  473. except Exception:
  474. comment = ''
  475. # 组织机构:优先 SQL 关联结果;为空时按用户主部门逐级向上解析
  476. org_name = row.get('org_name')
  477. if not org_name:
  478. first_dept = str(row.get('assignee_dept_id') or '').split(',')[0].strip()
  479. org_name = _resolve_dept_name(cursor, first_dept, dept_cache)
  480. org_name = org_name or ARCHIVE_UNIT
  481. nodes.append({
  482. 'id': row.get('node_id') or '',
  483. 'name': row.get('task_name') or '',
  484. 'type': '计量支付',
  485. 'orgName': org_name,
  486. 'operatorId': str(row.get('assignee') or row.get('assignee_account') or ''),
  487. 'operatorName': row.get('assignee_name') or '',
  488. 'createdTime': fmt_time(row.get('create_time')),
  489. 'operateTime': fmt_time(row.get('end_time')),
  490. 'opinion': comment,
  491. 'conclusion': OPERATE_TYPE_CONCLUSION.get(operate_type, operate_type),
  492. })
  493. return nodes
  494. def build_process_xml(process_nodes):
  495. """把审核过程节点渲染成 说明文件.xml 的 <审核过程> 片段。"""
  496. if not process_nodes:
  497. return " <审核过程></审核过程>"
  498. node_xml = "\n".join(
  499. XML_PROCESS_NODE_TEMPLATE.format(
  500. node_id=xml_escape(node.get('id')),
  501. name=xml_escape(node.get('name')),
  502. type=xml_escape(node.get('type')),
  503. org_name=xml_escape(node.get('orgName')),
  504. operator_name=xml_escape(node.get('operatorName')),
  505. created_time=xml_escape(node.get('createdTime')),
  506. operate_time=xml_escape(node.get('operateTime')),
  507. opinion=xml_escape(node.get('opinion')),
  508. conclusion=xml_escape(node.get('conclusion')),
  509. )
  510. for node in process_nodes
  511. )
  512. return " <审核过程>\n" + node_xml + "\n </审核过程>"
  513. def xml_escape(value):
  514. if value is None:
  515. return ''
  516. return (str(value)
  517. .replace('&', '&amp;')
  518. .replace('<', '&lt;')
  519. .replace('>', '&gt;'))
  520. def safe_value(value, default=''):
  521. return default if value is None else value
  522. def format_date(value, fmt='%Y-%m-%d'):
  523. if not value:
  524. return ''
  525. if isinstance(value, (datetime.datetime, datetime.date)):
  526. return value.strftime(fmt)
  527. text = str(value).strip()
  528. if not text:
  529. return ''
  530. if len(text) >= 10 and text[4] == '-' and text[7] == '-':
  531. try:
  532. return datetime.datetime.strptime(text[:10], '%Y-%m-%d').strftime(fmt)
  533. except ValueError:
  534. pass
  535. if len(text) >= 8 and text.isdigit():
  536. try:
  537. return datetime.datetime.strptime(text[:8], '%Y%m%d').strftime(fmt)
  538. except ValueError:
  539. pass
  540. return text[:10] if fmt == '%Y-%m-%d' else text
  541. def format_datetime(value):
  542. if not value:
  543. return ''
  544. if isinstance(value, datetime.datetime):
  545. return value.strftime('%Y-%m-%d %H:%M:%S')
  546. text = str(value).strip().replace('T', ' ')
  547. if not text:
  548. return ''
  549. if len(text) >= 19:
  550. return text[:19]
  551. if len(text) == 10:
  552. return text + ' 00:00:00'
  553. return text
  554. def format_amount(value):
  555. if value is None or value == '':
  556. return '0.00'
  557. try:
  558. return f"{Decimal(str(value)).quantize(Decimal('0.01')):.2f}"
  559. except Exception:
  560. return str(value)
  561. def stable_guid(seed):
  562. return uuid.uuid5(uuid.NAMESPACE_URL, str(seed)).hex.upper()
  563. def build_metadata_entities(order_data, file_id):
  564. header = order_data.get('header') or {}
  565. process_nodes = order_data.get('process') or []
  566. business_rows = []
  567. person_rows = []
  568. seen_operators = set()
  569. def add_entity(operator_id, operator_name, org_name, action_time, action, description, basis='', business_id=None):
  570. operator_id = str(operator_id or '').strip()
  571. operator_name = str(operator_name or '').strip()
  572. org_name = str(org_name or '').strip()
  573. action_time = format_datetime(action_time)
  574. if not operator_id or not operator_name or not org_name or not action_time:
  575. return
  576. person_key = (operator_id, org_name)
  577. if person_key not in seen_operators:
  578. person_rows.append({
  579. 'operator_id': operator_id,
  580. 'operator_name': operator_name,
  581. 'org_name': org_name,
  582. })
  583. seen_operators.add(person_key)
  584. business_rows.append({
  585. 'business_id': business_id or stable_guid(f"{file_id}:{operator_id}:{action_time}:{description}"),
  586. 'operator_id': operator_id,
  587. 'file_id': file_id,
  588. 'action_time': action_time,
  589. 'action_basis': basis,
  590. 'action': action or '审批',
  591. 'description': description or '文件审核通过',
  592. 'operator_name': operator_name,
  593. 'org_name': org_name,
  594. })
  595. tabulator_id = header.get('tabulator_id') or order_data.get('tabulator_id') or f"OP{str(order_data.get('id'))[-12:]}"
  596. tabulator_name = header.get('tabulator') or order_data.get('tabulator_name')
  597. tabulation_date = header.get('tabulation_date')
  598. tabulator_org = header.get('tabulator_org') or header.get('contractor') or header.get('section') or ARCHIVE_UNIT
  599. add_entity(
  600. tabulator_id,
  601. tabulator_name,
  602. tabulator_org,
  603. tabulation_date,
  604. '制表',
  605. f"制表;{tabulator_name or ''}文件制表提交;制表时间:{format_datetime(tabulation_date)}".strip(';'),
  606. '计量支付',
  607. business_id=stable_guid(f"{file_id}:tabulator")
  608. )
  609. for node in process_nodes:
  610. operator_id = node.get('operatorId') or node.get('assignee')
  611. operator_name = node.get('operatorName')
  612. org_name = node.get('orgName') or ARCHIVE_UNIT
  613. conclusion = node.get('conclusion') or ''
  614. # 行为依据 = 节点类型(计量支付)
  615. basis = node.get('type') or '计量支付'
  616. # 行为描述 = 节点名称 | 意见 | 结论 | 办理时间 | 创建时间(空值自动跳过)
  617. desc_parts = [
  618. node.get('name') or '审批节点',
  619. node.get('opinion') or '',
  620. f"结论:{conclusion}" if conclusion else '',
  621. f"办理时间:{format_datetime(node.get('operateTime'))}" if node.get('operateTime') else '',
  622. f"创建时间:{format_datetime(node.get('createdTime'))}" if node.get('createdTime') else '',
  623. ]
  624. description = ';'.join(p for p in desc_parts if p)
  625. add_entity(
  626. operator_id,
  627. operator_name,
  628. org_name,
  629. node.get('operateTime'),
  630. '审批',
  631. description,
  632. basis,
  633. stable_guid(f"{file_id}:{node.get('id') or node.get('taskId') or node.get('operatorId')}")
  634. )
  635. if not business_rows:
  636. fallback_id = tabulator_id or f"OP{str(order_data.get('id'))[-12:]}"
  637. fallback_name = tabulator_name or '系统管理员'
  638. fallback_org = tabulator_org
  639. fallback_time = tabulation_date or datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
  640. add_entity(fallback_id, fallback_name, fallback_org, fallback_time, '审批', f"{fallback_name}文件审核通过", business_id=stable_guid(f"{file_id}:fallback"))
  641. business_xml = "\n".join(
  642. XML_BUSINESS_ENTITY_TEMPLATE.format(**{k: xml_escape(v) for k, v in row.items()})
  643. for row in business_rows
  644. )
  645. person_xml = "\n".join(
  646. XML_PERSON_ENTITY_TEMPLATE.format(**{k: xml_escape(v) for k, v in row.items()})
  647. for row in person_rows
  648. )
  649. if person_rows:
  650. relation_xml = "\n".join(
  651. XML_PERSON_RELATION_TEMPLATE.format(operator_id=xml_escape(row['operator_id']))
  652. for row in person_rows
  653. )
  654. person_xml = person_xml + "\n" + relation_xml
  655. return business_xml, person_xml
  656. def init_sqlite():
  657. db_parent = os.path.dirname(SQLITE_DB)
  658. if db_parent and not os.path.exists(db_parent):
  659. os.makedirs(db_parent)
  660. conn = sqlite3.connect(SQLITE_DB)
  661. cursor = conn.cursor()
  662. # 计量单表
  663. cursor.execute('''
  664. CREATE TABLE IF NOT EXISTS measure_orders (
  665. id TEXT PRIMARY KEY,
  666. measure_number TEXT,
  667. status INTEGER,
  668. sync_status INTEGER DEFAULT 0,
  669. data_json TEXT,
  670. created_at TIMESTAMP
  671. )
  672. ''')
  673. # 附件表
  674. cursor.execute('''
  675. CREATE TABLE IF NOT EXISTS attachments (
  676. id TEXT PRIMARY KEY,
  677. measure_order_id TEXT,
  678. file_name TEXT,
  679. file_url TEXT,
  680. sync_status INTEGER DEFAULT 0
  681. )
  682. ''')
  683. conn.commit()
  684. return conn
  685. def fetch_from_mysql():
  686. try:
  687. print(f"Connecting to MySQL {DB_CONFIG['host']}...")
  688. conn = mysql.connector.connect(**DB_CONFIG)
  689. cursor = conn.cursor(dictionary=True)
  690. # 1. 获取已完成的施工计量单 (status=2 or 4)
  691. print("Fetching measure orders...")
  692. # status=2 (audited) 是已完成, status=4 also seen in completed orders
  693. query_orders = """
  694. SELECT *
  695. FROM mp_measure_order
  696. WHERE status IN (2, 4) AND is_deleted = 0
  697. ORDER BY id DESC
  698. LIMIT 1000
  699. """
  700. # 加 LIMIT 是为了测试方便,生产环境可以去掉
  701. cursor.execute(query_orders)
  702. orders = cursor.fetchall()
  703. print(f"Found {len(orders)} completed orders.")
  704. order_data_list = []
  705. for order in orders:
  706. order_id = str(order['id'])
  707. # 2. 获取关联的合同信息
  708. contract = None
  709. if order.get('mp_contract_id'):
  710. cursor.execute("SELECT * FROM mp_contract WHERE id = %s", (order['mp_contract_id'],))
  711. contract = cursor.fetchone()
  712. # 3. 获取其他支付项 (mp_construction_measure_others)
  713. cursor.execute("SELECT * FROM mp_construction_measure_others WHERE mp_construction_measure_id = %s AND is_deleted = 0", (order_id,))
  714. others = cursor.fetchall()
  715. tabulator_name = None
  716. tabulator_id = str(order.get('tabulator') or '')
  717. tabulator_org = None
  718. if order.get('tabulator'):
  719. cursor.execute("""
  720. SELECT u.id, u.account, u.real_name, d.full_name AS org_name
  721. FROM blade_user u
  722. LEFT JOIN blade_dept d ON FIND_IN_SET(d.id, u.dept_id) AND d.is_deleted = 0
  723. WHERE u.id = %s AND u.is_deleted = 0
  724. LIMIT 1
  725. """, (order['tabulator'],))
  726. user_row = cursor.fetchone()
  727. if user_row:
  728. tabulator_name = user_row['real_name']
  729. tabulator_id = str(user_row.get('id') or order.get('tabulator') or '')
  730. tabulator_org = user_row.get('org_name')
  731. # 5. 获取附件
  732. # 关联 mp_measure_attachments 和 tb_file (corrected from blade_attach)
  733. query_attachments = """
  734. SELECT a.id, a.mp_measure_id, a.sort, f.file_title as name, f.path as link, f.file_hash, f.create_time AS file_create_time
  735. FROM mp_measure_attachments a
  736. JOIN tb_file f ON a.file_id = f.id
  737. WHERE a.mp_measure_id = %s AND a.is_deleted = 0 AND f.is_deleted = 0
  738. ORDER BY a.sort, a.id
  739. """
  740. cursor.execute(query_attachments, (order_id,))
  741. attachments = cursor.fetchall()
  742. # 6. 获取审核过程 (流程节点)
  743. process_nodes = fetch_flow_nodes(cursor, order.get('flow_process_inst_id'))
  744. # 格式化附件数据
  745. attachment_list = []
  746. for att in attachments:
  747. url = att['link']
  748. # tb_file path is usually full url
  749. attachment_list.append({
  750. 'id': str(att['id']),
  751. 'name': att['name'],
  752. 'url': url,
  753. 'hash': att.get('file_hash') or '',
  754. 'fileCreateTime': att.get('file_create_time').isoformat() if isinstance(att.get('file_create_time'), (datetime.date, datetime.datetime)) else att.get('file_create_time')
  755. })
  756. # Helper to serialize date/decimal
  757. def serialize_row(row):
  758. if not row: return None
  759. new_row = {}
  760. for k, v in row.items():
  761. if isinstance(v, (datetime.date, datetime.datetime)):
  762. new_row[k] = v.isoformat()
  763. elif isinstance(v, Decimal):
  764. new_row[k] = float(v) # Or str(v) if precision is critical
  765. elif isinstance(v, (bytes, bytearray)):
  766. try:
  767. new_row[k] = v.decode('utf-8')
  768. except:
  769. new_row[k] = str(v) # Fallback
  770. elif isinstance(v, (set)):
  771. new_row[k] = list(v)
  772. else:
  773. new_row[k] = v
  774. return new_row
  775. # Serialize all data
  776. order_data = serialize_row(order)
  777. contract_data = serialize_row(contract) if contract else {}
  778. others_data = [serialize_row(x) for x in others]
  779. # Construct simplified structure matching screenshot
  780. # Helper to find amount in others
  781. def get_other_amount(name_key):
  782. for item in others_data:
  783. if item.get('name') == name_key:
  784. return float(item.get('construction_measure_amount') or 0)
  785. return 0.0
  786. subtotal = float(order.get('current_period_amount') or 0)
  787. price_adjustment = get_other_amount('价格调整')
  788. deduction_advance = get_other_amount('扣回材料设备预付款') # Or 扣回开工预付款? Screenshot says Material/Equipment
  789. # Total in screenshot = Subtotal + Price Adjustment (approx logic)
  790. # Or is it Subtotal - Deductions?
  791. # Screenshot:
  792. # Subtotal: -110,981,615.25
  793. # Adj: 123,456.00
  794. # Total: -110,858,159.25 (-110981615.25 + 123456.00 = -110858159.25)
  795. # So Total = Subtotal + Price Adjustment
  796. total_amount = subtotal + price_adjustment
  797. # Proposed Payment
  798. # Screenshot: Total (-110,858,159.25) - Deduction (-2,233,331,437.00) = ... wait
  799. # -110M - (-2233M) = +2122M. But result is -2344M.
  800. # -110M + (-2233M) = -2344M.
  801. # So Proposed Payment = Total + Deduction (if deduction is negative)
  802. # Or Proposed Payment = Total - Deduction (if deduction is positive)
  803. # In DB, '扣回...' amount might be stored as positive or negative.
  804. # We will just fetch the values. Calculation logic is secondary, primary is data availability.
  805. # Flattened Header Info
  806. header_info = {
  807. 'measure_no': order.get('measure_no'),
  808. 'measure_period': order.get('end_date').strftime('%Y%m') if order.get('end_date') else None,
  809. 'section': contract.get('section_id') if contract else None,
  810. 'measure_method': '分解计量',
  811. 'employer': contract.get('employer') if contract else None,
  812. 'contractor': order.get('construct_dept') or (contract.get('contractor_dept') if contract else None),
  813. 'supervisor': contract.get('jl_section') if contract else None,
  814. 'period_start': order.get('start_date').isoformat() if order.get('start_date') else None,
  815. 'period_end': order.get('end_date').isoformat() if order.get('end_date') else None,
  816. 'tabulation_date': order.get('tabulation_time').isoformat() if order.get('tabulation_time') else None,
  817. 'tabulator_id': tabulator_id,
  818. 'tabulator': tabulator_name,
  819. 'tabulator_org': tabulator_org
  820. }
  821. # Statistics Info
  822. statistics_info = {
  823. 'subtotal': subtotal,
  824. 'price_adjustment': price_adjustment,
  825. 'total': total_amount,
  826. 'deduction_material_advance': deduction_advance,
  827. 'proposed_payment': float(order.get('end_current_period_amount') or 0) - float(order.get('end_last_period_amount') or 0), # Best guess or specific field
  828. # Actually, let's just dump the relevant others rows to be safe if exact mapping is tricky
  829. 'others_details': [{'name': x['name'], 'amount': float(x['construction_measure_amount'] or 0)} for x in others_data if x['construction_measure_amount'] != 0],
  830. 'completed_last_period': float(order.get('end_last_period_amount') or 0),
  831. 'completed_cumulative': float(order.get('end_current_period_amount') or 0)
  832. }
  833. order_data_list.append({
  834. 'id': str(order['id']), # Keep ID for internal use
  835. 'measure_number': order.get('measure_number'), # Keep for internal use
  836. 'status': order.get('status'), # Keep for internal use
  837. 'header': header_info,
  838. 'statistics': statistics_info,
  839. 'attachments': attachment_list,
  840. 'process': process_nodes
  841. })
  842. cursor.close()
  843. conn.close()
  844. return order_data_list
  845. except mysql.connector.Error as err:
  846. print(f"MySQL Error: {err}")
  847. return None
  848. except Exception as e:
  849. print(f"Error: {e}")
  850. return None
  851. def cache_data(sqlite_conn, data_list):
  852. if not data_list:
  853. return
  854. cursor = sqlite_conn.cursor()
  855. count_new = 0
  856. count_updated = 0
  857. for item in data_list:
  858. # Filter by section name
  859. section_name = item.get('header', {}).get('section', '')
  860. # Ensure section_name is a string before checking
  861. if section_name is None:
  862. section_name = ''
  863. else:
  864. section_name = str(section_name)
  865. if not any(keyword in section_name for keyword in ['CS', 'ZJG', 'TC']):
  866. continue
  867. order_id = item['id']
  868. measure_number = item['measure_number']
  869. status = item['status']
  870. attachments = item['attachments']
  871. # 检查是否存在
  872. cursor.execute("SELECT id FROM measure_orders WHERE id = ?", (order_id,))
  873. exists = cursor.fetchone()
  874. # Create a clean data object for JSON storage (exclude internal fields if desired, or keep them)
  875. # We'll store the whole item as JSON for simplicity, it contains header and statistics.
  876. json_str = json.dumps(item, ensure_ascii=False)
  877. if not exists:
  878. cursor.execute('''
  879. INSERT INTO measure_orders (id, measure_number, status, data_json, created_at)
  880. VALUES (?, ?, ?, ?, ?)
  881. ''', (order_id, measure_number, status, json_str, datetime.datetime.now()))
  882. count_new += 1
  883. else:
  884. # Update data and reset sync_status to 0 to ensure updated data is synced
  885. # cursor.execute('''
  886. # UPDATE measure_orders SET data_json = ?, sync_status = 0 WHERE id = ?
  887. # ''', (json_str, order_id))
  888. # count_updated += 1
  889. continue
  890. # 存储附件信息
  891. for att in attachments:
  892. cursor.execute("SELECT id FROM attachments WHERE id = ?", (att['id'],))
  893. att_exists = cursor.fetchone()
  894. if not att_exists:
  895. cursor.execute('''
  896. INSERT INTO attachments (id, measure_order_id, file_name, file_url)
  897. VALUES (?, ?, ?, ?)
  898. ''', (att['id'], order_id, att['name'], att['url']))
  899. sqlite_conn.commit()
  900. print(f"Cached: {count_new} new, {count_updated} updated.")
  901. def get_file_md5(filepath):
  902. hash_md5 = hashlib.md5()
  903. with open(filepath, "rb") as f:
  904. for chunk in iter(lambda: f.read(4096), b""):
  905. hash_md5.update(chunk)
  906. return hash_md5.hexdigest()
  907. def download_file(url, dest_path):
  908. # Try to ensure URL is valid
  909. if not url.startswith('http'):
  910. # If url is like /profile/upload/..., append base
  911. if url.startswith('/'):
  912. url = FILE_BASE_URL + url
  913. else:
  914. url = FILE_BASE_URL + '/' + url
  915. print(f"Downloading {url} to {dest_path}...")
  916. try:
  917. parsed_url = urlparse(url)
  918. hostname = parsed_url.netloc
  919. path = parsed_url.path
  920. if parsed_url.query:
  921. path += '?' + parsed_url.query
  922. headers = {
  923. 'User-Agent': 'Apifox/1.0.0 (https://apifox.com)',
  924. 'Accept': '*/*',
  925. 'Host': hostname,
  926. 'Connection': 'keep-alive'
  927. }
  928. conn = None
  929. if parsed_url.scheme == 'https':
  930. conn = http.client.HTTPSConnection(hostname)
  931. else:
  932. conn = http.client.HTTPConnection(hostname)
  933. conn.request("GET", path, '', headers)
  934. res = conn.getresponse()
  935. # Log response details for debugging
  936. print(f" Response Status: {res.status}")
  937. print(f" Content-Type: {res.getheader('Content-Type')}")
  938. print(f" Content-Length: {res.getheader('Content-Length')}")
  939. if res.status == 200:
  940. with open(dest_path, 'wb') as f:
  941. while True:
  942. chunk = res.read(8192)
  943. if not chunk:
  944. break
  945. f.write(chunk)
  946. conn.close()
  947. return True
  948. else:
  949. print(f"Failed to download {url}: Status {res.status}")
  950. conn.close()
  951. return False
  952. except Exception as e:
  953. print(f"Exception downloading {url}: {e}")
  954. return False
  955. def create_eep_package(order_data, output_dir='eep_packages'):
  956. order_id = str(order_data['id'])
  957. archive_id = order_id
  958. header = order_data.get('header') or {}
  959. statistics = order_data.get('statistics') or {}
  960. measure_no = header.get('measure_no') or ''
  961. title = f"计量单-{measure_no}"
  962. tabulation_raw = header.get('tabulation_date')
  963. period_end_raw = header.get('period_end')
  964. current_period = header.get('measure_period') or format_date(period_end_raw, '%Y%m')
  965. tabulator_id = header.get('tabulator_id') or f"OP{order_id[-12:]}"
  966. if not current_period and measure_no and len(measure_no.split('-')) >= 2:
  967. current_period = measure_no.split('-')[-2]
  968. year_source = tabulation_raw or period_end_raw
  969. year = int(format_date(year_source, '%Y') or datetime.datetime.now().year)
  970. date_str = format_date(tabulation_raw) or datetime.datetime.now().strftime('%Y-%m-%d')
  971. date_compact = format_date(tabulation_raw, '%Y%m%d') or datetime.datetime.now().strftime('%Y%m%d')
  972. file_id = stable_guid(f"file:{archive_id}")
  973. # Clean output dir for this order
  974. pkg_root = os.path.join(output_dir, archive_id)
  975. if os.path.exists(pkg_root):
  976. shutil.rmtree(pkg_root)
  977. os.makedirs(pkg_root)
  978. # Directory structure
  979. archive_dir = os.path.join(pkg_root, '电子档案', str(year), archive_id)
  980. os.makedirs(archive_dir)
  981. # Download attachments
  982. files_info = []
  983. attachments = order_data.get('attachments', [])
  984. for att in attachments:
  985. fname = att['name']
  986. furl = att['url']
  987. if not fname or not furl: continue
  988. fname = os.path.basename(fname)
  989. local_path = os.path.join(archive_dir, fname)
  990. if download_file(furl, local_path):
  991. fsize = os.path.getsize(local_path)
  992. fmd5 = get_file_md5(local_path)
  993. fext = os.path.splitext(fname)[1].lstrip('.')
  994. files_info.append({
  995. 'name': fname,
  996. 'path': f'电子档案/{year}/{archive_id}/{fname}',
  997. 'real_path': local_path,
  998. 'size': fsize,
  999. 'md5': (att.get('hash') or fmd5).lower(),
  1000. 'ext': fext,
  1001. 'type': '附件',
  1002. 'created': att.get('fileCreateTime') or tabulation_raw or date_str
  1003. })
  1004. # Calculate total size
  1005. total_size = sum(f['size'] for f in files_info)
  1006. # Generate XMLs
  1007. # 1. 说明文件.xml
  1008. desc_xml = XML_DESC_TEMPLATE.format(
  1009. archive_id=archive_id,
  1010. size=total_size,
  1011. date=date_str,
  1012. year=year,
  1013. file_count=len(files_info),
  1014. process_xml=build_process_xml(order_data.get('process') or [])
  1015. )
  1016. with open(os.path.join(pkg_root, '说明文件.xml'), 'w', encoding='utf-8') as f:
  1017. f.write(desc_xml)
  1018. # 2. 文件目录.xml
  1019. file_details_xml = ""
  1020. for f in files_info:
  1021. file_details_xml += XML_FILE_DETAIL_TEMPLATE.format(
  1022. path=f"电子档案/{year}/{archive_id}/{f['name']}",
  1023. size=f['size'],
  1024. md5=f['md5'],
  1025. name=f['name'],
  1026. type=f['type']
  1027. ) + "\n"
  1028. catalog_values = {
  1029. 'doc_num': measure_no,
  1030. 'title': title,
  1031. 'date': date_str,
  1032. 'date_compact': date_compact,
  1033. 'archive_id': archive_id,
  1034. 'year': year,
  1035. 'file_details': file_details_xml,
  1036. 'signing_unit': CATALOG_SIGNING_UNIT,
  1037. 'current_period': current_period,
  1038. 'measure_number': header.get('measure_no') or '',
  1039. 'period_start': format_date(header.get('period_start')),
  1040. 'period_end': format_date(header.get('period_end')),
  1041. 'tabulator_id': tabulator_id,
  1042. 'tabulator_name': header.get('tabulator') or '',
  1043. 'tabulation_date': format_date(tabulation_raw),
  1044. 'completed_last_period': format_amount(statistics.get('completed_last_period')),
  1045. 'current_period_amount': format_amount(statistics.get('subtotal')),
  1046. 'completed_cumulative': format_amount(statistics.get('completed_cumulative')),
  1047. }
  1048. catalog_xml = XML_CATALOG_TEMPLATE.format(**{key: xml_escape(value) if key != 'file_details' else value for key, value in catalog_values.items()})
  1049. with open(os.path.join(pkg_root, '文件目录.xml'), 'w', encoding='utf-8') as f:
  1050. f.write(catalog_xml)
  1051. # 3. 文件元数据.xml
  1052. docs_xml = ""
  1053. for file_info in files_info:
  1054. doc_values = {
  1055. 'date': date_str,
  1056. 'md5': file_info['md5'],
  1057. 'ext': file_info['ext'],
  1058. 'filename': file_info['name'],
  1059. 'size': file_info['size'],
  1060. 'date_compact': format_date(file_info.get('created'), '%Y%m%d') or date_compact,
  1061. 'doc_title': file_info['name'],
  1062. 'path': file_info['path'],
  1063. }
  1064. docs_xml += XML_DOC_TEMPLATE.format(**{key: xml_escape(value) for key, value in doc_values.items()}) + "\n"
  1065. business_entities_xml, person_entities_xml = build_metadata_entities(order_data, file_id)
  1066. metadata_values = {
  1067. 'date': date_str,
  1068. 'year': year,
  1069. 'title': title,
  1070. 'date_compact': date_compact,
  1071. 'docs': docs_xml,
  1072. 'file_id': file_id,
  1073. 'archive_unit': ARCHIVE_UNIT,
  1074. 'business_entities_xml': business_entities_xml,
  1075. 'person_entities_xml': person_entities_xml,
  1076. }
  1077. metadata_xml = XML_METADATA_TEMPLATE.format(**{key: value if key in {'docs', 'business_entities_xml', 'person_entities_xml'} else xml_escape(value) for key, value in metadata_values.items()})
  1078. with open(os.path.join(archive_dir, '文件元数据.xml'), 'w', encoding='utf-8') as f:
  1079. f.write(metadata_xml)
  1080. # Zip it
  1081. eep_filename = f"{archive_id}.eep"
  1082. eep_path = os.path.join(output_dir, eep_filename)
  1083. with zipfile.ZipFile(eep_path, 'w', zipfile.ZIP_DEFLATED) as zf:
  1084. for root, dirs, files in os.walk(pkg_root):
  1085. for file in files:
  1086. abs_path = os.path.join(root, file)
  1087. rel_path = os.path.relpath(abs_path, output_dir)
  1088. zf.write(abs_path, rel_path)
  1089. return eep_path, files_info
  1090. import copy
  1091. def upload_eep_package(eep_path, order_data, files_info):
  1092. archive_id = str(order_data['id'])
  1093. eep_size = os.path.getsize(eep_path)
  1094. eep_md5 = get_file_md5(eep_path)
  1095. eep_filename = os.path.basename(f".{eep_path}")
  1096. print(f"eep_filename: {eep_filename}")
  1097. print(f"eep_path: {eep_path}")
  1098. # Read file content for Base64
  1099. with open(eep_path, "rb") as f:
  1100. file_content = f.read()
  1101. base64_str = base64.b64encode(file_content).decode('utf-8')
  1102. payload = {
  1103. "data": {
  1104. "syscode": "HWKJLZF",
  1105. "businesscode": "HWKJLZF",
  1106. "id": archive_id
  1107. },
  1108. "files": [
  1109. {
  1110. "id": archive_id,
  1111. "path": '',
  1112. "filename": eep_filename,
  1113. "ext": ".eep",
  1114. "size": eep_size,
  1115. "md5code": eep_md5,
  1116. "fjsize": len(files_info),
  1117. "pathtype": "4", # Base64
  1118. "base64": base64_str
  1119. }
  1120. ]
  1121. }
  1122. # Print JSON (truncate base64 for readability)
  1123. # log_payload = copy.deepcopy(payload)
  1124. # for f in log_payload['files']:
  1125. # if 'base64' in f:
  1126. # f['base64'] = f['base64'][:100] + '... (truncated)'
  1127. # print(f"\n[DEBUG] JSON Payload for {eep_filename}:")
  1128. # print(json.dumps(log_payload, indent=2, ensure_ascii=False))
  1129. # print(f"Skipping actual upload for {eep_filename}...")
  1130. # return False
  1131. print(f"Uploading {eep_filename} (Size: {eep_size}, MD5: {eep_md5})...")
  1132. try:
  1133. headers = {'Content-Type': 'application/json'}
  1134. response = requests.post(API_URL, json=payload, headers=headers, timeout=60)
  1135. print(f"Upload Response: {response.text}")
  1136. if response.status_code == 200:
  1137. res_json = response.json()
  1138. if res_json.get('success'):
  1139. return True
  1140. else:
  1141. print(f"API returned failure: {res_json.get('message')}")
  1142. return False
  1143. else:
  1144. print(f"HTTP Error: {response.status_code}")
  1145. return False
  1146. except Exception as e:
  1147. print(f"Upload Exception: {e}")
  1148. return False
  1149. def sync_to_external_system(sqlite_conn):
  1150. cursor = sqlite_conn.cursor()
  1151. # 获取未同步的数据
  1152. cursor.execute("SELECT id, data_json FROM measure_orders WHERE sync_status = 0")
  1153. rows = cursor.fetchall()
  1154. if not rows:
  1155. print("No pending records to sync.")
  1156. return
  1157. print(f"Syncing {len(rows)} records to external system...")
  1158. # Create output directory
  1159. output_dir = OUTPUT_DIR
  1160. if not os.path.exists(output_dir):
  1161. os.makedirs(output_dir)
  1162. for row in rows:
  1163. order_id = row[0]
  1164. data_json = row[1]
  1165. # if order_id == '2005072020533338113':
  1166. # print(f"Debug: {order_id}")
  1167. # else:
  1168. # continue
  1169. data = json.loads(data_json)
  1170. try:
  1171. print(f"Processing order {data.get('header', {}).get('measure_no', 'Unknown')} (ID: {order_id})...")
  1172. # 1. Generate EEP Package
  1173. eep_path, files_info = create_eep_package(data, output_dir)
  1174. # 2. Upload EEP Package
  1175. if upload_eep_package(eep_path, data, files_info):
  1176. # 3. Update Sync Status
  1177. cursor.execute("UPDATE measure_orders SET sync_status = 1 WHERE id = ?", (order_id,))
  1178. sqlite_conn.commit() # 立即提交事务
  1179. print(f"Order {order_id} synced successfully.")
  1180. else:
  1181. print(f"Failed to upload order {order_id}.")
  1182. except Exception as e:
  1183. print(f"Failed to sync order {order_id}: {e}")
  1184. import traceback
  1185. traceback.print_exc()
  1186. sqlite_conn.commit()
  1187. print("Sync completed.")
  1188. if __name__ == "__main__":
  1189. print(f"配置文件: {CONFIG_FILE}")
  1190. print(f"MySQL: {DB_CONFIG['user']}@{DB_CONFIG['host']}:{DB_CONFIG['port']}/{DB_CONFIG['database']}")
  1191. print(f"本地缓存: {SQLITE_DB}")
  1192. print()
  1193. sqlite_conn = init_sqlite()
  1194. print("Fetching data from MySQL...")
  1195. data = fetch_from_mysql()
  1196. if data is not None:
  1197. print(f"Caching {len(data)} records...")
  1198. cache_data(sqlite_conn, data)
  1199. # Print sample structure
  1200. if len(data) > 0:
  1201. sample = data[0]
  1202. print("\nSample Data Structure Cached:")
  1203. print(f"Header Keys: {list(sample['header'].keys())}")
  1204. print(f"Statistics Keys: {list(sample['statistics'].keys())}")
  1205. print(f"Attachments Count: {len(sample['attachments'])}")
  1206. sync_to_external_system(sqlite_conn)
  1207. else:
  1208. print("Failed to fetch data from MySQL. Please check your connection settings.")
  1209. sqlite_conn.close()