from calendar import c 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 import uuid from decimal import Decimal import sys import configparser # ========== 配置文件加载 ========== # exe / 脚本同目录下的 config.ini,首次运行自动生成,用记事本即可修改 if getattr(sys, 'frozen', False): BASE_DIR = os.path.dirname(sys.executable) else: BASE_DIR = os.path.dirname(os.path.abspath(__file__)) CONFIG_FILE = os.path.join(BASE_DIR, 'config.ini') DEFAULT_CONFIG = """# ============================================ # 沪武档案同步玄海 - 运行配置 # 修改本文件后重新运行程序即可生效,无需重新生成 exe # ============================================ [mysql] # 业务数据库连接(连接失败请检查 VPN 或修改以下地址/账号) host = 172.16.10.152 port = 15606 user = root password = 84853032 database = dnn202500200jy connect_timeout = 10 [api] # 档案系统上传接口 api_url = http://218.94.73.106:8081/api/eps9/tyjk/api/data/asip/HWKJLZF # 附件文件下载地址前缀(数据库中为相对路径时自动拼接) file_base_url = https://oss.dnnbuild.com [archive] # 归档单位(默认值,数据缺失时使用) archive_unit = 无锡至宜兴高速公路雪堰枢纽至西坞枢纽段扩建工程 # 文件目录署名单位 catalog_signing_unit = 沪武高速公路太仓至常州段扩建工程苏州段 [local] # 本地 SQLite 缓存文件名(放在 exe 同目录) sqlite_db = measure_data_cache.db # EEP 包输出目录(放在 exe 同目录) output_dir = eep_packages """ def load_config(): """加载 config.ini;不存在时自动写入默认配置。返回 (DB_CONFIG, API_URL, FILE_BASE_URL, ARCHIVE_UNIT, CATALOG_SIGNING_UNIT, SQLITE_DB, OUTPUT_DIR)。""" if not os.path.exists(CONFIG_FILE): try: with open(CONFIG_FILE, 'w', encoding='utf-8') as f: f.write(DEFAULT_CONFIG) print(f"[配置] 未找到配置文件,已自动生成: {CONFIG_FILE}") print("[配置] 可关闭程序,用记事本修改该文件后重新运行。") print() except Exception as e: print(f"[配置][警告] 无法写入配置文件 {CONFIG_FILE}: {e},改用内置默认配置。") # interpolation=None:密码中出现 % 等特殊字符也不会报错 cfg = configparser.ConfigParser(interpolation=None) cfg.optionxform = str # 保留键名大小写 try: cfg.read(CONFIG_FILE, encoding='utf-8-sig') except Exception as e: print(f"[配置][警告] 读取配置文件失败({e}),改用内置默认配置。") cfg = configparser.ConfigParser(interpolation=None) cfg.optionxform = str cfg.read_string(DEFAULT_CONFIG) def get(section, key, fallback): try: value = cfg.get(section, key) return value if value != '' else fallback except Exception: return fallback db_config = { 'user': get('mysql', 'user', 'root'), 'password': get('mysql', 'password', '84853032'), 'host': get('mysql', 'host', '172.16.10.152'), 'port': int(get('mysql', 'port', '15606')), 'database': get('mysql', 'database', 'dnn202500200jy'), 'use_pure': True, 'connect_timeout': int(get('mysql', 'connect_timeout', '10')), } api_url = get('api', 'api_url', "http://218.94.73.106:8081/api/eps9/tyjk/api/data/asip/HWKJLZF") file_base_url = get('api', 'file_base_url', "https://oss.dnnbuild.com") archive_unit = get('archive', 'archive_unit', "无锡至宜兴高速公路雪堰枢纽至西坞枢纽段扩建工程") catalog_signing_unit = get('archive', 'catalog_signing_unit', "沪武高速公路太仓至常州段扩建工程苏州段") sqlite_db = get('local', 'sqlite_db', 'measure_data_cache.db') output_dir = get('local', 'output_dir', 'eep_packages') if not os.path.isabs(sqlite_db): sqlite_db = os.path.join(BASE_DIR, sqlite_db) if not os.path.isabs(output_dir): output_dir = os.path.join(BASE_DIR, output_dir) return db_config, api_url, file_base_url, archive_unit, catalog_signing_unit, sqlite_db, output_dir (DB_CONFIG, API_URL, FILE_BASE_URL, ARCHIVE_UNIT, CATALOG_SIGNING_UNIT, SQLITE_DB, OUTPUT_DIR) = load_config() # XML 模板 XML_DESC_TEMPLATE = """ <文件说明> <载体编号>{archive_id} <载体类型>在线 <载体容量>{size} <制作时间>{date} <载体制作单位名称>沪武高速公路太仓至常州段扩建工程苏州段 <载体保管单位名称>沪武高速公路太仓至常州段扩建工程苏州段 <载体检查单位名称>沪武高速公路太仓至常州段扩建工程苏州段 <载体申请单位名称>沪武高速公路太仓至常州段扩建工程苏州段 <年度>{year} <归档文件数量>{file_count} <归档类型>文件 <起始件号> <截至件号> <信息系统名称>档案综合利用平台 {process_xml}""" XML_PROCESS_NODE_TEMPLATE = """ <节点> <节点标识>{node_id} <节点名称>{name} <类型>{type} <机构名称>{org_name} <办理人>{operator_name} <创建时间>{created_time} <办理时间>{operate_time} <审核意见>{opinion} <审核结论>{conclusion} """ XML_CATALOG_TEMPLATE = """ <文件目录> <归档文件> <处理部门> <公文标识> <文件类型>发文 <份号> <密级和保密期限>普通 <紧急程度>内部资料 <发文机关标志> <发文字号>{doc_num} <签发人>null <标题>{title} <主送机关> <附件说明> <发文机关或签发人署名>{signing_unit} <成文日期>{date_compact} <附注> <抄送机关> <印发机关> <印发日期> <发布层次> <档号>{archive_id} <年度>{year} <保管期限> <机构或问题> <当前计量期>{current_period} <计量号>{measure_number} <起始日期>{period_start} <终止日期>{period_end} <制表人标识>{tabulator_id} <制表人名称>{tabulator_name} <制表日期>{tabulation_date} <到上期末累计完成额>{completed_last_period} <本期完成额>{current_period_amount} <本期末累计额>{completed_cumulative} <数字对象标识> <环境信息> <软件环境> <硬件环境> <处理类型> <处理者> <处理时间> <处理结果> <文件> {file_details} """ XML_FILE_DETAIL_TEMPLATE = """ <文件详情> <文件路径>{path} <文件大小>{size} <数字摘要>{md5} <文件单位>B <文件名称>{name} <文件类型>{type} """ XML_METADATA_TEMPLATE = """ <电子文件封装包 name="M201"> <封装包格式描述 name="M202">本EEP根据中华人民共和国档案行业标准DA/T 48-2009《基于XML的电子文件封装规范》生成 <版本 name="M203">2009 <被签名对象 name="M204"> <封装包类型 name="M205" /> <封装包类型描述 name="M206" /> <封装包创建时间 name="M207">{date} <封装包创建单位 name="M208">{archive_unit} <封装内容 name="M209"> <文件实体块 name="M210"> <文件实体 name="M211"> <聚合层次 name="M1" /> <来源 name="M2"> <档案馆名称 name="M3">xx <档案馆代码 name="M4" /> <全宗名称 name="M5">{archive_unit} <立档单位名称 name="M6">{archive_unit} <电子文件号 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_compact} <文种 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} <文件实体关系 name="M222"> <文件标识符 name="M223">{file_id} <被关联文件标识符 name="M224" /> <关系类型 name="M87" /> <关系 name="M87" /> <关系描述 name="M88" /> <业务实体块 name="M225"> {business_entities_xml} <机构人员实体块 name="M229"> {person_entities_xml} <电子签名块 name="M201"> <电子签名 name="M57"> <签名标识符 name="M234" /> <签名规则 name="M58" /> <签名时间 name="M59" /> <签名人 name="M60" /> <签名结果 name="M61" /> <签名算法标识 name="M64" /> <锁定签名 name="M201"> <被锁定签名标识符 name="M237" /> <签名规则 name="M58" /> <签名时间 name="M59" /> <签名人 name="M60" /> <签名结果 name="M61" /> <证书块 name="M235"> <证书 name="M62" /> <证书引证 name="M63" /> <签名算法标识 name="M64" /> """ XML_DOC_TEMPLATE = """ <文档> <文档标识符 name="M215">{md5} <文档序号 name="M19" /> <文档主从声明 name="M216" /> <题名 name="M22">{doc_title} <文档数据 name="M217"> <编码 name="M218"> <电子属性 name="M46"> <格式信息 name="M47">{ext} <计算机文件名 name="M48">{filename} <计算机文件大小 name="M49">{size} <文档创建程序 name="M50" /> <信息系统描述 name="M51" /> <计算机文件创建时间 name="M101">{date_compact} <数字化属性 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">{path} <脱机载体编号 name="M67" /> <脱机载体存址 name="M68" /> <缩微号 name="M69" /> <权限管理 name="M70"> <知识产权说明 name="M71" /> <控制标识 name="M74" /> <固化信息块 name="P16"> <固化信息 name="P17"> <类型 name="P18" /> <值 name="P19" /> """ XML_BUSINESS_ENTITY_TEMPLATE = """ <业务实体 name="M226"> <业务标识符 name="M227">{business_id} <机构人员标识符 name="M228">{operator_id} <文件标识符 name="M223">{file_id} <业务状态 name="M80">历史行为 <业务行为 name="M81">审批 <行为时间 name="M82">{action_time} <行为依据 name="M83">{action_basis} <行为描述 name="M84">{description} <机构人员名称 name="M77">{operator_name} <组织机构代码 name="M78">{org_name} """ XML_PERSON_ENTITY_TEMPLATE = """ <机构人员实体 name="M230"> <机构人员标识符 name="M210">{operator_id} <机构人员类型 name="M76">经办人 <机构人员名称 name="M77">{operator_name} <组织机构代码 name="M78">{org_name} <个人职位 name="M79" /> """ XML_PERSON_RELATION_TEMPLATE = """ <机构人员实体关系 name="M231"> <机构人员标识符 name="M228">{operator_id} <被关联机构人员标识符 name="M76" /> <关系类型 name="M77" /> <关系 name="M78" /> <关系描述 name="M79" /> """ # 流程节点 operateType -> 审核结论 映射 (参考 FlowProcessServiceImpl.resolveHisActivityStatus) OPERATE_TYPE_CONCLUSION = { 'pass': '通过', 'agree': '通过', 'start': '通过', 'reject': '驳回', 'deliver': '转办', 'stop': '终止', 'read': '已阅', 'addAssignee': '后加签', 'insertAssignee': '前加签', 'assignReject': '指定回退', } # 流程节点查询 SQL: 从 Flowable 历史表还原 /api/flow/process/flow/detail 的 historyFlows 数据 QUERY_FLOW_NODES = """ SELECT ai.ID_ AS node_id, ai.TASK_ID_ AS task_id, ai.ACT_ID_ AS task_def_key, ai.ACT_NAME_ AS task_name, ai.START_TIME_ AS create_time, ai.END_TIME_ AS end_time, ai.ASSIGNEE_ AS assignee, u.account AS assignee_account, u.real_name AS assignee_name, d.full_name AS org_name, (SELECT v.TEXT_ FROM ACT_HI_VARINST v WHERE v.TASK_ID_ = ai.TASK_ID_ AND v.NAME_ = 'operateType' LIMIT 1) AS operate_type, (SELECT CONVERT(cm.FULL_MSG_ USING utf8mb4) FROM ACT_HI_COMMENT cm WHERE cm.TASK_ID_ = ai.TASK_ID_ AND cm.TYPE_ = 'comment' ORDER BY cm.TIME_ LIMIT 1) AS comment_msg FROM ACT_HI_ACTINST ai LEFT JOIN blade_user u ON u.id = ai.ASSIGNEE_ AND u.is_deleted = 0 LEFT JOIN blade_dept d ON FIND_IN_SET(d.id, u.dept_id) AND d.is_deleted = 0 WHERE ai.PROC_INST_ID_ = %s AND ai.ACT_TYPE_ = 'userTask' ORDER BY IFNULL(ai.END_TIME_, NOW()), ai.START_TIME_ """ def fetch_flow_nodes(cursor, flow_process_inst_id): """获取计量单审核过程节点列表 (等价于 /api/flow/process/flow/detail 的 flow 数据)。 只保留已办结 (END_TIME_ 非空) 且带 operateType 的节点,与后端 FlowProcessServiceImpl.resolveHisActivityStatus 的过滤逻辑一致。 """ if not flow_process_inst_id: return [] # flow_process_inst.id -> proc_inst_id cursor.execute( "SELECT proc_inst_id FROM flow_process_inst WHERE id = %s", (flow_process_inst_id,) ) inst_row = cursor.fetchone() if not inst_row or not inst_row.get('proc_inst_id'): return [] cursor.execute(QUERY_FLOW_NODES, (inst_row['proc_inst_id'],)) rows = cursor.fetchall() def fmt_time(value): if not value: return '' if isinstance(value, (datetime.datetime, datetime.date)): return value.isoformat(timespec='milliseconds') if isinstance(value, datetime.datetime) else value.isoformat() return str(value) nodes = [] for row in rows: # 未办结节点无 operateType, 后端同样跳过 if not row.get('end_time') or not row.get('operate_type'): continue operate_type = str(row['operate_type']) comment = row.get('comment_msg') or '' if isinstance(comment, (bytes, bytearray)): try: comment = comment.decode('utf-8') except Exception: comment = '' nodes.append({ 'id': row.get('node_id') or '', 'name': row.get('task_name') or '', 'type': '计量支付', 'orgName': row.get('org_name') or ARCHIVE_UNIT, 'operatorId': str(row.get('assignee') or row.get('assignee_account') or ''), 'operatorName': row.get('assignee_name') or '', 'createdTime': fmt_time(row.get('create_time')), 'operateTime': fmt_time(row.get('end_time')), 'opinion': comment, 'conclusion': OPERATE_TYPE_CONCLUSION.get(operate_type, operate_type), }) return nodes def build_process_xml(process_nodes): """把审核过程节点渲染成 说明文件.xml 的 <审核过程> 片段。""" if not process_nodes: return " <审核过程>" node_xml = "\n".join( XML_PROCESS_NODE_TEMPLATE.format( node_id=xml_escape(node.get('id')), name=xml_escape(node.get('name')), type=xml_escape(node.get('type')), org_name=xml_escape(node.get('orgName')), operator_name=xml_escape(node.get('operatorName')), created_time=xml_escape(node.get('createdTime')), operate_time=xml_escape(node.get('operateTime')), opinion=xml_escape(node.get('opinion')), conclusion=xml_escape(node.get('conclusion')), ) for node in process_nodes ) return " <审核过程>\n" + node_xml + "\n " def xml_escape(value): if value is None: return '' return (str(value) .replace('&', '&') .replace('<', '<') .replace('>', '>')) def safe_value(value, default=''): return default if value is None else value def format_date(value, fmt='%Y-%m-%d'): if not value: return '' if isinstance(value, (datetime.datetime, datetime.date)): return value.strftime(fmt) text = str(value).strip() if not text: return '' if len(text) >= 10 and text[4] == '-' and text[7] == '-': try: return datetime.datetime.strptime(text[:10], '%Y-%m-%d').strftime(fmt) except ValueError: pass if len(text) >= 8 and text.isdigit(): try: return datetime.datetime.strptime(text[:8], '%Y%m%d').strftime(fmt) except ValueError: pass return text[:10] if fmt == '%Y-%m-%d' else text def format_datetime(value): if not value: return '' if isinstance(value, datetime.datetime): return value.strftime('%Y-%m-%d %H:%M:%S') text = str(value).strip().replace('T', ' ') if not text: return '' if len(text) >= 19: return text[:19] if len(text) == 10: return text + ' 00:00:00' return text def format_amount(value): if value is None or value == '': return '0.00' try: return f"{Decimal(str(value)).quantize(Decimal('0.01')):.2f}" except Exception: return str(value) def stable_guid(seed): return uuid.uuid5(uuid.NAMESPACE_URL, str(seed)).hex.upper() def build_metadata_entities(order_data, file_id): header = order_data.get('header') or {} process_nodes = order_data.get('process') or [] business_rows = [] person_rows = [] seen_operators = set() def add_entity(operator_id, operator_name, org_name, action_time, action, description, basis='', business_id=None): operator_id = str(operator_id or '').strip() operator_name = str(operator_name or '').strip() org_name = str(org_name or '').strip() action_time = format_datetime(action_time) if not operator_id or not operator_name or not org_name or not action_time: return person_key = (operator_id, org_name) if person_key not in seen_operators: person_rows.append({ 'operator_id': operator_id, 'operator_name': operator_name, 'org_name': org_name, }) seen_operators.add(person_key) business_rows.append({ 'business_id': business_id or stable_guid(f"{file_id}:{operator_id}:{action_time}:{description}"), 'operator_id': operator_id, 'file_id': file_id, 'action_time': action_time, 'action_basis': basis, 'action': action or '审批', 'description': description or '文件审核通过', 'operator_name': operator_name, 'org_name': org_name, }) tabulator_id = header.get('tabulator_id') or order_data.get('tabulator_id') or f"OP{str(order_data.get('id'))[-12:]}" tabulator_name = header.get('tabulator') or order_data.get('tabulator_name') tabulation_date = header.get('tabulation_date') tabulator_org = header.get('tabulator_org') or header.get('contractor') or header.get('section') or ARCHIVE_UNIT add_entity( tabulator_id, tabulator_name, tabulator_org, tabulation_date, '制表', f"{tabulator_name or ''}文件制表提交".strip(), business_id=stable_guid(f"{file_id}:tabulator") ) for node in process_nodes: operator_id = node.get('operatorId') or node.get('assignee') operator_name = node.get('operatorName') org_name = node.get('orgName') or ARCHIVE_UNIT conclusion = node.get('conclusion') or '通过' action = '审批通过' if conclusion == '通过' else f"审批{conclusion}" description = f"{node.get('name') or '审批节点'}-{operator_name or ''}{action}".strip('-') add_entity( operator_id, operator_name, org_name, node.get('operateTime'), '审批', description, node.get('id') or node.get('taskId') or '', stable_guid(f"{file_id}:{node.get('id') or node.get('taskId') or node.get('operatorId')}") ) if not business_rows: fallback_id = tabulator_id or f"OP{str(order_data.get('id'))[-12:]}" fallback_name = tabulator_name or '系统管理员' fallback_org = tabulator_org fallback_time = tabulation_date or datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') add_entity(fallback_id, fallback_name, fallback_org, fallback_time, '审批', f"{fallback_name}文件审核通过", business_id=stable_guid(f"{file_id}:fallback")) business_xml = "\n".join( XML_BUSINESS_ENTITY_TEMPLATE.format(**{k: xml_escape(v) for k, v in row.items()}) for row in business_rows ) person_xml = "\n".join( XML_PERSON_ENTITY_TEMPLATE.format(**{k: xml_escape(v) for k, v in row.items()}) for row in person_rows ) if person_rows: relation_xml = "\n".join( XML_PERSON_RELATION_TEMPLATE.format(operator_id=xml_escape(row['operator_id'])) for row in person_rows ) person_xml = person_xml + "\n" + relation_xml return business_xml, person_xml def init_sqlite(): db_parent = os.path.dirname(SQLITE_DB) if db_parent and not os.path.exists(db_parent): os.makedirs(db_parent) 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() tabulator_name = None tabulator_id = str(order.get('tabulator') or '') tabulator_org = None if order.get('tabulator'): cursor.execute(""" SELECT u.id, u.account, u.real_name, d.full_name AS org_name FROM blade_user u LEFT JOIN blade_dept d ON FIND_IN_SET(d.id, u.dept_id) AND d.is_deleted = 0 WHERE u.id = %s AND u.is_deleted = 0 LIMIT 1 """, (order['tabulator'],)) user_row = cursor.fetchone() if user_row: tabulator_name = user_row['real_name'] tabulator_id = str(user_row.get('id') or order.get('tabulator') or '') tabulator_org = user_row.get('org_name') # 5. 获取附件 # 关联 mp_measure_attachments 和 tb_file (corrected from blade_attach) query_attachments = """ 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 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 ORDER BY a.sort, a.id """ cursor.execute(query_attachments, (order_id,)) attachments = cursor.fetchall() # 6. 获取审核过程 (流程节点) process_nodes = fetch_flow_nodes(cursor, order.get('flow_process_inst_id')) # 格式化附件数据 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, 'hash': att.get('file_hash') or '', 'fileCreateTime': att.get('file_create_time').isoformat() if isinstance(att.get('file_create_time'), (datetime.date, datetime.datetime)) else att.get('file_create_time') }) # 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'), 'measure_period': order.get('end_date').strftime('%Y%m') if order.get('end_date') else None, 'section': contract.get('section_id') if contract else None, 'measure_method': '分解计量', '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_id': tabulator_id, 'tabulator': tabulator_name, 'tabulator_org': tabulator_org } # 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, 'process': process_nodes }) 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 continue # 存储附件信息 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 header = order_data.get('header') or {} statistics = order_data.get('statistics') or {} measure_no = header.get('measure_no') or '' title = f"计量单-{measure_no}" tabulation_raw = header.get('tabulation_date') period_end_raw = header.get('period_end') current_period = header.get('measure_period') or format_date(period_end_raw, '%Y%m') tabulator_id = header.get('tabulator_id') or f"OP{order_id[-12:]}" if not current_period and measure_no and len(measure_no.split('-')) >= 2: current_period = measure_no.split('-')[-2] year_source = tabulation_raw or period_end_raw year = int(format_date(year_source, '%Y') or datetime.datetime.now().year) date_str = format_date(tabulation_raw) or datetime.datetime.now().strftime('%Y-%m-%d') date_compact = format_date(tabulation_raw, '%Y%m%d') or datetime.datetime.now().strftime('%Y%m%d') file_id = stable_guid(f"file:{archive_id}") # 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': (att.get('hash') or fmd5).lower(), 'ext': fext, 'type': '附件', 'created': att.get('fileCreateTime') or tabulation_raw or date_str }) # 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), process_xml=build_process_xml(order_data.get('process') or []) ) 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_values = { 'doc_num': measure_no, 'title': title, 'date': date_str, 'date_compact': date_compact, 'archive_id': archive_id, 'year': year, 'file_details': file_details_xml, 'signing_unit': CATALOG_SIGNING_UNIT, 'current_period': current_period, 'measure_number': header.get('measure_no') or '', 'period_start': format_date(header.get('period_start')), 'period_end': format_date(header.get('period_end')), 'tabulator_id': tabulator_id, 'tabulator_name': header.get('tabulator') or '', 'tabulation_date': format_date(tabulation_raw), 'completed_last_period': format_amount(statistics.get('completed_last_period')), 'current_period_amount': format_amount(statistics.get('subtotal')), 'completed_cumulative': format_amount(statistics.get('completed_cumulative')), } catalog_xml = XML_CATALOG_TEMPLATE.format(**{key: xml_escape(value) if key != 'file_details' else value for key, value in catalog_values.items()}) with open(os.path.join(pkg_root, '文件目录.xml'), 'w', encoding='utf-8') as f: f.write(catalog_xml) # 3. 文件元数据.xml docs_xml = "" for file_info in files_info: doc_values = { 'date': date_str, 'md5': file_info['md5'], 'ext': file_info['ext'], 'filename': file_info['name'], 'size': file_info['size'], 'date_compact': format_date(file_info.get('created'), '%Y%m%d') or date_compact, 'doc_title': file_info['name'], 'path': file_info['path'], } docs_xml += XML_DOC_TEMPLATE.format(**{key: xml_escape(value) for key, value in doc_values.items()}) + "\n" business_entities_xml, person_entities_xml = build_metadata_entities(order_data, file_id) metadata_values = { 'date': date_str, 'year': year, 'title': title, 'date_compact': date_compact, 'docs': docs_xml, 'file_id': file_id, 'archive_unit': ARCHIVE_UNIT, 'business_entities_xml': business_entities_xml, 'person_entities_xml': person_entities_xml, } 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()}) 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}") # 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 = OUTPUT_DIR if not os.path.exists(output_dir): os.makedirs(output_dir) for row in rows: order_id = row[0] data_json = row[1] # if order_id == '2005072020533338113': # print(f"Debug: {order_id}") # else: # continue 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,)) sqlite_conn.commit() # 立即提交事务 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__": print(f"配置文件: {CONFIG_FILE}") print(f"MySQL: {DB_CONFIG['user']}@{DB_CONFIG['host']}:{DB_CONFIG['port']}/{DB_CONFIG['database']}") print(f"本地缓存: {SQLITE_DB}") print() 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()