| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223 |
- 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
- # 数据库配置 (从 application-dev.yml 获取)
- # 如果连接失败,请检查 VPN 或修改此处的 host/port/user/password
- DB_CONFIG = {
- 'user': 'root',
- 'password': '84853032',
- 'host': '172.16.10.152',
- 'port': 15606,
- 'database': 'dnn202500200jy',
- 'use_pure': True,
- '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_UNIT = "无锡至宜兴高速公路雪堰枢纽至西坞枢纽段扩建工程"
- CATALOG_SIGNING_UNIT = "沪武高速公路太仓至常州段扩建工程苏州段"
- # XML 模板
- XML_DESC_TEMPLATE = """<?xml version="1.0" encoding="UTF-8"?>
- <文件说明>
- <载体编号>{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 = """<?xml version="1.0" encoding="UTF-8"?>
- <文件目录>
- <归档文件>
- <处理部门></处理部门>
- <公文标识></公文标识>
- <文件类型>发文</文件类型>
- <份号></份号>
- <密级和保密期限>普通</密级和保密期限>
- <紧急程度>内部资料</紧急程度>
- <发文机关标志></发文机关标志>
- <发文字号>{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 = """<?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">{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" />
- </机构人员实体关系>"""
- # 本地缓存文件
- SQLITE_DB = 'measure_data_cache.db'
- # 流程节点 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():
- 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 = '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]
- # 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__":
- 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()
-
|