sync_measure_data.py 47 KB

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