|
@@ -0,0 +1,786 @@
|
|
|
|
|
+import mysql.connector
|
|
|
|
|
+import sqlite3
|
|
|
|
|
+import json
|
|
|
|
|
+import os
|
|
|
|
|
+import datetime
|
|
|
|
|
+import time
|
|
|
|
|
+import requests
|
|
|
|
|
+import http.client
|
|
|
|
|
+from urllib.parse import urlparse
|
|
|
|
|
+import shutil
|
|
|
|
|
+import hashlib
|
|
|
|
|
+import zipfile
|
|
|
|
|
+import base64
|
|
|
|
|
+from decimal import Decimal
|
|
|
|
|
+
|
|
|
|
|
+# 数据库配置 (从 application-dev.yml 获取)
|
|
|
|
|
+# 如果连接失败,请检查 VPN 或修改此处的 host/port/user/password
|
|
|
|
|
+DB_CONFIG = {
|
|
|
|
|
+ 'user': 'root',
|
|
|
|
|
+ 'password': '84853032',
|
|
|
|
|
+ 'host': '47.99.60.80',
|
|
|
|
|
+ 'port': 3306,
|
|
|
|
|
+ 'database': '2022hs060',
|
|
|
|
|
+ 'use_pure': True,
|
|
|
|
|
+ 'connect_timeout': 5
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+# 目标API配置
|
|
|
|
|
+API_URL = "http://218.94.73.106:8081/api/eps9/tyjk/api/data/asip/HWKJLZF"
|
|
|
|
|
+FILE_BASE_URL = "https://oss.dnnbuild.com" # 猜测的文件下载基地址
|
|
|
|
|
+
|
|
|
|
|
+# XML 模板
|
|
|
|
|
+XML_DESC_TEMPLATE = """<?xml version="1.0" encoding="UTF-8"?>
|
|
|
|
|
+<文件说明>
|
|
|
|
|
+ <载体编号>{archive_id}</载体编号>
|
|
|
|
|
+ <载体类型>在线</载体类型>
|
|
|
|
|
+ <载体容量>{size}</载体容量>
|
|
|
|
|
+ <制作时间>{date}</制作时间>
|
|
|
|
|
+ <载体制作单位名称>沪武高速公路太仓至常州段扩建工程苏州段</载体制作单位名称>
|
|
|
|
|
+ <载体保管单位名称>沪武高速公路太仓至常州段扩建工程苏州段</载体保管单位名称>
|
|
|
|
|
+ <载体检查单位名称>沪武高速公路太仓至常州段扩建工程苏州段</载体检查单位名称>
|
|
|
|
|
+ <载体申请单位名称>沪武高速公路太仓至常州段扩建工程苏州段</载体申请单位名称>
|
|
|
|
|
+ <年度>{year}</年度>
|
|
|
|
|
+ <归档文件数量>{file_count}</归档文件数量>
|
|
|
|
|
+ <归档类型>文件</归档类型>
|
|
|
|
|
+ <起始件号></起始件号>
|
|
|
|
|
+ <截至件号></截至件号>
|
|
|
|
|
+ <信息系统名称>档案综合利用平台</信息系统名称>
|
|
|
|
|
+</文件说明>"""
|
|
|
|
|
+
|
|
|
|
|
+XML_CATALOG_TEMPLATE = """<?xml version="1.0" encoding="UTF-8"?>
|
|
|
|
|
+<文件目录>
|
|
|
|
|
+ <归档文件>
|
|
|
|
|
+ <处理部门></处理部门>
|
|
|
|
|
+ <公文标识></公文标识>
|
|
|
|
|
+ <文件类型>发文</文件类型>
|
|
|
|
|
+ <份号></份号>
|
|
|
|
|
+ <密级和保密期限>普通</密级和保密期限>
|
|
|
|
|
+ <紧急程度>内部资料</紧急程度>
|
|
|
|
|
+ <发文机关标志></发文机关标志>
|
|
|
|
|
+ <发文字号>{doc_num}</发文字号>
|
|
|
|
|
+ <签发人>null</签发人>
|
|
|
|
|
+ <标题>{title}</标题>
|
|
|
|
|
+ <主送机关></主送机关>
|
|
|
|
|
+ <附件说明></附件说明>
|
|
|
|
|
+ <发文机关或签发人署名>沪武高速公路太仓至常州段扩建工程苏州段</发文机关或签发人署名>
|
|
|
|
|
+ <成文日期>{date_compact}</成文日期>
|
|
|
|
|
+ <附注></附注>
|
|
|
|
|
+ <抄送机关></抄送机关>
|
|
|
|
|
+ <印发机关></印发机关>
|
|
|
|
|
+ <印发日期></印发日期>
|
|
|
|
|
+ <发布层次></发布层次>
|
|
|
|
|
+ <档号>{archive_id}</档号>
|
|
|
|
|
+ <年度>{year}</年度>
|
|
|
|
|
+ <保管期限></保管期限>
|
|
|
|
|
+ <机构或问题></机构或问题>
|
|
|
|
|
+ <件号></件号>
|
|
|
|
|
+ <数字对象标识></数字对象标识>
|
|
|
|
|
+ <环境信息></环境信息>
|
|
|
|
|
+ <软件环境></软件环境>
|
|
|
|
|
+ <硬件环境></硬件环境>
|
|
|
|
|
+ <处理类型></处理类型>
|
|
|
|
|
+ <处理者></处理者>
|
|
|
|
|
+ <处理时间></处理时间>
|
|
|
|
|
+ <处理结果></处理结果>
|
|
|
|
|
+ <文件>
|
|
|
|
|
+{file_details}
|
|
|
|
|
+ </文件>
|
|
|
|
|
+ </归档文件>
|
|
|
|
|
+</文件目录>"""
|
|
|
|
|
+
|
|
|
|
|
+XML_FILE_DETAIL_TEMPLATE = """ <文件详情>
|
|
|
|
|
+ <文件路径>{path}</文件路径>
|
|
|
|
|
+ <文件大小>{size}</文件大小>
|
|
|
|
|
+ <数字摘要>{md5}</数字摘要>
|
|
|
|
|
+ <文件单位>B</文件单位>
|
|
|
|
|
+ <文件名称>{name}</文件名称>
|
|
|
|
|
+ <文件类型>{type}</文件类型>
|
|
|
|
|
+ </文件详情>"""
|
|
|
|
|
+
|
|
|
|
|
+XML_METADATA_TEMPLATE = """<?xml version="1.0" encoding="UTF-8"?>
|
|
|
|
|
+<电子文件封装包 name="M201">
|
|
|
|
|
+ <封装包格式描述 name="M202">本EEP根据中华人民共和国档案行业标准DA/T 48-2009《基于XML的电子文件封装规范》生成</封装包格式描述>
|
|
|
|
|
+ <版本 name="M203">2009</版本>
|
|
|
|
|
+ <被签名对象 name="M204">
|
|
|
|
|
+ <封装包类型 name="M205" />
|
|
|
|
|
+ <封装包类型描述 name="M206" />
|
|
|
|
|
+ <封装包创建时间 name="M207">{date}</封装包创建时间>
|
|
|
|
|
+ <封装包创建单位 name="M208">沪武高速公路太仓至常州段扩建工程苏州段</封装包创建单位>
|
|
|
|
|
+ <封装内容 name="M209">
|
|
|
|
|
+ <文件实体块 name="M210">
|
|
|
|
|
+ <文件实体 name="M211">
|
|
|
|
|
+ <聚合层次 name="M1" />
|
|
|
|
|
+ <来源 name="M2">
|
|
|
|
|
+ <档案馆名称 name="M3">xx</档案馆名称>
|
|
|
|
|
+ <档案馆代码 name="M4" />
|
|
|
|
|
+ <全宗名称 name="M5">沪武高速公路太仓至常州段扩建工程苏州段</全宗名称>
|
|
|
|
|
+ <立档单位名称 name="M6">沪武高速公路太仓至常州段扩建工程苏州段</立档单位名称>
|
|
|
|
|
+ </来源>
|
|
|
|
|
+ <电子文件号 name="M7" />
|
|
|
|
|
+ <档号 name="M8">
|
|
|
|
|
+ <全宗号 name="M9">XYK</全宗号>
|
|
|
|
|
+ <目录号 name="M10" />
|
|
|
|
|
+ <年度 name="M11">{year}</年度>
|
|
|
|
|
+ <保管期限 name="M12">永久</保管期限>
|
|
|
|
|
+ <机构或问题 name="M13" />
|
|
|
|
|
+ <类别号 name="M14" />
|
|
|
|
|
+ <室编案卷号 name="M15" />
|
|
|
|
|
+ <馆编案卷号 name="M16" />
|
|
|
|
|
+ <室编件号 name="M17" />
|
|
|
|
|
+ <文档序号 name="M19" />
|
|
|
|
|
+ <页号 name="M20" />
|
|
|
|
|
+ </档号>
|
|
|
|
|
+ <内容描述 name="M21">
|
|
|
|
|
+ <题名 name="M22">{title}</题名>
|
|
|
|
|
+ <并列题名 name="M23" />
|
|
|
|
|
+ <副题名 name="M24" />
|
|
|
|
|
+ <说明题名文字 name="M25" />
|
|
|
|
|
+ <主题词 name="M26" />
|
|
|
|
|
+ <关键词 name="M27" />
|
|
|
|
|
+ <人名 name="M28" />
|
|
|
|
|
+ <摘要 name="M29" />
|
|
|
|
|
+ <分类号 name="M30" />
|
|
|
|
|
+ <文件编号 name="M31" />
|
|
|
|
|
+ <责任者 name="M32" />
|
|
|
|
|
+ <日期 name="M33">{date}</日期>
|
|
|
|
|
+ <文种 name="M34" />
|
|
|
|
|
+ <紧急程度 name="M35" />
|
|
|
|
|
+ <主送 name="M36" />
|
|
|
|
|
+ <抄送 name="M37" />
|
|
|
|
|
+ <密级 name="M38" />
|
|
|
|
|
+ <保管期限 name="M39" />
|
|
|
|
|
+ </内容描述>
|
|
|
|
|
+ <形式特征 name="M41">
|
|
|
|
|
+ <文件组合类型 name="M42" />
|
|
|
|
|
+ <件数 name="M43" />
|
|
|
|
|
+ <页数 name="M44" />
|
|
|
|
|
+ <语种 name="M45" />
|
|
|
|
|
+ <稿本 name="M46" />
|
|
|
|
|
+ </形式特征>
|
|
|
|
|
+ <附注 name="M75" />
|
|
|
|
|
+ <文件数据 name="M213">
|
|
|
|
|
+{docs}
|
|
|
|
|
+ </文件数据>
|
|
|
|
|
+ </文件实体>
|
|
|
|
|
+ </文件实体块>
|
|
|
|
|
+ </封装内容>
|
|
|
|
|
+ </被签名对象>
|
|
|
|
|
+</电子文件封装包>"""
|
|
|
|
|
+
|
|
|
|
|
+XML_DOC_TEMPLATE = """ <文档>
|
|
|
|
|
+ <文档标识符 name="M215">{md5}</文档标识符>
|
|
|
|
|
+ <文档序号 name="M19" />
|
|
|
|
|
+ <文档主从声明 name="M216" />
|
|
|
|
|
+ <题名 name="M22"/>
|
|
|
|
|
+ <文档数据 name="M217">
|
|
|
|
|
+ <编码 name="M218">
|
|
|
|
|
+ <电子属性 name="M46">
|
|
|
|
|
+ <格式信息 name="M47">{ext}</格式信息>
|
|
|
|
|
+ <计算机文件名 name="M48">{filename}</计算机文件名>
|
|
|
|
|
+ <计算机文件大小 name="M49">{size}</计算机文件大小>
|
|
|
|
|
+ <文档创建程序 name="M50" />
|
|
|
|
|
+ <信息系统描述 name="M51" />
|
|
|
|
|
+ <计算机文件创建时间 name="M101">{date}</计算机文件创建时间>
|
|
|
|
|
+ </电子属性>
|
|
|
|
|
+ <数字化属性 name="M52">
|
|
|
|
|
+ <数字化对象形态 name="M53" />
|
|
|
|
|
+ <扫描分辨率 name="M54" />
|
|
|
|
|
+ <扫描色彩模式 name="M55" />
|
|
|
|
|
+ <图像压缩方案 name="M56" />
|
|
|
|
|
+ </数字化属性>
|
|
|
|
|
+ <编码描述 name="M219" />
|
|
|
|
|
+ <反编码关键字 name="M220" />
|
|
|
|
|
+ <编码数据 name="M221" />
|
|
|
|
|
+ </编码>
|
|
|
|
|
+ <电子签名 name="M57">
|
|
|
|
|
+ <签名规则 name="M58" />
|
|
|
|
|
+ <签名时间 name="M59" />
|
|
|
|
|
+ <签名人 name="M60" />
|
|
|
|
|
+ <签名结果 name="M61" />
|
|
|
|
|
+ <签名算法标识 name="M64" />
|
|
|
|
|
+ </电子签名>
|
|
|
|
|
+ <存储位置 name="M65">
|
|
|
|
|
+ <当前位置 name="M66" />
|
|
|
|
|
+ <脱机载体编号 name="M67" />
|
|
|
|
|
+ <脱机载体存址 name="M68" />
|
|
|
|
|
+ <缩微号 name="M69" />
|
|
|
|
|
+ </存储位置>
|
|
|
|
|
+ </文档数据>
|
|
|
|
|
+ </文档>"""
|
|
|
|
|
+
|
|
|
|
|
+# 本地缓存文件
|
|
|
|
|
+SQLITE_DB = 'measure_data_cache.db'
|
|
|
|
|
+
|
|
|
|
|
+def init_sqlite():
|
|
|
|
|
+ conn = sqlite3.connect(SQLITE_DB)
|
|
|
|
|
+ cursor = conn.cursor()
|
|
|
|
|
+ # 计量单表
|
|
|
|
|
+ cursor.execute('''
|
|
|
|
|
+ CREATE TABLE IF NOT EXISTS measure_orders (
|
|
|
|
|
+ id TEXT PRIMARY KEY,
|
|
|
|
|
+ measure_number TEXT,
|
|
|
|
|
+ status INTEGER,
|
|
|
|
|
+ sync_status INTEGER DEFAULT 0,
|
|
|
|
|
+ data_json TEXT,
|
|
|
|
|
+ created_at TIMESTAMP
|
|
|
|
|
+ )
|
|
|
|
|
+ ''')
|
|
|
|
|
+ # 附件表
|
|
|
|
|
+ cursor.execute('''
|
|
|
|
|
+ CREATE TABLE IF NOT EXISTS attachments (
|
|
|
|
|
+ id TEXT PRIMARY KEY,
|
|
|
|
|
+ measure_order_id TEXT,
|
|
|
|
|
+ file_name TEXT,
|
|
|
|
|
+ file_url TEXT,
|
|
|
|
|
+ sync_status INTEGER DEFAULT 0
|
|
|
|
|
+ )
|
|
|
|
|
+ ''')
|
|
|
|
|
+ conn.commit()
|
|
|
|
|
+ return conn
|
|
|
|
|
+
|
|
|
|
|
+def fetch_from_mysql():
|
|
|
|
|
+ try:
|
|
|
|
|
+ print(f"Connecting to MySQL {DB_CONFIG['host']}...")
|
|
|
|
|
+ conn = mysql.connector.connect(**DB_CONFIG)
|
|
|
|
|
+ cursor = conn.cursor(dictionary=True)
|
|
|
|
|
+
|
|
|
|
|
+ # 1. 获取已完成的施工计量单 (status=2 or 4)
|
|
|
|
|
+ print("Fetching measure orders...")
|
|
|
|
|
+ # status=2 (audited) 是已完成, status=4 also seen in completed orders
|
|
|
|
|
+ query_orders = """
|
|
|
|
|
+ SELECT *
|
|
|
|
|
+ FROM mp_measure_order
|
|
|
|
|
+ WHERE status IN (2, 4) AND is_deleted = 0
|
|
|
|
|
+ ORDER BY id DESC
|
|
|
|
|
+ LIMIT 1000
|
|
|
|
|
+ """
|
|
|
|
|
+ # 加 LIMIT 是为了测试方便,生产环境可以去掉
|
|
|
|
|
+
|
|
|
|
|
+ cursor.execute(query_orders)
|
|
|
|
|
+ orders = cursor.fetchall()
|
|
|
|
|
+ print(f"Found {len(orders)} completed orders.")
|
|
|
|
|
+
|
|
|
|
|
+ order_data_list = []
|
|
|
|
|
+
|
|
|
|
|
+ for order in orders:
|
|
|
|
|
+ order_id = str(order['id'])
|
|
|
|
|
+
|
|
|
|
|
+ # 2. 获取关联的合同信息
|
|
|
|
|
+ contract = None
|
|
|
|
|
+ if order.get('mp_contract_id'):
|
|
|
|
|
+ cursor.execute("SELECT * FROM mp_contract WHERE id = %s", (order['mp_contract_id'],))
|
|
|
|
|
+ contract = cursor.fetchone()
|
|
|
|
|
+
|
|
|
|
|
+ # 3. 获取其他支付项 (mp_construction_measure_others)
|
|
|
|
|
+ cursor.execute("SELECT * FROM mp_construction_measure_others WHERE mp_construction_measure_id = %s AND is_deleted = 0", (order_id,))
|
|
|
|
|
+ others = cursor.fetchall()
|
|
|
|
|
+
|
|
|
|
|
+ # 4. 获取 Tabulator Name (blade_user)
|
|
|
|
|
+ tabulator_name = None
|
|
|
|
|
+ if order.get('tabulator'):
|
|
|
|
|
+ cursor.execute("SELECT real_name FROM blade_user WHERE id = %s", (order['tabulator'],))
|
|
|
|
|
+ user_row = cursor.fetchone()
|
|
|
|
|
+ if user_row:
|
|
|
|
|
+ tabulator_name = user_row['real_name']
|
|
|
|
|
+
|
|
|
|
|
+ # 5. 获取附件
|
|
|
|
|
+ # 关联 mp_measure_attachments 和 tb_file (corrected from blade_attach)
|
|
|
|
|
+ query_attachments = """
|
|
|
|
|
+ SELECT a.id, a.mp_measure_id, f.file_title as name, f.path as link
|
|
|
|
|
+ FROM mp_measure_attachments a
|
|
|
|
|
+ JOIN tb_file f ON a.file_id = f.id
|
|
|
|
|
+ WHERE a.mp_measure_id = %s AND a.is_deleted = 0 AND f.is_deleted = 0
|
|
|
|
|
+ """
|
|
|
|
|
+ cursor.execute(query_attachments, (order_id,))
|
|
|
|
|
+ attachments = cursor.fetchall()
|
|
|
|
|
+
|
|
|
|
|
+ # 格式化附件数据
|
|
|
|
|
+ attachment_list = []
|
|
|
|
|
+ for att in attachments:
|
|
|
|
|
+ url = att['link']
|
|
|
|
|
+ # tb_file path is usually full url
|
|
|
|
|
+
|
|
|
|
|
+ attachment_list.append({
|
|
|
|
|
+ 'id': str(att['id']),
|
|
|
|
|
+ 'name': att['name'],
|
|
|
|
|
+ 'url': url
|
|
|
|
|
+ })
|
|
|
|
|
+
|
|
|
|
|
+ # Helper to serialize date/decimal
|
|
|
|
|
+ def serialize_row(row):
|
|
|
|
|
+ if not row: return None
|
|
|
|
|
+ new_row = {}
|
|
|
|
|
+ for k, v in row.items():
|
|
|
|
|
+ if isinstance(v, (datetime.date, datetime.datetime)):
|
|
|
|
|
+ new_row[k] = v.isoformat()
|
|
|
|
|
+ elif isinstance(v, Decimal):
|
|
|
|
|
+ new_row[k] = float(v) # Or str(v) if precision is critical
|
|
|
|
|
+ elif isinstance(v, (bytes, bytearray)):
|
|
|
|
|
+ try:
|
|
|
|
|
+ new_row[k] = v.decode('utf-8')
|
|
|
|
|
+ except:
|
|
|
|
|
+ new_row[k] = str(v) # Fallback
|
|
|
|
|
+ elif isinstance(v, (set)):
|
|
|
|
|
+ new_row[k] = list(v)
|
|
|
|
|
+ else:
|
|
|
|
|
+ new_row[k] = v
|
|
|
|
|
+ return new_row
|
|
|
|
|
+
|
|
|
|
|
+ # Serialize all data
|
|
|
|
|
+ order_data = serialize_row(order)
|
|
|
|
|
+ contract_data = serialize_row(contract) if contract else {}
|
|
|
|
|
+ others_data = [serialize_row(x) for x in others]
|
|
|
|
|
+
|
|
|
|
|
+ # Construct simplified structure matching screenshot
|
|
|
|
|
+
|
|
|
|
|
+ # Helper to find amount in others
|
|
|
|
|
+ def get_other_amount(name_key):
|
|
|
|
|
+ for item in others_data:
|
|
|
|
|
+ if item.get('name') == name_key:
|
|
|
|
|
+ return float(item.get('construction_measure_amount') or 0)
|
|
|
|
|
+ return 0.0
|
|
|
|
|
+
|
|
|
|
|
+ subtotal = float(order.get('current_period_amount') or 0)
|
|
|
|
|
+ price_adjustment = get_other_amount('价格调整')
|
|
|
|
|
+ deduction_advance = get_other_amount('扣回材料设备预付款') # Or 扣回开工预付款? Screenshot says Material/Equipment
|
|
|
|
|
+
|
|
|
|
|
+ # Total in screenshot = Subtotal + Price Adjustment (approx logic)
|
|
|
|
|
+ # Or is it Subtotal - Deductions?
|
|
|
|
|
+ # Screenshot:
|
|
|
|
|
+ # Subtotal: -110,981,615.25
|
|
|
|
|
+ # Adj: 123,456.00
|
|
|
|
|
+ # Total: -110,858,159.25 (-110981615.25 + 123456.00 = -110858159.25)
|
|
|
|
|
+ # So Total = Subtotal + Price Adjustment
|
|
|
|
|
+ total_amount = subtotal + price_adjustment
|
|
|
|
|
+
|
|
|
|
|
+ # Proposed Payment
|
|
|
|
|
+ # Screenshot: Total (-110,858,159.25) - Deduction (-2,233,331,437.00) = ... wait
|
|
|
|
|
+ # -110M - (-2233M) = +2122M. But result is -2344M.
|
|
|
|
|
+ # -110M + (-2233M) = -2344M.
|
|
|
|
|
+ # So Proposed Payment = Total + Deduction (if deduction is negative)
|
|
|
|
|
+ # Or Proposed Payment = Total - Deduction (if deduction is positive)
|
|
|
|
|
+ # In DB, '扣回...' amount might be stored as positive or negative.
|
|
|
|
|
+ # We will just fetch the values. Calculation logic is secondary, primary is data availability.
|
|
|
|
|
+
|
|
|
|
|
+ # Flattened Header Info
|
|
|
|
|
+ header_info = {
|
|
|
|
|
+ 'measure_no': order.get('measure_no'),
|
|
|
|
|
+ 'section': contract.get('section_id') if contract else None, # Assuming section_id holds the name
|
|
|
|
|
+ 'measure_method': '分解计量', # Hardcoded as per screenshot/context
|
|
|
|
|
+ 'employer': contract.get('employer') if contract else None,
|
|
|
|
|
+ 'contractor': order.get('construct_dept') or (contract.get('contractor_dept') if contract else None),
|
|
|
|
|
+ 'supervisor': contract.get('jl_section') if contract else None,
|
|
|
|
|
+ 'period_start': order.get('start_date').isoformat() if order.get('start_date') else None,
|
|
|
|
|
+ 'period_end': order.get('end_date').isoformat() if order.get('end_date') else None,
|
|
|
|
|
+ 'tabulation_date': order.get('tabulation_time').isoformat() if order.get('tabulation_time') else None,
|
|
|
|
|
+ 'tabulator': tabulator_name
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ # Statistics Info
|
|
|
|
|
+ statistics_info = {
|
|
|
|
|
+ 'subtotal': subtotal,
|
|
|
|
|
+ 'price_adjustment': price_adjustment,
|
|
|
|
|
+ 'total': total_amount,
|
|
|
|
|
+ 'deduction_material_advance': deduction_advance,
|
|
|
|
|
+ '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
|
|
|
|
|
+ # Actually, let's just dump the relevant others rows to be safe if exact mapping is tricky
|
|
|
|
|
+ 'others_details': [{'name': x['name'], 'amount': float(x['construction_measure_amount'] or 0)} for x in others_data if x['construction_measure_amount'] != 0],
|
|
|
|
|
+ 'completed_last_period': float(order.get('end_last_period_amount') or 0),
|
|
|
|
|
+ 'completed_cumulative': float(order.get('end_current_period_amount') or 0)
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ order_data_list.append({
|
|
|
|
|
+ 'id': str(order['id']), # Keep ID for internal use
|
|
|
|
|
+ 'measure_number': order.get('measure_number'), # Keep for internal use
|
|
|
|
|
+ 'status': order.get('status'), # Keep for internal use
|
|
|
|
|
+ 'header': header_info,
|
|
|
|
|
+ 'statistics': statistics_info,
|
|
|
|
|
+ 'attachments': attachment_list
|
|
|
|
|
+ })
|
|
|
|
|
+
|
|
|
|
|
+ cursor.close()
|
|
|
|
|
+ conn.close()
|
|
|
|
|
+ return order_data_list
|
|
|
|
|
+
|
|
|
|
|
+ except mysql.connector.Error as err:
|
|
|
|
|
+ print(f"MySQL Error: {err}")
|
|
|
|
|
+ return None
|
|
|
|
|
+ except Exception as e:
|
|
|
|
|
+ print(f"Error: {e}")
|
|
|
|
|
+ return None
|
|
|
|
|
+
|
|
|
|
|
+def cache_data(sqlite_conn, data_list):
|
|
|
|
|
+ if not data_list:
|
|
|
|
|
+ return
|
|
|
|
|
+
|
|
|
|
|
+ cursor = sqlite_conn.cursor()
|
|
|
|
|
+ count_new = 0
|
|
|
|
|
+ count_updated = 0
|
|
|
|
|
+
|
|
|
|
|
+ for item in data_list:
|
|
|
|
|
+ # Filter by section name
|
|
|
|
|
+ section_name = item.get('header', {}).get('section', '')
|
|
|
|
|
+ # Ensure section_name is a string before checking
|
|
|
|
|
+ if section_name is None:
|
|
|
|
|
+ section_name = ''
|
|
|
|
|
+ else:
|
|
|
|
|
+ section_name = str(section_name)
|
|
|
|
|
+
|
|
|
|
|
+ if not any(keyword in section_name for keyword in ['CS', 'ZJG', 'TC']):
|
|
|
|
|
+ continue
|
|
|
|
|
+
|
|
|
|
|
+ order_id = item['id']
|
|
|
|
|
+ measure_number = item['measure_number']
|
|
|
|
|
+ status = item['status']
|
|
|
|
|
+ attachments = item['attachments']
|
|
|
|
|
+
|
|
|
|
|
+ # 检查是否存在
|
|
|
|
|
+ cursor.execute("SELECT id FROM measure_orders WHERE id = ?", (order_id,))
|
|
|
|
|
+ exists = cursor.fetchone()
|
|
|
|
|
+
|
|
|
|
|
+ # Create a clean data object for JSON storage (exclude internal fields if desired, or keep them)
|
|
|
|
|
+ # We'll store the whole item as JSON for simplicity, it contains header and statistics.
|
|
|
|
|
+ json_str = json.dumps(item, ensure_ascii=False)
|
|
|
|
|
+
|
|
|
|
|
+ if not exists:
|
|
|
|
|
+ cursor.execute('''
|
|
|
|
|
+ INSERT INTO measure_orders (id, measure_number, status, data_json, created_at)
|
|
|
|
|
+ VALUES (?, ?, ?, ?, ?)
|
|
|
|
|
+ ''', (order_id, measure_number, status, json_str, datetime.datetime.now()))
|
|
|
|
|
+ count_new += 1
|
|
|
|
|
+ else:
|
|
|
|
|
+ # Update data and reset sync_status to 0 to ensure updated data is synced
|
|
|
|
|
+ cursor.execute('''
|
|
|
|
|
+ UPDATE measure_orders SET data_json = ?, sync_status = 0 WHERE id = ?
|
|
|
|
|
+ ''', (json_str, order_id))
|
|
|
|
|
+ count_updated += 1
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+ # 存储附件信息
|
|
|
|
|
+ for att in attachments:
|
|
|
|
|
+ cursor.execute("SELECT id FROM attachments WHERE id = ?", (att['id'],))
|
|
|
|
|
+ att_exists = cursor.fetchone()
|
|
|
|
|
+ if not att_exists:
|
|
|
|
|
+ cursor.execute('''
|
|
|
|
|
+ INSERT INTO attachments (id, measure_order_id, file_name, file_url)
|
|
|
|
|
+ VALUES (?, ?, ?, ?)
|
|
|
|
|
+ ''', (att['id'], order_id, att['name'], att['url']))
|
|
|
|
|
+
|
|
|
|
|
+ sqlite_conn.commit()
|
|
|
|
|
+ print(f"Cached: {count_new} new, {count_updated} updated.")
|
|
|
|
|
+
|
|
|
|
|
+def get_file_md5(filepath):
|
|
|
|
|
+ hash_md5 = hashlib.md5()
|
|
|
|
|
+ with open(filepath, "rb") as f:
|
|
|
|
|
+ for chunk in iter(lambda: f.read(4096), b""):
|
|
|
|
|
+ hash_md5.update(chunk)
|
|
|
|
|
+ return hash_md5.hexdigest()
|
|
|
|
|
+
|
|
|
|
|
+def download_file(url, dest_path):
|
|
|
|
|
+ # Try to ensure URL is valid
|
|
|
|
|
+ if not url.startswith('http'):
|
|
|
|
|
+ # If url is like /profile/upload/..., append base
|
|
|
|
|
+ if url.startswith('/'):
|
|
|
|
|
+ url = FILE_BASE_URL + url
|
|
|
|
|
+ else:
|
|
|
|
|
+ url = FILE_BASE_URL + '/' + url
|
|
|
|
|
+
|
|
|
|
|
+ print(f"Downloading {url} to {dest_path}...")
|
|
|
|
|
+ try:
|
|
|
|
|
+ parsed_url = urlparse(url)
|
|
|
|
|
+ hostname = parsed_url.netloc
|
|
|
|
|
+ path = parsed_url.path
|
|
|
|
|
+ if parsed_url.query:
|
|
|
|
|
+ path += '?' + parsed_url.query
|
|
|
|
|
+
|
|
|
|
|
+ headers = {
|
|
|
|
|
+ 'User-Agent': 'Apifox/1.0.0 (https://apifox.com)',
|
|
|
|
|
+ 'Accept': '*/*',
|
|
|
|
|
+ 'Host': hostname,
|
|
|
|
|
+ 'Connection': 'keep-alive'
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ conn = None
|
|
|
|
|
+ if parsed_url.scheme == 'https':
|
|
|
|
|
+ conn = http.client.HTTPSConnection(hostname)
|
|
|
|
|
+ else:
|
|
|
|
|
+ conn = http.client.HTTPConnection(hostname)
|
|
|
|
|
+
|
|
|
|
|
+ conn.request("GET", path, '', headers)
|
|
|
|
|
+ res = conn.getresponse()
|
|
|
|
|
+
|
|
|
|
|
+ # Log response details for debugging
|
|
|
|
|
+ print(f" Response Status: {res.status}")
|
|
|
|
|
+ print(f" Content-Type: {res.getheader('Content-Type')}")
|
|
|
|
|
+ print(f" Content-Length: {res.getheader('Content-Length')}")
|
|
|
|
|
+
|
|
|
|
|
+ if res.status == 200:
|
|
|
|
|
+ with open(dest_path, 'wb') as f:
|
|
|
|
|
+ while True:
|
|
|
|
|
+ chunk = res.read(8192)
|
|
|
|
|
+ if not chunk:
|
|
|
|
|
+ break
|
|
|
|
|
+ f.write(chunk)
|
|
|
|
|
+ conn.close()
|
|
|
|
|
+ return True
|
|
|
|
|
+ else:
|
|
|
|
|
+ print(f"Failed to download {url}: Status {res.status}")
|
|
|
|
|
+ conn.close()
|
|
|
|
|
+ return False
|
|
|
|
|
+ except Exception as e:
|
|
|
|
|
+ print(f"Exception downloading {url}: {e}")
|
|
|
|
|
+ return False
|
|
|
|
|
+
|
|
|
|
|
+def create_eep_package(order_data, output_dir='eep_packages'):
|
|
|
|
|
+ order_id = str(order_data['id'])
|
|
|
|
|
+ archive_id = order_id
|
|
|
|
|
+ year = datetime.datetime.now().year
|
|
|
|
|
+ date_str = datetime.datetime.now().strftime('%Y-%m-%d')
|
|
|
|
|
+ date_compact = datetime.datetime.now().strftime('%Y%m%d')
|
|
|
|
|
+
|
|
|
|
|
+ # Clean output dir for this order
|
|
|
|
|
+ pkg_root = os.path.join(output_dir, archive_id)
|
|
|
|
|
+ if os.path.exists(pkg_root):
|
|
|
|
|
+ shutil.rmtree(pkg_root)
|
|
|
|
|
+ os.makedirs(pkg_root)
|
|
|
|
|
+
|
|
|
|
|
+ # Directory structure
|
|
|
|
|
+ archive_dir = os.path.join(pkg_root, '电子档案', str(year), archive_id)
|
|
|
|
|
+ os.makedirs(archive_dir)
|
|
|
|
|
+
|
|
|
|
|
+ # Download attachments
|
|
|
|
|
+ files_info = []
|
|
|
|
|
+ attachments = order_data.get('attachments', [])
|
|
|
|
|
+
|
|
|
|
|
+ for att in attachments:
|
|
|
|
|
+ fname = att['name']
|
|
|
|
|
+ furl = att['url']
|
|
|
|
|
+ if not fname or not furl: continue
|
|
|
|
|
+
|
|
|
|
|
+ fname = os.path.basename(fname)
|
|
|
|
|
+ local_path = os.path.join(archive_dir, fname)
|
|
|
|
|
+
|
|
|
|
|
+ if download_file(furl, local_path):
|
|
|
|
|
+ fsize = os.path.getsize(local_path)
|
|
|
|
|
+ fmd5 = get_file_md5(local_path)
|
|
|
|
|
+ fext = os.path.splitext(fname)[1].lstrip('.')
|
|
|
|
|
+ files_info.append({
|
|
|
|
|
+ 'name': fname,
|
|
|
|
|
+ 'path': f'/电子档案/{year}/{archive_id}/{fname}',
|
|
|
|
|
+ 'real_path': local_path,
|
|
|
|
|
+ 'size': fsize,
|
|
|
|
|
+ 'md5': fmd5,
|
|
|
|
|
+ 'ext': fext,
|
|
|
|
|
+ 'type': '附件'
|
|
|
|
|
+ })
|
|
|
|
|
+
|
|
|
|
|
+ # Calculate total size
|
|
|
|
|
+ total_size = sum(f['size'] for f in files_info)
|
|
|
|
|
+
|
|
|
|
|
+ # Generate XMLs
|
|
|
|
|
+ # 1. 说明文件.xml
|
|
|
|
|
+ desc_xml = XML_DESC_TEMPLATE.format(
|
|
|
|
|
+ archive_id=archive_id,
|
|
|
|
|
+ size=total_size,
|
|
|
|
|
+ date=date_str,
|
|
|
|
|
+ year=year,
|
|
|
|
|
+ file_count=len(files_info)
|
|
|
|
|
+ )
|
|
|
|
|
+ with open(os.path.join(pkg_root, '说明文件.xml'), 'w', encoding='utf-8') as f:
|
|
|
|
|
+ f.write(desc_xml)
|
|
|
|
|
+
|
|
|
|
|
+ # 2. 文件目录.xml
|
|
|
|
|
+ file_details_xml = ""
|
|
|
|
|
+ for f in files_info:
|
|
|
|
|
+ file_details_xml += XML_FILE_DETAIL_TEMPLATE.format(
|
|
|
|
|
+ path=f"电子档案/{year}/{archive_id}/{f['name']}",
|
|
|
|
|
+ size=f['size'],
|
|
|
|
|
+ md5=f['md5'],
|
|
|
|
|
+ name=f['name'],
|
|
|
|
|
+ type=f['type']
|
|
|
|
|
+ ) + "\n"
|
|
|
|
|
+
|
|
|
|
|
+ catalog_xml = XML_CATALOG_TEMPLATE.format(
|
|
|
|
|
+ doc_num=order_data.get('header', {}).get('measure_no', ''),
|
|
|
|
|
+ title=f"计量单-{order_data.get('header', {}).get('measure_no', '')}",
|
|
|
|
|
+ date=date_str,
|
|
|
|
|
+ date_compact=date_compact,
|
|
|
|
|
+ archive_id=archive_id,
|
|
|
|
|
+ year=year,
|
|
|
|
|
+ file_details=file_details_xml
|
|
|
|
|
+ )
|
|
|
|
|
+ with open(os.path.join(pkg_root, '文件目录.xml'), 'w', encoding='utf-8') as f:
|
|
|
|
|
+ f.write(catalog_xml)
|
|
|
|
|
+
|
|
|
|
|
+ # 3. 文件元数据.xml
|
|
|
|
|
+ docs_xml = ""
|
|
|
|
|
+ for f in files_info:
|
|
|
|
|
+ docs_xml += XML_DOC_TEMPLATE.format(
|
|
|
|
|
+ md5=f['md5'],
|
|
|
|
|
+ ext=f['ext'],
|
|
|
|
|
+ filename=f['name'],
|
|
|
|
|
+ size=f['size'],
|
|
|
|
|
+ date_compact=date_compact
|
|
|
|
|
+ ) + "\n"
|
|
|
|
|
+
|
|
|
|
|
+ metadata_xml = XML_METADATA_TEMPLATE.format(
|
|
|
|
|
+ date=date_str,
|
|
|
|
|
+ year=year,
|
|
|
|
|
+ title=f"计量单-{order_data.get('header', {}).get('measure_no', '')}",
|
|
|
|
|
+ date_compact=date_compact,
|
|
|
|
|
+ docs=docs_xml
|
|
|
|
|
+ )
|
|
|
|
|
+ with open(os.path.join(archive_dir, '文件元数据.xml'), 'w', encoding='utf-8') as f:
|
|
|
|
|
+ f.write(metadata_xml)
|
|
|
|
|
+
|
|
|
|
|
+ # Zip it
|
|
|
|
|
+ eep_filename = f"{archive_id}.eep"
|
|
|
|
|
+ eep_path = os.path.join(output_dir, eep_filename)
|
|
|
|
|
+
|
|
|
|
|
+ with zipfile.ZipFile(eep_path, 'w', zipfile.ZIP_DEFLATED) as zf:
|
|
|
|
|
+ for root, dirs, files in os.walk(pkg_root):
|
|
|
|
|
+ for file in files:
|
|
|
|
|
+ abs_path = os.path.join(root, file)
|
|
|
|
|
+ rel_path = os.path.relpath(abs_path, output_dir)
|
|
|
|
|
+ zf.write(abs_path, rel_path)
|
|
|
|
|
+
|
|
|
|
|
+ return eep_path, files_info
|
|
|
|
|
+
|
|
|
|
|
+import copy
|
|
|
|
|
+
|
|
|
|
|
+def upload_eep_package(eep_path, order_data, files_info):
|
|
|
|
|
+ archive_id = str(order_data['id'])
|
|
|
|
|
+ eep_size = os.path.getsize(eep_path)
|
|
|
|
|
+ eep_md5 = get_file_md5(eep_path)
|
|
|
|
|
+ eep_filename = os.path.basename(f".{eep_path}")
|
|
|
|
|
+ print(f"eep_filename: {eep_filename}")
|
|
|
|
|
+ print(f"eep_path: {eep_path}")
|
|
|
|
|
+
|
|
|
|
|
+ return False
|
|
|
|
|
+ # Read file content for Base64
|
|
|
|
|
+ with open(eep_path, "rb") as f:
|
|
|
|
|
+ file_content = f.read()
|
|
|
|
|
+ base64_str = base64.b64encode(file_content).decode('utf-8')
|
|
|
|
|
+
|
|
|
|
|
+ payload = {
|
|
|
|
|
+ "data": {
|
|
|
|
|
+ "syscode": "HWKJLZF",
|
|
|
|
|
+ "businesscode": "HWKJLZF",
|
|
|
|
|
+ "id": archive_id
|
|
|
|
|
+ },
|
|
|
|
|
+ "files": [
|
|
|
|
|
+ {
|
|
|
|
|
+ "id": archive_id,
|
|
|
|
|
+ "path": '',
|
|
|
|
|
+ "filename": eep_filename,
|
|
|
|
|
+ "ext": ".eep",
|
|
|
|
|
+ "size": eep_size,
|
|
|
|
|
+ "md5code": eep_md5,
|
|
|
|
|
+ "fjsize": len(files_info),
|
|
|
|
|
+ "pathtype": "4", # Base64
|
|
|
|
|
+ "base64": base64_str
|
|
|
|
|
+ }
|
|
|
|
|
+ ]
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ # Print JSON (truncate base64 for readability)
|
|
|
|
|
+ # log_payload = copy.deepcopy(payload)
|
|
|
|
|
+ # for f in log_payload['files']:
|
|
|
|
|
+ # if 'base64' in f:
|
|
|
|
|
+ # f['base64'] = f['base64'][:100] + '... (truncated)'
|
|
|
|
|
+
|
|
|
|
|
+ # print(f"\n[DEBUG] JSON Payload for {eep_filename}:")
|
|
|
|
|
+ # print(json.dumps(log_payload, indent=2, ensure_ascii=False))
|
|
|
|
|
+
|
|
|
|
|
+ # print(f"Skipping actual upload for {eep_filename}...")
|
|
|
|
|
+ # return False
|
|
|
|
|
+
|
|
|
|
|
+ print(f"Uploading {eep_filename} (Size: {eep_size}, MD5: {eep_md5})...")
|
|
|
|
|
+
|
|
|
|
|
+ try:
|
|
|
|
|
+ headers = {'Content-Type': 'application/json'}
|
|
|
|
|
+ response = requests.post(API_URL, json=payload, headers=headers, timeout=60)
|
|
|
|
|
+ print(f"Upload Response: {response.text}")
|
|
|
|
|
+
|
|
|
|
|
+ if response.status_code == 200:
|
|
|
|
|
+ res_json = response.json()
|
|
|
|
|
+ if res_json.get('success'):
|
|
|
|
|
+ return True
|
|
|
|
|
+ else:
|
|
|
|
|
+ print(f"API returned failure: {res_json.get('message')}")
|
|
|
|
|
+ return False
|
|
|
|
|
+ else:
|
|
|
|
|
+ print(f"HTTP Error: {response.status_code}")
|
|
|
|
|
+ return False
|
|
|
|
|
+
|
|
|
|
|
+ except Exception as e:
|
|
|
|
|
+ print(f"Upload Exception: {e}")
|
|
|
|
|
+ return False
|
|
|
|
|
+
|
|
|
|
|
+def sync_to_external_system(sqlite_conn):
|
|
|
|
|
+ cursor = sqlite_conn.cursor()
|
|
|
|
|
+ # 获取未同步的数据
|
|
|
|
|
+ cursor.execute("SELECT id, data_json FROM measure_orders WHERE sync_status = 0")
|
|
|
|
|
+ rows = cursor.fetchall()
|
|
|
|
|
+
|
|
|
|
|
+ if not rows:
|
|
|
|
|
+ print("No pending records to sync.")
|
|
|
|
|
+ return
|
|
|
|
|
+
|
|
|
|
|
+ print(f"Syncing {len(rows)} records to external system...")
|
|
|
|
|
+
|
|
|
|
|
+ # Create output directory
|
|
|
|
|
+ output_dir = 'eep_packages'
|
|
|
|
|
+ if not os.path.exists(output_dir):
|
|
|
|
|
+ os.makedirs(output_dir)
|
|
|
|
|
+
|
|
|
|
|
+ for row in rows:
|
|
|
|
|
+ order_id = row[0]
|
|
|
|
|
+ data_json = row[1]
|
|
|
|
|
+ data = json.loads(data_json)
|
|
|
|
|
+ try:
|
|
|
|
|
+ print(f"Processing order {data.get('header', {}).get('measure_no', 'Unknown')} (ID: {order_id})...")
|
|
|
|
|
+
|
|
|
|
|
+ # 1. Generate EEP Package
|
|
|
|
|
+ eep_path, files_info = create_eep_package(data, output_dir)
|
|
|
|
|
+
|
|
|
|
|
+ # 2. Upload EEP Package
|
|
|
|
|
+ if upload_eep_package(eep_path, data, files_info):
|
|
|
|
|
+ # 3. Update Sync Status
|
|
|
|
|
+ cursor.execute("UPDATE measure_orders SET sync_status = 1 WHERE id = ?", (order_id,))
|
|
|
|
|
+ print(f"Order {order_id} synced successfully.")
|
|
|
|
|
+ else:
|
|
|
|
|
+ print(f"Failed to upload order {order_id}.")
|
|
|
|
|
+
|
|
|
|
|
+ except Exception as e:
|
|
|
|
|
+ print(f"Failed to sync order {order_id}: {e}")
|
|
|
|
|
+ import traceback
|
|
|
|
|
+ traceback.print_exc()
|
|
|
|
|
+
|
|
|
|
|
+ sqlite_conn.commit()
|
|
|
|
|
+ print("Sync completed.")
|
|
|
|
|
+
|
|
|
|
|
+if __name__ == "__main__":
|
|
|
|
|
+ sqlite_conn = init_sqlite()
|
|
|
|
|
+ print("Fetching data from MySQL...")
|
|
|
|
|
+ data = fetch_from_mysql()
|
|
|
|
|
+
|
|
|
|
|
+ if data is not None:
|
|
|
|
|
+ print(f"Caching {len(data)} records...")
|
|
|
|
|
+ cache_data(sqlite_conn, data)
|
|
|
|
|
+
|
|
|
|
|
+ # Print sample structure
|
|
|
|
|
+ if len(data) > 0:
|
|
|
|
|
+ sample = data[0]
|
|
|
|
|
+ print("\nSample Data Structure Cached:")
|
|
|
|
|
+ print(f"Header Keys: {list(sample['header'].keys())}")
|
|
|
|
|
+ print(f"Statistics Keys: {list(sample['statistics'].keys())}")
|
|
|
|
|
+ print(f"Attachments Count: {len(sample['attachments'])}")
|
|
|
|
|
+
|
|
|
|
|
+ sync_to_external_system(sqlite_conn)
|
|
|
|
|
+ else:
|
|
|
|
|
+ print("Failed to fetch data from MySQL. Please check your connection settings.")
|
|
|
|
|
+
|
|
|
|
|
+ sqlite_conn.close()
|
|
|
|
|
+
|