sync_measure_data.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788
  1. import mysql.connector
  2. import sqlite3
  3. import json
  4. import os
  5. import datetime
  6. import time
  7. import requests
  8. import http.client
  9. from urllib.parse import urlparse
  10. import shutil
  11. import hashlib
  12. import zipfile
  13. import base64
  14. from decimal import Decimal
  15. # 数据库配置 (从 application-dev.yml 获取)
  16. # 如果连接失败,请检查 VPN 或修改此处的 host/port/user/password
  17. DB_CONFIG = {
  18. 'user': 'root',
  19. 'password': '84853032',
  20. 'host': '47.99.60.80',
  21. 'port': 3306,
  22. 'database': '2022hs060',
  23. 'use_pure': True,
  24. 'connect_timeout': 5
  25. }
  26. # 目标API配置
  27. API_URL = "http://218.94.73.106:8081/api/eps9/tyjk/api/data/asip/HWKJLZF"
  28. FILE_BASE_URL = "https://oss.dnnbuild.com" # 猜测的文件下载基地址
  29. # XML 模板
  30. XML_DESC_TEMPLATE = """<?xml version="1.0" encoding="UTF-8"?>
  31. <文件说明>
  32. <载体编号>{archive_id}</载体编号>
  33. <载体类型>在线</载体类型>
  34. <载体容量>{size}</载体容量>
  35. <制作时间>{date}</制作时间>
  36. <载体制作单位名称>沪武高速公路太仓至常州段扩建工程苏州段</载体制作单位名称>
  37. <载体保管单位名称>沪武高速公路太仓至常州段扩建工程苏州段</载体保管单位名称>
  38. <载体检查单位名称>沪武高速公路太仓至常州段扩建工程苏州段</载体检查单位名称>
  39. <载体申请单位名称>沪武高速公路太仓至常州段扩建工程苏州段</载体申请单位名称>
  40. <年度>{year}</年度>
  41. <归档文件数量>{file_count}</归档文件数量>
  42. <归档类型>文件</归档类型>
  43. <起始件号></起始件号>
  44. <截至件号></截至件号>
  45. <信息系统名称>档案综合利用平台</信息系统名称>
  46. </文件说明>"""
  47. XML_CATALOG_TEMPLATE = """<?xml version="1.0" encoding="UTF-8"?>
  48. <文件目录>
  49. <归档文件>
  50. <处理部门></处理部门>
  51. <公文标识></公文标识>
  52. <文件类型>发文</文件类型>
  53. <份号></份号>
  54. <密级和保密期限>普通</密级和保密期限>
  55. <紧急程度>内部资料</紧急程度>
  56. <发文机关标志></发文机关标志>
  57. <发文字号>{doc_num}</发文字号>
  58. <签发人>null</签发人>
  59. <标题>{title}</标题>
  60. <主送机关></主送机关>
  61. <附件说明></附件说明>
  62. <发文机关或签发人署名>沪武高速公路太仓至常州段扩建工程苏州段</发文机关或签发人署名>
  63. <成文日期>{date_compact}</成文日期>
  64. <附注></附注>
  65. <抄送机关></抄送机关>
  66. <印发机关></印发机关>
  67. <印发日期></印发日期>
  68. <发布层次></发布层次>
  69. <档号>{archive_id}</档号>
  70. <年度>{year}</年度>
  71. <保管期限></保管期限>
  72. <机构或问题></机构或问题>
  73. <件号></件号>
  74. <数字对象标识></数字对象标识>
  75. <环境信息></环境信息>
  76. <软件环境></软件环境>
  77. <硬件环境></硬件环境>
  78. <处理类型></处理类型>
  79. <处理者></处理者>
  80. <处理时间></处理时间>
  81. <处理结果></处理结果>
  82. <文件>
  83. {file_details}
  84. </文件>
  85. </归档文件>
  86. </文件目录>"""
  87. XML_FILE_DETAIL_TEMPLATE = """ <文件详情>
  88. <文件路径>{path}</文件路径>
  89. <文件大小>{size}</文件大小>
  90. <数字摘要>{md5}</数字摘要>
  91. <文件单位>B</文件单位>
  92. <文件名称>{name}</文件名称>
  93. <文件类型>{type}</文件类型>
  94. </文件详情>"""
  95. XML_METADATA_TEMPLATE = """<?xml version="1.0" encoding="UTF-8"?>
  96. <电子文件封装包 name="M201">
  97. <封装包格式描述 name="M202">本EEP根据中华人民共和国档案行业标准DA/T 48-2009《基于XML的电子文件封装规范》生成</封装包格式描述>
  98. <版本 name="M203">2009</版本>
  99. <被签名对象 name="M204">
  100. <封装包类型 name="M205" />
  101. <封装包类型描述 name="M206" />
  102. <封装包创建时间 name="M207">{date}</封装包创建时间>
  103. <封装包创建单位 name="M208">沪武高速公路太仓至常州段扩建工程苏州段</封装包创建单位>
  104. <封装内容 name="M209">
  105. <文件实体块 name="M210">
  106. <文件实体 name="M211">
  107. <聚合层次 name="M1" />
  108. <来源 name="M2">
  109. <档案馆名称 name="M3">xx</档案馆名称>
  110. <档案馆代码 name="M4" />
  111. <全宗名称 name="M5">沪武高速公路太仓至常州段扩建工程苏州段</全宗名称>
  112. <立档单位名称 name="M6">沪武高速公路太仓至常州段扩建工程苏州段</立档单位名称>
  113. </来源>
  114. <电子文件号 name="M7" />
  115. <档号 name="M8">
  116. <全宗号 name="M9">XYK</全宗号>
  117. <目录号 name="M10" />
  118. <年度 name="M11">{year}</年度>
  119. <保管期限 name="M12">永久</保管期限>
  120. <机构或问题 name="M13" />
  121. <类别号 name="M14" />
  122. <室编案卷号 name="M15" />
  123. <馆编案卷号 name="M16" />
  124. <室编件号 name="M17" />
  125. <文档序号 name="M19" />
  126. <页号 name="M20" />
  127. </档号>
  128. <内容描述 name="M21">
  129. <题名 name="M22">{title}</题名>
  130. <并列题名 name="M23" />
  131. <副题名 name="M24" />
  132. <说明题名文字 name="M25" />
  133. <主题词 name="M26" />
  134. <关键词 name="M27" />
  135. <人名 name="M28" />
  136. <摘要 name="M29" />
  137. <分类号 name="M30" />
  138. <文件编号 name="M31" />
  139. <责任者 name="M32" />
  140. <日期 name="M33">{date}</日期>
  141. <文种 name="M34" />
  142. <紧急程度 name="M35" />
  143. <主送 name="M36" />
  144. <抄送 name="M37" />
  145. <密级 name="M38" />
  146. <保管期限 name="M39" />
  147. </内容描述>
  148. <形式特征 name="M41">
  149. <文件组合类型 name="M42" />
  150. <件数 name="M43" />
  151. <页数 name="M44" />
  152. <语种 name="M45" />
  153. <稿本 name="M46" />
  154. </形式特征>
  155. <附注 name="M75" />
  156. <文件数据 name="M213">
  157. {docs}
  158. </文件数据>
  159. </文件实体>
  160. </文件实体块>
  161. </封装内容>
  162. </被签名对象>
  163. </电子文件封装包>"""
  164. XML_DOC_TEMPLATE = """ <文档>
  165. <文档标识符 name="M215">{md5}</文档标识符>
  166. <文档序号 name="M19" />
  167. <文档主从声明 name="M216" />
  168. <题名 name="M22"/>
  169. <文档数据 name="M217">
  170. <编码 name="M218">
  171. <电子属性 name="M46">
  172. <格式信息 name="M47">{ext}</格式信息>
  173. <计算机文件名 name="M48">{filename}</计算机文件名>
  174. <计算机文件大小 name="M49">{size}</计算机文件大小>
  175. <文档创建程序 name="M50" />
  176. <信息系统描述 name="M51" />
  177. <计算机文件创建时间 name="M101">{date}</计算机文件创建时间>
  178. </电子属性>
  179. <数字化属性 name="M52">
  180. <数字化对象形态 name="M53" />
  181. <扫描分辨率 name="M54" />
  182. <扫描色彩模式 name="M55" />
  183. <图像压缩方案 name="M56" />
  184. </数字化属性>
  185. <编码描述 name="M219" />
  186. <反编码关键字 name="M220" />
  187. <编码数据 name="M221" />
  188. </编码>
  189. <电子签名 name="M57">
  190. <签名规则 name="M58" />
  191. <签名时间 name="M59" />
  192. <签名人 name="M60" />
  193. <签名结果 name="M61" />
  194. <签名算法标识 name="M64" />
  195. </电子签名>
  196. <存储位置 name="M65">
  197. <当前位置 name="M66" />
  198. <脱机载体编号 name="M67" />
  199. <脱机载体存址 name="M68" />
  200. <缩微号 name="M69" />
  201. </存储位置>
  202. </文档数据>
  203. </文档>"""
  204. # 本地缓存文件
  205. SQLITE_DB = 'measure_data_cache.db'
  206. def init_sqlite():
  207. conn = sqlite3.connect(SQLITE_DB)
  208. cursor = conn.cursor()
  209. # 计量单表
  210. cursor.execute('''
  211. CREATE TABLE IF NOT EXISTS measure_orders (
  212. id TEXT PRIMARY KEY,
  213. measure_number TEXT,
  214. status INTEGER,
  215. sync_status INTEGER DEFAULT 0,
  216. data_json TEXT,
  217. created_at TIMESTAMP
  218. )
  219. ''')
  220. # 附件表
  221. cursor.execute('''
  222. CREATE TABLE IF NOT EXISTS attachments (
  223. id TEXT PRIMARY KEY,
  224. measure_order_id TEXT,
  225. file_name TEXT,
  226. file_url TEXT,
  227. sync_status INTEGER DEFAULT 0
  228. )
  229. ''')
  230. conn.commit()
  231. return conn
  232. def fetch_from_mysql():
  233. try:
  234. print(f"Connecting to MySQL {DB_CONFIG['host']}...")
  235. conn = mysql.connector.connect(**DB_CONFIG)
  236. cursor = conn.cursor(dictionary=True)
  237. # 1. 获取已完成的施工计量单 (status=2 or 4)
  238. print("Fetching measure orders...")
  239. # status=2 (audited) 是已完成, status=4 also seen in completed orders
  240. query_orders = """
  241. SELECT *
  242. FROM mp_measure_order
  243. WHERE status IN (2, 4) AND is_deleted = 0
  244. ORDER BY id DESC
  245. LIMIT 1000
  246. """
  247. # 加 LIMIT 是为了测试方便,生产环境可以去掉
  248. cursor.execute(query_orders)
  249. orders = cursor.fetchall()
  250. print(f"Found {len(orders)} completed orders.")
  251. order_data_list = []
  252. for order in orders:
  253. order_id = str(order['id'])
  254. # 2. 获取关联的合同信息
  255. contract = None
  256. if order.get('mp_contract_id'):
  257. cursor.execute("SELECT * FROM mp_contract WHERE id = %s", (order['mp_contract_id'],))
  258. contract = cursor.fetchone()
  259. # 3. 获取其他支付项 (mp_construction_measure_others)
  260. cursor.execute("SELECT * FROM mp_construction_measure_others WHERE mp_construction_measure_id = %s AND is_deleted = 0", (order_id,))
  261. others = cursor.fetchall()
  262. # 4. 获取 Tabulator Name (blade_user)
  263. tabulator_name = None
  264. if order.get('tabulator'):
  265. cursor.execute("SELECT real_name FROM blade_user WHERE id = %s", (order['tabulator'],))
  266. user_row = cursor.fetchone()
  267. if user_row:
  268. tabulator_name = user_row['real_name']
  269. # 5. 获取附件
  270. # 关联 mp_measure_attachments 和 tb_file (corrected from blade_attach)
  271. query_attachments = """
  272. SELECT a.id, a.mp_measure_id, f.file_title as name, f.path as link
  273. FROM mp_measure_attachments a
  274. JOIN tb_file f ON a.file_id = f.id
  275. WHERE a.mp_measure_id = %s AND a.is_deleted = 0 AND f.is_deleted = 0
  276. """
  277. cursor.execute(query_attachments, (order_id,))
  278. attachments = cursor.fetchall()
  279. # 格式化附件数据
  280. attachment_list = []
  281. for att in attachments:
  282. url = att['link']
  283. # tb_file path is usually full url
  284. attachment_list.append({
  285. 'id': str(att['id']),
  286. 'name': att['name'],
  287. 'url': url
  288. })
  289. # Helper to serialize date/decimal
  290. def serialize_row(row):
  291. if not row: return None
  292. new_row = {}
  293. for k, v in row.items():
  294. if isinstance(v, (datetime.date, datetime.datetime)):
  295. new_row[k] = v.isoformat()
  296. elif isinstance(v, Decimal):
  297. new_row[k] = float(v) # Or str(v) if precision is critical
  298. elif isinstance(v, (bytes, bytearray)):
  299. try:
  300. new_row[k] = v.decode('utf-8')
  301. except:
  302. new_row[k] = str(v) # Fallback
  303. elif isinstance(v, (set)):
  304. new_row[k] = list(v)
  305. else:
  306. new_row[k] = v
  307. return new_row
  308. # Serialize all data
  309. order_data = serialize_row(order)
  310. contract_data = serialize_row(contract) if contract else {}
  311. others_data = [serialize_row(x) for x in others]
  312. # Construct simplified structure matching screenshot
  313. # Helper to find amount in others
  314. def get_other_amount(name_key):
  315. for item in others_data:
  316. if item.get('name') == name_key:
  317. return float(item.get('construction_measure_amount') or 0)
  318. return 0.0
  319. subtotal = float(order.get('current_period_amount') or 0)
  320. price_adjustment = get_other_amount('价格调整')
  321. deduction_advance = get_other_amount('扣回材料设备预付款') # Or 扣回开工预付款? Screenshot says Material/Equipment
  322. # Total in screenshot = Subtotal + Price Adjustment (approx logic)
  323. # Or is it Subtotal - Deductions?
  324. # Screenshot:
  325. # Subtotal: -110,981,615.25
  326. # Adj: 123,456.00
  327. # Total: -110,858,159.25 (-110981615.25 + 123456.00 = -110858159.25)
  328. # So Total = Subtotal + Price Adjustment
  329. total_amount = subtotal + price_adjustment
  330. # Proposed Payment
  331. # Screenshot: Total (-110,858,159.25) - Deduction (-2,233,331,437.00) = ... wait
  332. # -110M - (-2233M) = +2122M. But result is -2344M.
  333. # -110M + (-2233M) = -2344M.
  334. # So Proposed Payment = Total + Deduction (if deduction is negative)
  335. # Or Proposed Payment = Total - Deduction (if deduction is positive)
  336. # In DB, '扣回...' amount might be stored as positive or negative.
  337. # We will just fetch the values. Calculation logic is secondary, primary is data availability.
  338. # Flattened Header Info
  339. header_info = {
  340. 'measure_no': order.get('measure_no'),
  341. 'section': contract.get('section_id') if contract else None, # Assuming section_id holds the name
  342. 'measure_method': '分解计量', # Hardcoded as per screenshot/context
  343. 'employer': contract.get('employer') if contract else None,
  344. 'contractor': order.get('construct_dept') or (contract.get('contractor_dept') if contract else None),
  345. 'supervisor': contract.get('jl_section') if contract else None,
  346. 'period_start': order.get('start_date').isoformat() if order.get('start_date') else None,
  347. 'period_end': order.get('end_date').isoformat() if order.get('end_date') else None,
  348. 'tabulation_date': order.get('tabulation_time').isoformat() if order.get('tabulation_time') else None,
  349. 'tabulator': tabulator_name
  350. }
  351. # Statistics Info
  352. statistics_info = {
  353. 'subtotal': subtotal,
  354. 'price_adjustment': price_adjustment,
  355. 'total': total_amount,
  356. 'deduction_material_advance': deduction_advance,
  357. '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
  358. # Actually, let's just dump the relevant others rows to be safe if exact mapping is tricky
  359. 'others_details': [{'name': x['name'], 'amount': float(x['construction_measure_amount'] or 0)} for x in others_data if x['construction_measure_amount'] != 0],
  360. 'completed_last_period': float(order.get('end_last_period_amount') or 0),
  361. 'completed_cumulative': float(order.get('end_current_period_amount') or 0)
  362. }
  363. order_data_list.append({
  364. 'id': str(order['id']), # Keep ID for internal use
  365. 'measure_number': order.get('measure_number'), # Keep for internal use
  366. 'status': order.get('status'), # Keep for internal use
  367. 'header': header_info,
  368. 'statistics': statistics_info,
  369. 'attachments': attachment_list
  370. })
  371. cursor.close()
  372. conn.close()
  373. return order_data_list
  374. except mysql.connector.Error as err:
  375. print(f"MySQL Error: {err}")
  376. return None
  377. except Exception as e:
  378. print(f"Error: {e}")
  379. return None
  380. def cache_data(sqlite_conn, data_list):
  381. if not data_list:
  382. return
  383. cursor = sqlite_conn.cursor()
  384. count_new = 0
  385. count_updated = 0
  386. for item in data_list:
  387. # Filter by section name
  388. section_name = item.get('header', {}).get('section', '')
  389. # Ensure section_name is a string before checking
  390. if section_name is None:
  391. section_name = ''
  392. else:
  393. section_name = str(section_name)
  394. if not any(keyword in section_name for keyword in ['CS', 'ZJG', 'TC']):
  395. continue
  396. order_id = item['id']
  397. measure_number = item['measure_number']
  398. status = item['status']
  399. attachments = item['attachments']
  400. # 检查是否存在
  401. cursor.execute("SELECT id FROM measure_orders WHERE id = ?", (order_id,))
  402. exists = cursor.fetchone()
  403. # Create a clean data object for JSON storage (exclude internal fields if desired, or keep them)
  404. # We'll store the whole item as JSON for simplicity, it contains header and statistics.
  405. json_str = json.dumps(item, ensure_ascii=False)
  406. if not exists:
  407. cursor.execute('''
  408. INSERT INTO measure_orders (id, measure_number, status, data_json, created_at)
  409. VALUES (?, ?, ?, ?, ?)
  410. ''', (order_id, measure_number, status, json_str, datetime.datetime.now()))
  411. count_new += 1
  412. else:
  413. # Update data and reset sync_status to 0 to ensure updated data is synced
  414. cursor.execute('''
  415. UPDATE measure_orders SET data_json = ?, sync_status = 0 WHERE id = ?
  416. ''', (json_str, order_id))
  417. count_updated += 1
  418. # 存储附件信息
  419. for att in attachments:
  420. cursor.execute("SELECT id FROM attachments WHERE id = ?", (att['id'],))
  421. att_exists = cursor.fetchone()
  422. if not att_exists:
  423. cursor.execute('''
  424. INSERT INTO attachments (id, measure_order_id, file_name, file_url)
  425. VALUES (?, ?, ?, ?)
  426. ''', (att['id'], order_id, att['name'], att['url']))
  427. sqlite_conn.commit()
  428. print(f"Cached: {count_new} new, {count_updated} updated.")
  429. def get_file_md5(filepath):
  430. hash_md5 = hashlib.md5()
  431. with open(filepath, "rb") as f:
  432. for chunk in iter(lambda: f.read(4096), b""):
  433. hash_md5.update(chunk)
  434. return hash_md5.hexdigest()
  435. def download_file(url, dest_path):
  436. # Try to ensure URL is valid
  437. if not url.startswith('http'):
  438. # If url is like /profile/upload/..., append base
  439. if url.startswith('/'):
  440. url = FILE_BASE_URL + url
  441. else:
  442. url = FILE_BASE_URL + '/' + url
  443. print(f"Downloading {url} to {dest_path}...")
  444. try:
  445. parsed_url = urlparse(url)
  446. hostname = parsed_url.netloc
  447. path = parsed_url.path
  448. if parsed_url.query:
  449. path += '?' + parsed_url.query
  450. headers = {
  451. 'User-Agent': 'Apifox/1.0.0 (https://apifox.com)',
  452. 'Accept': '*/*',
  453. 'Host': hostname,
  454. 'Connection': 'keep-alive'
  455. }
  456. conn = None
  457. if parsed_url.scheme == 'https':
  458. conn = http.client.HTTPSConnection(hostname)
  459. else:
  460. conn = http.client.HTTPConnection(hostname)
  461. conn.request("GET", path, '', headers)
  462. res = conn.getresponse()
  463. # Log response details for debugging
  464. print(f" Response Status: {res.status}")
  465. print(f" Content-Type: {res.getheader('Content-Type')}")
  466. print(f" Content-Length: {res.getheader('Content-Length')}")
  467. if res.status == 200:
  468. with open(dest_path, 'wb') as f:
  469. while True:
  470. chunk = res.read(8192)
  471. if not chunk:
  472. break
  473. f.write(chunk)
  474. conn.close()
  475. return True
  476. else:
  477. print(f"Failed to download {url}: Status {res.status}")
  478. conn.close()
  479. return False
  480. except Exception as e:
  481. print(f"Exception downloading {url}: {e}")
  482. return False
  483. def create_eep_package(order_data, output_dir='eep_packages'):
  484. order_id = str(order_data['id'])
  485. archive_id = order_id
  486. year = datetime.datetime.now().year
  487. date_str = datetime.datetime.now().strftime('%Y-%m-%d')
  488. date_compact = datetime.datetime.now().strftime('%Y%m%d')
  489. # Clean output dir for this order
  490. pkg_root = os.path.join(output_dir, archive_id)
  491. if os.path.exists(pkg_root):
  492. shutil.rmtree(pkg_root)
  493. os.makedirs(pkg_root)
  494. # Directory structure
  495. archive_dir = os.path.join(pkg_root, '电子档案', str(year), archive_id)
  496. os.makedirs(archive_dir)
  497. # Download attachments
  498. files_info = []
  499. attachments = order_data.get('attachments', [])
  500. for att in attachments:
  501. fname = att['name']
  502. furl = att['url']
  503. if not fname or not furl: continue
  504. fname = os.path.basename(fname)
  505. local_path = os.path.join(archive_dir, fname)
  506. if download_file(furl, local_path):
  507. fsize = os.path.getsize(local_path)
  508. fmd5 = get_file_md5(local_path)
  509. fext = os.path.splitext(fname)[1].lstrip('.')
  510. files_info.append({
  511. 'name': fname,
  512. 'path': f'/电子档案/{year}/{archive_id}/{fname}',
  513. 'real_path': local_path,
  514. 'size': fsize,
  515. 'md5': fmd5,
  516. 'ext': fext,
  517. 'type': '附件'
  518. })
  519. # Calculate total size
  520. total_size = sum(f['size'] for f in files_info)
  521. # Generate XMLs
  522. # 1. 说明文件.xml
  523. desc_xml = XML_DESC_TEMPLATE.format(
  524. archive_id=archive_id,
  525. size=total_size,
  526. date=date_str,
  527. year=year,
  528. file_count=len(files_info)
  529. )
  530. with open(os.path.join(pkg_root, '说明文件.xml'), 'w', encoding='utf-8') as f:
  531. f.write(desc_xml)
  532. # 2. 文件目录.xml
  533. file_details_xml = ""
  534. for f in files_info:
  535. file_details_xml += XML_FILE_DETAIL_TEMPLATE.format(
  536. path=f"电子档案/{year}/{archive_id}/{f['name']}",
  537. size=f['size'],
  538. md5=f['md5'],
  539. name=f['name'],
  540. type=f['type']
  541. ) + "\n"
  542. catalog_xml = XML_CATALOG_TEMPLATE.format(
  543. doc_num=order_data.get('header', {}).get('measure_no', ''),
  544. title=f"计量单-{order_data.get('header', {}).get('measure_no', '')}",
  545. date=date_str,
  546. date_compact=date_compact,
  547. archive_id=archive_id,
  548. year=year,
  549. file_details=file_details_xml
  550. )
  551. with open(os.path.join(pkg_root, '文件目录.xml'), 'w', encoding='utf-8') as f:
  552. f.write(catalog_xml)
  553. # 3. 文件元数据.xml
  554. docs_xml = ""
  555. for f in files_info:
  556. docs_xml += XML_DOC_TEMPLATE.format(
  557. date=date_str,
  558. md5=f['md5'],
  559. ext=f['ext'],
  560. filename=f['name'],
  561. size=f['size'],
  562. date_compact=date_compact
  563. ) + "\n"
  564. metadata_xml = XML_METADATA_TEMPLATE.format(
  565. date=date_str,
  566. year=year,
  567. title=f"计量单-{order_data.get('header', {}).get('measure_no', '')}",
  568. date_compact=date_compact,
  569. docs=docs_xml
  570. )
  571. with open(os.path.join(archive_dir, '文件元数据.xml'), 'w', encoding='utf-8') as f:
  572. f.write(metadata_xml)
  573. # Zip it
  574. eep_filename = f"{archive_id}.eep"
  575. eep_path = os.path.join(output_dir, eep_filename)
  576. with zipfile.ZipFile(eep_path, 'w', zipfile.ZIP_DEFLATED) as zf:
  577. for root, dirs, files in os.walk(pkg_root):
  578. for file in files:
  579. abs_path = os.path.join(root, file)
  580. rel_path = os.path.relpath(abs_path, output_dir)
  581. zf.write(abs_path, rel_path)
  582. return eep_path, files_info
  583. import copy
  584. def upload_eep_package(eep_path, order_data, files_info):
  585. archive_id = str(order_data['id'])
  586. eep_size = os.path.getsize(eep_path)
  587. eep_md5 = get_file_md5(eep_path)
  588. eep_filename = os.path.basename(f".{eep_path}")
  589. print(f"eep_filename: {eep_filename}")
  590. print(f"eep_path: {eep_path}")
  591. # Read file content for Base64
  592. with open(eep_path, "rb") as f:
  593. file_content = f.read()
  594. base64_str = base64.b64encode(file_content).decode('utf-8')
  595. payload = {
  596. "data": {
  597. "syscode": "HWKJLZF",
  598. "businesscode": "HWKJLZF",
  599. "id": archive_id
  600. },
  601. "files": [
  602. {
  603. "id": archive_id,
  604. "path": '',
  605. "filename": eep_filename,
  606. "ext": ".eep",
  607. "size": eep_size,
  608. "md5code": eep_md5,
  609. "fjsize": len(files_info),
  610. "pathtype": "4", # Base64
  611. "base64": base64_str
  612. }
  613. ]
  614. }
  615. # Print JSON (truncate base64 for readability)
  616. # log_payload = copy.deepcopy(payload)
  617. # for f in log_payload['files']:
  618. # if 'base64' in f:
  619. # f['base64'] = f['base64'][:100] + '... (truncated)'
  620. # print(f"\n[DEBUG] JSON Payload for {eep_filename}:")
  621. # print(json.dumps(log_payload, indent=2, ensure_ascii=False))
  622. # print(f"Skipping actual upload for {eep_filename}...")
  623. # return False
  624. print(f"Uploading {eep_filename} (Size: {eep_size}, MD5: {eep_md5})...")
  625. try:
  626. headers = {'Content-Type': 'application/json'}
  627. response = requests.post(API_URL, json=payload, headers=headers, timeout=60)
  628. print(f"Upload Response: {response.text}")
  629. if response.status_code == 200:
  630. res_json = response.json()
  631. if res_json.get('success'):
  632. return True
  633. else:
  634. print(f"API returned failure: {res_json.get('message')}")
  635. return False
  636. else:
  637. print(f"HTTP Error: {response.status_code}")
  638. return False
  639. except Exception as e:
  640. print(f"Upload Exception: {e}")
  641. return False
  642. def sync_to_external_system(sqlite_conn):
  643. cursor = sqlite_conn.cursor()
  644. # 获取未同步的数据
  645. cursor.execute("SELECT id, data_json FROM measure_orders WHERE sync_status = 0")
  646. rows = cursor.fetchall()
  647. if not rows:
  648. print("No pending records to sync.")
  649. return
  650. print(f"Syncing {len(rows)} records to external system...")
  651. # Create output directory
  652. output_dir = 'eep_packages'
  653. if not os.path.exists(output_dir):
  654. os.makedirs(output_dir)
  655. for row in rows:
  656. order_id = row[0]
  657. data_json = row[1]
  658. data = json.loads(data_json)
  659. try:
  660. print(f"Processing order {data.get('header', {}).get('measure_no', 'Unknown')} (ID: {order_id})...")
  661. # 1. Generate EEP Package
  662. eep_path, files_info = create_eep_package(data, output_dir)
  663. # 2. Upload EEP Package
  664. if upload_eep_package(eep_path, data, files_info):
  665. # 3. Update Sync Status
  666. cursor.execute("UPDATE measure_orders SET sync_status = 1 WHERE id = ?", (order_id,))
  667. sqlite_conn.commit() # 立即提交事务
  668. print(f"Order {order_id} synced successfully.")
  669. else:
  670. print(f"Failed to upload order {order_id}.")
  671. except Exception as e:
  672. print(f"Failed to sync order {order_id}: {e}")
  673. import traceback
  674. traceback.print_exc()
  675. sqlite_conn.commit()
  676. print("Sync completed.")
  677. if __name__ == "__main__":
  678. sqlite_conn = init_sqlite()
  679. print("Fetching data from MySQL...")
  680. data = fetch_from_mysql()
  681. if data is not None:
  682. print(f"Caching {len(data)} records...")
  683. cache_data(sqlite_conn, data)
  684. # Print sample structure
  685. if len(data) > 0:
  686. sample = data[0]
  687. print("\nSample Data Structure Cached:")
  688. print(f"Header Keys: {list(sample['header'].keys())}")
  689. print(f"Statistics Keys: {list(sample['statistics'].keys())}")
  690. print(f"Attachments Count: {len(sample['attachments'])}")
  691. sync_to_external_system(sqlite_conn)
  692. else:
  693. print("Failed to fetch data from MySQL. Please check your connection settings.")
  694. sqlite_conn.close()