sync_measure_data.py 29 KB

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