CI / check (push) Failing after 15m48s
Signed-off-by: 南通一次元科技有限公司 <guwangtu@icimeta.com>
1835 lines
79 KiB
Python
1835 lines
79 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""审计管理平台升级版服务层(真实数据)
|
||
|
||
在现有四套系统之上补充:
|
||
- 审计驾驶舱:聚合真实审计项目 / 风险 / 合同 / 文档数据
|
||
- 计划与项目:直接读取现有审计库中的年度计划、项目、步骤、资料
|
||
- 整改管理:新建整改台账,可从既有审计分析结果、检查风险数据导入
|
||
- 数据资源:展示真实数据库与文件资源,支持外部数据源配置与连接测试
|
||
- 模型管理:内置审计模型,运行结果是真实 SQL 查询结果
|
||
- ETL 导入:真实上传 CSV / Excel 并解析入临时结果表
|
||
- 流程配置:整改 / 项目审批流程模板
|
||
所有新增配置数据保存在 digital_audit.db,不改动原业务库。
|
||
"""
|
||
import csv
|
||
import io
|
||
import json
|
||
import re
|
||
import sqlite3
|
||
import datetime
|
||
from pathlib import Path
|
||
import operator_context as opctx
|
||
|
||
BASE_DIR = Path(__file__).parent.resolve()
|
||
WORKSPACE = BASE_DIR.parent
|
||
DB_PATH = BASE_DIR / "digital_audit.db"
|
||
|
||
AUDIT_DB = WORKSPACE / "审计项目管理平台" / "audit_data.db"
|
||
RISK_DB = WORKSPACE / "风险管理项目" / "risk_data.db"
|
||
CONTRACT_DB = WORKSPACE / "合同审核管理平台" / "contract.db"
|
||
AUDIT_UPLOADS = WORKSPACE / "审计项目管理平台" / "uploads"
|
||
CONTRACT_FILES = WORKSPACE / "合同审核管理平台" / "合同"
|
||
REPORT_FILES = WORKSPACE / "合同审核管理平台" / "报告"
|
||
|
||
STATUS_RECT = ["待整改", "整改中", "待验收", "已验收", "已超期"]
|
||
|
||
|
||
def _now():
|
||
return datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
||
|
||
|
||
def _today():
|
||
return datetime.date.today().strftime("%Y-%m-%d")
|
||
|
||
|
||
def _conn():
|
||
conn = sqlite3.connect(str(DB_PATH), timeout=10)
|
||
conn.row_factory = sqlite3.Row
|
||
conn.execute("PRAGMA journal_mode=WAL")
|
||
return conn
|
||
|
||
|
||
def _ro(path):
|
||
conn = sqlite3.connect(f"file:{Path(path).as_posix()}?mode=ro", uri=True, timeout=10)
|
||
conn.row_factory = sqlite3.Row
|
||
return conn
|
||
|
||
|
||
def _json(text, default):
|
||
try:
|
||
return json.loads(text) if text else default
|
||
except Exception:
|
||
return default
|
||
|
||
|
||
def _dir_stat(path):
|
||
if not path.exists():
|
||
return {"count": 0, "size": 0}
|
||
files = [p for p in path.rglob("*") if p.is_file()]
|
||
return {"count": len(files), "size": sum(p.stat().st_size for p in files)}
|
||
|
||
|
||
def _db_stat(path):
|
||
try:
|
||
conn = _ro(path)
|
||
tables = [r[0] for r in conn.execute(
|
||
"SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'")]
|
||
rows = 0
|
||
for t in tables:
|
||
try:
|
||
rows += conn.execute(f"SELECT COUNT(*) FROM {t}").fetchone()[0]
|
||
except Exception:
|
||
pass
|
||
conn.close()
|
||
return {"size": path.stat().st_size if path.exists() else 0, "tables": len(tables), "rows": rows}
|
||
except Exception:
|
||
return {"size": path.stat().st_size if path.exists() else 0, "tables": 0, "rows": 0}
|
||
|
||
|
||
def log(conn, action, detail):
|
||
conn.execute("INSERT INTO da_logs(action, detail, operator, created_at) VALUES (?,?,?,?)",
|
||
(action, detail, opctx.get_operator(), _now()))
|
||
|
||
|
||
# ==================== 初始化 ====================
|
||
def init_db():
|
||
conn = _conn()
|
||
conn.executescript("""
|
||
CREATE TABLE IF NOT EXISTS da_rectifications (
|
||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||
project_id INTEGER, project_name TEXT, issue TEXT, dept TEXT,
|
||
level TEXT DEFAULT '中', status TEXT DEFAULT '待整改', deadline TEXT,
|
||
owner TEXT, progress INTEGER DEFAULT 0,
|
||
q1 TEXT DEFAULT '', q2 TEXT DEFAULT '', q3 TEXT DEFAULT '',
|
||
q4 TEXT DEFAULT '', q5 TEXT DEFAULT '', q6 TEXT DEFAULT '',
|
||
result TEXT DEFAULT '', source_type TEXT DEFAULT '', source_id INTEGER DEFAULT 0,
|
||
created_at TEXT
|
||
);
|
||
CREATE TABLE IF NOT EXISTS da_external_sources (
|
||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||
name TEXT, type TEXT, endpoint TEXT, auth_type TEXT, schedule TEXT,
|
||
status TEXT DEFAULT '待修复', last_error TEXT, last_test TEXT, created_at TEXT
|
||
);
|
||
CREATE TABLE IF NOT EXISTS da_models (
|
||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||
name TEXT, category TEXT, risk_level TEXT, rule_type TEXT,
|
||
description TEXT, query_key TEXT, expression TEXT,
|
||
status TEXT DEFAULT '启用', run_count INTEGER DEFAULT 0, created_at TEXT
|
||
);
|
||
CREATE TABLE IF NOT EXISTS da_model_runs (
|
||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||
model_id INTEGER, summary TEXT, matched INTEGER DEFAULT 0,
|
||
detail TEXT, created_at TEXT
|
||
);
|
||
CREATE TABLE IF NOT EXISTS da_workflows (
|
||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||
name TEXT, business TEXT, nodes TEXT, status TEXT DEFAULT '启用', created_at TEXT
|
||
);
|
||
CREATE TABLE IF NOT EXISTS da_etl_tasks (
|
||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||
name TEXT, source_file TEXT, target_table TEXT, status TEXT DEFAULT '已导入',
|
||
row_count INTEGER DEFAULT 0, last_run TEXT, created_at TEXT
|
||
);
|
||
CREATE TABLE IF NOT EXISTS da_etl_results (
|
||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||
task_id INTEGER, data TEXT, created_at TEXT
|
||
);
|
||
CREATE TABLE IF NOT EXISTS da_rule_categories (
|
||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||
name TEXT, parent_id INTEGER DEFAULT 0, sort INTEGER DEFAULT 0
|
||
);
|
||
CREATE TABLE IF NOT EXISTS da_rules (
|
||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||
code TEXT, name TEXT, category_id INTEGER, category_name TEXT,
|
||
risk_level TEXT DEFAULT 'R2', rule_type TEXT, params TEXT,
|
||
tags TEXT, description TEXT, status TEXT DEFAULT '启用',
|
||
version INTEGER DEFAULT 1, created_at TEXT, updated_at TEXT
|
||
);
|
||
CREATE TABLE IF NOT EXISTS da_tasks (
|
||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||
name TEXT, task_type TEXT, project_id INTEGER, project_name TEXT,
|
||
rule_ids TEXT, status TEXT DEFAULT '待执行', progress INTEGER DEFAULT 0,
|
||
doc_total INTEGER DEFAULT 0, hit_total INTEGER DEFAULT 0,
|
||
mode TEXT DEFAULT '正式运行', created_at TEXT, started_at TEXT, finished_at TEXT
|
||
);
|
||
CREATE TABLE IF NOT EXISTS da_task_hits (
|
||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||
task_id INTEGER, rule_id INTEGER, rule_name TEXT, risk_level TEXT,
|
||
doc_id INTEGER, doc_title TEXT, hit_type TEXT, snippet TEXT,
|
||
description TEXT, created_at TEXT
|
||
);
|
||
CREATE TABLE IF NOT EXISTS da_parsed_docs (
|
||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||
filename TEXT, file_type TEXT, mode TEXT, status TEXT,
|
||
pages INTEGER DEFAULT 0, char_count INTEGER DEFAULT 0,
|
||
preview TEXT, content TEXT, error TEXT, created_at TEXT
|
||
);
|
||
CREATE TABLE IF NOT EXISTS da_pulled_data (
|
||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||
source_id INTEGER, source_name TEXT, pull_type TEXT,
|
||
record_count INTEGER DEFAULT 0, columns TEXT, data TEXT,
|
||
status TEXT DEFAULT '成功', error TEXT, created_at TEXT
|
||
);
|
||
CREATE TABLE IF NOT EXISTS da_logs (
|
||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||
action TEXT, detail TEXT, operator TEXT, created_at TEXT
|
||
);
|
||
""")
|
||
conn.executescript("""
|
||
CREATE INDEX IF NOT EXISTS idx_da_tasks_status ON da_tasks(status);
|
||
CREATE INDEX IF NOT EXISTS idx_da_tasks_schedule ON da_tasks(schedule_type,next_run);
|
||
CREATE INDEX IF NOT EXISTS idx_da_tasks_project ON da_tasks(project_id);
|
||
CREATE INDEX IF NOT EXISTS idx_da_rules_status ON da_rules(status,publish_status);
|
||
CREATE INDEX IF NOT EXISTS idx_da_task_hits_task ON da_task_hits(task_id);
|
||
CREATE INDEX IF NOT EXISTS idx_da_logs_created ON da_logs(created_at);
|
||
CREATE INDEX IF NOT EXISTS idx_da_parsed_created ON da_parsed_docs(created_at);
|
||
CREATE INDEX IF NOT EXISTS idx_da_rect_status ON da_rectifications(status);
|
||
CREATE INDEX IF NOT EXISTS idx_da_rect_deadline ON da_rectifications(deadline);
|
||
""")
|
||
conn.commit()
|
||
if conn.execute("SELECT COUNT(*) FROM da_models").fetchone()[0] == 0:
|
||
_seed_models(conn)
|
||
if conn.execute("SELECT COUNT(*) FROM da_workflows").fetchone()[0] == 0:
|
||
_seed_workflows(conn)
|
||
if conn.execute("SELECT COUNT(*) FROM da_rules").fetchone()[0] == 0:
|
||
_seed_rules(conn)
|
||
_ensure_rule_columns(conn)
|
||
_ensure_task_columns(conn)
|
||
_seed_advanced_rules(conn)
|
||
conn.close()
|
||
|
||
|
||
def _seed_models(conn):
|
||
presets = [
|
||
("合同风险等级分布", "合同审计类", "R2", "统计分析", "统计合同审核后的风险等级分布", "contract_risk"),
|
||
("高风险合同清单", "合同审计类", "R1", "疑点筛查", "筛出风险等级为高、极高的合同,需重点复核", "contract_high"),
|
||
("风险清单等级分布", "财务合规类", "R2", "统计分析", "统计风险清单中高/中/低风险点的数量和占比", "risk_level"),
|
||
("高风险科室分布", "财务合规类", "R1", "疑点筛查", "统计检查风险数据中高风险问题所属科室", "risk_dept"),
|
||
("审计项目进度排行", "审计作业类", "R3", "进度分析", "按项目步骤平均进度排序,识别滞后项目", "audit_progress"),
|
||
("审计资料风险分析", "审计作业类", "R2", "统计分析", "统计已分析审计资料的风险等级分布", "doc_analysis"),
|
||
]
|
||
now = _now()
|
||
for p in presets:
|
||
conn.execute("""INSERT INTO da_models(name,category,risk_level,rule_type,description,query_key,created_at)
|
||
VALUES (?,?,?,?,?,?,?)""", p + (now,))
|
||
log(conn, "初始化", "内置审计模型初始化")
|
||
conn.commit()
|
||
|
||
|
||
def _seed_workflows(conn):
|
||
now = _now()
|
||
wfs = [
|
||
("审计项目立项审批流", "项目立项",
|
||
[{"name": "审计组长审核", "type": "或签"}, {"name": "审计科长审批", "type": "会签"},
|
||
{"name": "分管院领导审批", "type": "或签"}]),
|
||
("整改验收审批流", "整改验收",
|
||
[{"name": "责任科室提交", "type": "发起"}, {"name": "审计人员初验", "type": "或签"},
|
||
{"name": "审计科长确认", "type": "或签"}]),
|
||
("审计报告签发流", "报告签发",
|
||
[{"name": "主审编制", "type": "发起"}, {"name": "审计科长复核", "type": "会签"},
|
||
{"name": "分管领导签发", "type": "或签"}]),
|
||
]
|
||
for w in wfs:
|
||
conn.execute("INSERT INTO da_workflows(name,business,nodes,created_at) VALUES (?,?,?,?)",
|
||
(w[0], w[1], json.dumps(w[2], ensure_ascii=False), now))
|
||
log(conn, "初始化", "内置审批流程模板初始化")
|
||
conn.commit()
|
||
|
||
|
||
def _seed_rules(conn):
|
||
now = _now()
|
||
cats = ["合同审计类", "财务合规类", "采购流程类", "资产管理类", "工程造价类", "审计作业类"]
|
||
cat_ids = {}
|
||
for i, c in enumerate(cats):
|
||
cur = conn.execute("INSERT INTO da_rule_categories(name,parent_id,sort) VALUES (?,0,?)", (c, i))
|
||
cat_ids[c] = cur.lastrowid
|
||
rules = [
|
||
("合同必须包含违约责任条款", "合同审计类", "R2", "keyword_exists",
|
||
{"keywords": ["违约责任", "违约金"], "min_count": 1, "doc_types": ["合同"], "doc_title_keywords": ["合同", "协议"]},
|
||
["合规类", "合同条款"], "合同文本中应约定违约责任及违约金计算方式"),
|
||
("合同禁止绝对化免责表述", "合同审计类", "R3", "keyword_forbidden",
|
||
{"keywords": ["最终解释权", "免除全部责任", "不承担任何责任"], "doc_types": ["合同"], "doc_title_keywords": ["合同", "协议"]},
|
||
["高风险", "合同条款"], "合同中不得出现排除对方主要权利的绝对化免责条款"),
|
||
("合同金额字段完整性", "合同审计类", "R2", "keyword_exists",
|
||
{"keywords": ["合同金额", "合同总价", "总金额"], "min_count": 1, "doc_types": ["合同"], "doc_title_keywords": ["合同", "协议"]},
|
||
["金额校验类"], "合同应明确约定合同金额或总价"),
|
||
("合同争议解决方式约定", "合同审计类", "R3", "keyword_exists",
|
||
{"keywords": ["争议解决", "诉讼", "仲裁"], "min_count": 1, "doc_types": ["合同"], "doc_title_keywords": ["合同", "协议"]},
|
||
["合规类"], "合同应约定争议解决方式及管辖法院"),
|
||
("审计报告须包含整改建议", "财务合规类", "R2", "keyword_exists",
|
||
{"keywords": ["整改建议", "整改措施", "审计建议"], "min_count": 1, "doc_types": ["报告"], "doc_title_keywords": ["报告", "征求意见", "审计结果"]},
|
||
["审计质量"], "审计报告应针对发现问题提出整改建议"),
|
||
("审计资料应列明附件清单", "财务合规类", "R4", "keyword_exists",
|
||
{"keywords": ["附件清单", "附件"], "min_count": 1},
|
||
["资料完整性"], "审计资料应列明附件清单,便于归档核查"),
|
||
("采购方式合规表述", "采购流程类", "R2", "keyword_exists",
|
||
{"keywords": ["公开招标", "邀请招标", "竞争性谈判", "询价", "单一来源"], "min_count": 1, "doc_types": ["采购"], "doc_title_keywords": ["采购", "招标"]},
|
||
["合规类", "采购流程"], "采购文件应明确采购方式并符合金额标准"),
|
||
("采购公告时间节点校验", "采购流程类", "R2", "time_logic",
|
||
{"rule": "招标公告发布至开标不少于20日"},
|
||
["时间逻辑类"], "需结构化采购时间数据,当前版本登记规则、后续接入结构化数据后自动校验"),
|
||
("资产盘点应包含资产编号", "资产管理类", "R3", "keyword_exists",
|
||
{"keywords": ["资产编号", "资产编码"], "min_count": 1, "doc_types": ["盘点", "资产"], "doc_title_keywords": ["盘点", "资产"]},
|
||
["资产完整性"], "资产盘点资料应包含资产编号,便于账实核对"),
|
||
("结算书须包含工程量清单", "工程造价类", "R2", "keyword_exists",
|
||
{"keywords": ["工程量清单", "清单编号"], "min_count": 1, "doc_types": ["结算", "工程"], "doc_title_keywords": ["结算", "工程"]},
|
||
["合规类", "工程造价"], "工程结算书应包含工程量清单及单价依据"),
|
||
("施工照片EXIF信息校验", "工程造价类", "R3", "time_logic",
|
||
{"rule": "施工照片拍摄时间与施工日志一致"},
|
||
["影像审计"], "需接入图片EXIF解析,当前版本登记规则、后续接入影像审计模块"),
|
||
("审计实施方案应包含审计目标", "审计作业类", "R3", "keyword_exists",
|
||
{"keywords": ["审计目标"], "min_count": 1, "doc_types": ["方案"], "doc_title_keywords": ["审计实施方案", "审计方案", "实施计划"]},
|
||
["审计质量", "方案完整性"], "审计实施方案应明确审计目标"),
|
||
("审计实施方案应包含审计范围", "审计作业类", "R3", "keyword_exists",
|
||
{"keywords": ["审计范围"], "min_count": 1, "doc_types": ["方案"], "doc_title_keywords": ["审计实施方案", "审计方案", "实施计划"]},
|
||
["审计质量", "方案完整性"], "审计实施方案应明确审计范围"),
|
||
("审计报告应包含审计结论", "审计作业类", "R2", "keyword_exists",
|
||
{"keywords": ["审计结论", "审计意见"], "min_count": 1, "doc_types": ["报告"], "doc_title_keywords": ["报告", "征求意见", "审计结果"]},
|
||
["审计质量"], "审计报告应给出明确审计结论或审计意见"),
|
||
("审计报告应包含问题清单", "审计作业类", "R3", "keyword_exists",
|
||
{"keywords": ["问题清单", "发现问题", "审计发现"], "min_count": 1, "doc_types": ["报告"], "doc_title_keywords": ["报告", "征求意见", "审计结果"]},
|
||
["审计质量"], "审计报告应列明审计发现的问题清单"),
|
||
("文档相似度异常检测", "财务合规类", "R2", "similarity",
|
||
{"threshold": 0.85},
|
||
["相似度", "高风险"], "同一项目内文档相似度超过阈值,提示可能存在雷同或重复报送"),
|
||
]
|
||
for name, cat, level, rtype, params, tags, desc in rules:
|
||
code = "R-" + datetime.datetime.now().strftime("%Y%m%d") + "-" + str(100 + len(name))
|
||
conn.execute("""INSERT INTO da_rules(code,name,category_id,category_name,risk_level,rule_type,params,
|
||
tags,description,status,version,created_at,updated_at)
|
||
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)""",
|
||
(code, name, cat_ids[cat], cat, level, rtype,
|
||
json.dumps(params, ensure_ascii=False), json.dumps(tags, ensure_ascii=False),
|
||
desc, "启用", 1, now, now))
|
||
log(conn, "初始化", "内置审计规则库初始化(12 条规则)")
|
||
conn.commit()
|
||
|
||
|
||
def _ensure_rule_columns(conn):
|
||
cols = [r[1] for r in conn.execute("PRAGMA table_info(da_rules)")]
|
||
for col, ddl in [
|
||
("publish_status", "TEXT DEFAULT '已发布'"),
|
||
("review_comment", "TEXT DEFAULT ''"),
|
||
("submitted_at", "TEXT DEFAULT ''"),
|
||
("approved_at", "TEXT DEFAULT ''"),
|
||
]:
|
||
if col not in cols:
|
||
conn.execute(f"ALTER TABLE da_rules ADD COLUMN {col} {ddl}")
|
||
conn.execute("UPDATE da_rules SET publish_status='已发布' WHERE publish_status IS NULL OR publish_status=''")
|
||
conn.commit()
|
||
|
||
|
||
def _seed_advanced_rules(conn):
|
||
"""高级规则:跨文档勾稽、时间逻辑、数值范围、计算校验(按名称幂等)。"""
|
||
advanced = [
|
||
("合同金额合理范围校验", "合同审计类", "R2", "numeric_range",
|
||
{"keywords": ["合同金额", "合同总价", "总金额"], "min": 0, "max": 100000000},
|
||
["金额校验类"], "合同金额不得为负数或超过 1 亿元;超出范围提示人工复核"),
|
||
("合同签订与验收时间逻辑", "合同审计类", "R2", "time_logic",
|
||
{"a_title": ["合同", "协议"], "a_date": "签订日期|签署日期",
|
||
"b_title": ["验收", "到货"], "b_date": "验收日期|到货日期", "order": "A<=B"},
|
||
["时间逻辑类"], "合同签订日期应早于或等于验收日期"),
|
||
("合同与验收金额一致性", "合同审计类", "R2", "cross_doc",
|
||
{"a_title": ["合同", "协议"], "a_label": "合同金额|合同总价|总金额",
|
||
"b_title": ["验收", "结算"], "b_label": "验收金额|结算金额|合计金额",
|
||
"tolerance": 0.05},
|
||
["勾稽类", "金额校验类"], "验收/结算金额与合同金额偏差不得超过 5%"),
|
||
("分项金额与合计校验", "财务合规类", "R2", "calc_check",
|
||
{"total_label": "合计金额|价税合计|总额", "parts_labels": ["金额"], "tolerance": 0.01},
|
||
["计算校验类"], "重新计算分项金额合计,与文档合计字段比对,偏差超过 1% 提示异常"),
|
||
("发票号码格式规则", "财务合规类", "R3", "regex_match",
|
||
{"pattern": "\\b\\d{8,20}\\b"},
|
||
["格式校验类"], "单据中应包含 8-20 位发票号码"),
|
||
("合同付款节点与验收顺序", "合同审计类", "R3", "time_logic",
|
||
{"a_title": ["验收", "到货"], "a_date": "验收日期|到货日期",
|
||
"b_title": ["付款", "支付"], "b_date": "付款日期|支付日期", "order": "A<=B"},
|
||
["时间逻辑类"], "验收日期应早于或等于付款日期"),
|
||
]
|
||
import datetime as _dt
|
||
now = _dt.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
||
added = 0
|
||
for name, cat, level, rtype, params, tags, desc in advanced:
|
||
exists = conn.execute("SELECT 1 FROM da_rules WHERE name=?", (name,)).fetchone()
|
||
if exists:
|
||
continue
|
||
cat_row = conn.execute("SELECT id,name FROM da_rule_categories WHERE name=?", (cat,)).fetchone()
|
||
cat_id = cat_row["id"] if cat_row else None
|
||
code = "R-" + now.replace("-", "").replace(" ", "").replace(":", "")[:14]
|
||
conn.execute("""INSERT INTO da_rules(code,name,category_id,category_name,risk_level,rule_type,params,
|
||
tags,description,status,version,publish_status,created_at,updated_at)
|
||
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)""",
|
||
(code, name, cat_id, cat, level, rtype,
|
||
json.dumps(params, ensure_ascii=False), json.dumps(tags, ensure_ascii=False),
|
||
desc, "启用", 1, "已发布", now, now))
|
||
added += 1
|
||
if added:
|
||
log(conn, "初始化", f"新增高级审计规则 {added} 条")
|
||
conn.commit()
|
||
|
||
|
||
def _ensure_task_columns(conn):
|
||
cols = [r[1] for r in conn.execute("PRAGMA table_info(da_tasks)")]
|
||
for col, ddl in [
|
||
("schedule_type", "TEXT DEFAULT '立即'"),
|
||
("scheduled_at", "TEXT DEFAULT ''"),
|
||
("next_run", "TEXT DEFAULT ''"),
|
||
("run_count", "INTEGER DEFAULT 0"),
|
||
("fail_reason", "TEXT DEFAULT ''"),
|
||
("last_run", "TEXT DEFAULT ''"),
|
||
]:
|
||
if col not in cols:
|
||
conn.execute(f"ALTER TABLE da_tasks ADD COLUMN {col} {ddl}")
|
||
conn.commit()
|
||
|
||
|
||
def _parse_dt(text):
|
||
text = (text or "").strip().replace("T", " ")
|
||
if not text:
|
||
return None
|
||
for fmt in ("%Y-%m-%d %H:%M:%S", "%Y-%m-%d %H:%M", "%Y-%m-%d"):
|
||
try:
|
||
return datetime.datetime.strptime(text, fmt)
|
||
except Exception:
|
||
continue
|
||
return None
|
||
|
||
|
||
def _fmt_dt(dt):
|
||
return dt.strftime("%Y-%m-%d %H:%M:%S") if dt else ""
|
||
|
||
|
||
def _calc_next_run(schedule_type, scheduled_at, after=None):
|
||
"""计算下一次执行时间;每日/每周支持自动顺延到未来。"""
|
||
base = _parse_dt(scheduled_at)
|
||
now = after or datetime.datetime.now()
|
||
if not base:
|
||
base = now + datetime.timedelta(minutes=1)
|
||
if schedule_type == "每日":
|
||
while base <= now:
|
||
base += datetime.timedelta(days=1)
|
||
elif schedule_type == "每周":
|
||
while base <= now:
|
||
base += datetime.timedelta(days=7)
|
||
return base
|
||
|
||
|
||
# ==================== 规则库 ====================
|
||
def list_rule_categories():
|
||
conn = _conn()
|
||
try:
|
||
return [dict(r) for r in conn.execute("SELECT * FROM da_rule_categories ORDER BY sort,id").fetchall()]
|
||
finally:
|
||
conn.close()
|
||
|
||
|
||
def list_rules(category=None, risk_level=None, status=None, keyword=None):
|
||
conn = _conn()
|
||
try:
|
||
sql = "SELECT * FROM da_rules WHERE 1=1"
|
||
args = []
|
||
if category:
|
||
sql += " AND category_name=?"
|
||
args.append(category)
|
||
if risk_level:
|
||
sql += " AND risk_level=?"
|
||
args.append(risk_level)
|
||
if status:
|
||
sql += " AND status=?"
|
||
args.append(status)
|
||
if keyword:
|
||
sql += " AND (name LIKE ? OR code LIKE ?)"
|
||
args += [f"%{keyword}%", f"%{keyword}%"]
|
||
sql += " ORDER BY id DESC"
|
||
rows = []
|
||
for r in conn.execute(sql, args).fetchall():
|
||
d = dict(r)
|
||
d["params"] = _json(d.get("params"), {})
|
||
d["tags"] = _json(d.get("tags"), [])
|
||
rows.append(d)
|
||
return rows
|
||
finally:
|
||
conn.close()
|
||
|
||
|
||
def save_rule(data):
|
||
conn = _conn()
|
||
now = _now()
|
||
try:
|
||
rid = data.get("id")
|
||
params = data.get("params", {})
|
||
if isinstance(params, str):
|
||
try:
|
||
params = json.loads(params)
|
||
except Exception:
|
||
params = {}
|
||
tags = data.get("tags", [])
|
||
if isinstance(tags, str):
|
||
tags = [t.strip() for t in tags.replace(",", ",").split(",") if t.strip()]
|
||
if rid:
|
||
row = conn.execute("SELECT * FROM da_rules WHERE id=?", (rid,)).fetchone()
|
||
version = (row["version"] if row else 1) + 1
|
||
conn.execute("""UPDATE da_rules SET name=?,category_id=?,category_name=?,risk_level=?,rule_type=?,
|
||
params=?,tags=?,description=?,status=?,version=?,updated_at=? WHERE id=?""",
|
||
(data.get("name"), data.get("category_id"), data.get("category_name"),
|
||
data.get("risk_level"), data.get("rule_type"),
|
||
json.dumps(params, ensure_ascii=False), json.dumps(tags, ensure_ascii=False),
|
||
data.get("description", ""), data.get("status", "启用"), version, now, rid))
|
||
log(conn, "规则修改", f"规则 {data.get('name','')} 版本 v{version}")
|
||
conn.commit()
|
||
return rid
|
||
code = "R-" + datetime.datetime.now().strftime("%Y%m%d%H%M%S")
|
||
cur = conn.execute("""INSERT INTO da_rules(code,name,category_id,category_name,risk_level,rule_type,
|
||
params,tags,description,status,version,publish_status,created_at,updated_at)
|
||
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)""",
|
||
(code, data.get("name"), data.get("category_id"), data.get("category_name"),
|
||
data.get("risk_level", "R2"), data.get("rule_type"),
|
||
json.dumps(params, ensure_ascii=False), json.dumps(tags, ensure_ascii=False),
|
||
data.get("description", ""), data.get("status", "启用"), 1,
|
||
data.get("publish_status", "草稿"), now, now))
|
||
log(conn, "规则新增", data.get("name", ""))
|
||
conn.commit()
|
||
return cur.lastrowid
|
||
finally:
|
||
conn.close()
|
||
|
||
|
||
def delete_rule(rid):
|
||
conn = _conn()
|
||
try:
|
||
conn.execute("DELETE FROM da_rules WHERE id=?", (rid,))
|
||
log(conn, "规则删除", f"规则ID {rid}")
|
||
conn.commit()
|
||
finally:
|
||
conn.close()
|
||
|
||
|
||
# ==================== 审计任务与规则引擎 ====================
|
||
def list_tasks():
|
||
conn = _conn()
|
||
try:
|
||
rows = []
|
||
for r in conn.execute("SELECT * FROM da_tasks ORDER BY id DESC").fetchall():
|
||
d = dict(r)
|
||
d["rule_ids"] = _json(d.get("rule_ids"), [])
|
||
rows.append(d)
|
||
return rows
|
||
finally:
|
||
conn.close()
|
||
|
||
|
||
def create_task(data, run_now=None):
|
||
conn = _conn()
|
||
try:
|
||
rule_ids = data.get("rule_ids") or []
|
||
project_id = data.get("project_id")
|
||
project_name = ""
|
||
if project_id:
|
||
try:
|
||
a = _ro(AUDIT_DB)
|
||
row = a.execute("SELECT name FROM projects WHERE id=?", (project_id,)).fetchone()
|
||
project_name = row["name"] if row else ""
|
||
a.close()
|
||
except Exception:
|
||
pass
|
||
schedule_type = data.get("schedule_type") or "立即"
|
||
scheduled_at = (data.get("scheduled_at") or "").strip()
|
||
if schedule_type not in ("立即", "定时", "每日", "每周"):
|
||
schedule_type = "立即"
|
||
if schedule_type == "立即":
|
||
immediate = True
|
||
elif schedule_type == "定时":
|
||
immediate = False
|
||
else:
|
||
immediate = False
|
||
finally:
|
||
conn.close()
|
||
if run_now is not None:
|
||
immediate = bool(run_now) and schedule_type == "立即"
|
||
|
||
conn = _conn()
|
||
try:
|
||
next_run = ""
|
||
if not immediate:
|
||
next_run = _fmt_dt(_calc_next_run(schedule_type, scheduled_at))
|
||
cur = conn.execute("""INSERT INTO da_tasks(name,task_type,project_id,project_name,rule_ids,status,
|
||
progress,doc_total,hit_total,mode,created_at,schedule_type,scheduled_at,
|
||
next_run,run_count,fail_reason,last_run)
|
||
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""",
|
||
(data.get("name") or f"审计任务 {_now()}",
|
||
data.get("task_type", "综合审计"), project_id, project_name,
|
||
json.dumps(rule_ids, ensure_ascii=False), "待执行", 0, 0, 0,
|
||
data.get("mode", "正式运行"), _now(), schedule_type, scheduled_at,
|
||
next_run, 0, "", ""))
|
||
tid = cur.lastrowid
|
||
log(conn, "任务创建", f"{data.get('name','')}({len(rule_ids)} 条规则,{schedule_type})")
|
||
conn.commit()
|
||
finally:
|
||
conn.close()
|
||
if immediate:
|
||
run_task(tid)
|
||
return tid
|
||
|
||
|
||
def run_due_tasks():
|
||
"""供后台调度线程调用:执行到期的定时/每日/每周任务。"""
|
||
now = _now()
|
||
conn = _conn()
|
||
try:
|
||
rows = conn.execute("""SELECT id FROM da_tasks WHERE status IN ('待执行','已排期')
|
||
AND schedule_type IN ('定时','每日','每周')
|
||
AND next_run != '' AND next_run <= ? ORDER BY next_run""",
|
||
(now,)).fetchall()
|
||
finally:
|
||
conn.close()
|
||
ran = 0
|
||
for r in rows:
|
||
try:
|
||
run_task(r["id"])
|
||
ran += 1
|
||
except Exception:
|
||
pass
|
||
return ran
|
||
|
||
|
||
def _load_docs(project_id=None):
|
||
try:
|
||
a = _ro(AUDIT_DB)
|
||
sql = ("SELECT d.id, d.title, d.doc_type, d.content, p.name project_name "
|
||
"FROM audit_docs d LEFT JOIN projects p ON d.project_id=p.id ")
|
||
args = []
|
||
if project_id:
|
||
sql += "WHERE d.project_id=? "
|
||
args.append(project_id)
|
||
sql += "ORDER BY d.id DESC LIMIT 80"
|
||
rows = [dict(r) for r in a.execute(sql, args).fetchall()]
|
||
a.close()
|
||
return rows
|
||
except Exception:
|
||
return []
|
||
|
||
|
||
def _text_of(doc):
|
||
content = (doc.get("content") or "").strip()
|
||
if content:
|
||
return content
|
||
title = (doc.get("title") or "").strip()
|
||
return title
|
||
|
||
|
||
PROJECT_RULE_TYPES = {"similarity", "cross_doc", "time_logic"}
|
||
|
||
|
||
def _match_title(doc, keywords):
|
||
title = doc.get("title") or ""
|
||
if not keywords:
|
||
return True
|
||
return any(k in title for k in keywords)
|
||
|
||
|
||
def _extract_number(text, label_pattern):
|
||
m = re.search(r"(?:" + label_pattern + r")[^0-9\-]{0,20}([0-9][0-9,,.]*(?:\.[0-9]+)?)", text or "")
|
||
if not m:
|
||
return None
|
||
raw = m.group(1).replace(",", "").replace(",", "")
|
||
try:
|
||
return float(raw), m.group(0)[:80]
|
||
except Exception:
|
||
return None
|
||
|
||
|
||
DATE_RE = r"(\d{4})[年\-/.]\s*(\d{1,2})[月\-/.]\s*(\d{1,2})"
|
||
|
||
|
||
def _extract_date(text, label_pattern):
|
||
m = re.search(r"(?:" + label_pattern + r")[^\n]{0,12}?" + DATE_RE, text or "")
|
||
if not m:
|
||
return None, ""
|
||
try:
|
||
return (int(m.group(1)), int(m.group(2)), int(m.group(3))), m.group(0)[:80]
|
||
except Exception:
|
||
return None, ""
|
||
|
||
|
||
def _eval_rule(rule, doc):
|
||
"""逐文档规则:返回命中的疑点描述或 None"""
|
||
params = rule.get("params") or {}
|
||
text = _text_of(doc)
|
||
rtype = rule.get("rule_type")
|
||
if not text or rtype in PROJECT_RULE_TYPES:
|
||
return None
|
||
allowed_types = params.get("doc_types") or []
|
||
if allowed_types and doc.get("doc_type") not in allowed_types:
|
||
return None
|
||
title_keys = params.get("doc_title_keywords") or []
|
||
if title_keys and not any(k in (doc.get("title") or "") for k in title_keys):
|
||
return None
|
||
if rtype == "keyword_exists":
|
||
keywords = params.get("keywords", [])
|
||
min_count = int(params.get("min_count", 1))
|
||
missing = [k for k in keywords if text.count(k) < min_count]
|
||
if missing and len(missing) == len(keywords):
|
||
return f"未检测到必有关键词:{'、'.join(keywords)}"
|
||
return None
|
||
if rtype == "keyword_forbidden":
|
||
keywords = params.get("keywords", [])
|
||
found = [k for k in keywords if k in text]
|
||
if found:
|
||
idx = min(text.find(k) for k in found)
|
||
snippet = text[max(0, idx - 30): idx + 80]
|
||
return f"出现禁止表述:{'、'.join(found)}|片段:{snippet}"
|
||
return None
|
||
if rtype == "regex_match":
|
||
pattern = params.get("pattern", "")
|
||
if pattern and not re.search(pattern, text):
|
||
return f"不符合格式要求(正则:{pattern})"
|
||
return None
|
||
if rtype == "numeric_range":
|
||
low = params.get("min")
|
||
high = params.get("max")
|
||
for label in params.get("keywords", []):
|
||
found = _extract_number(text, label)
|
||
if not found:
|
||
continue
|
||
value, snippet = found
|
||
if low is not None and value < float(low):
|
||
return f"「{label}」数值 {value:g} 低于下限 {low}|片段:{snippet}"
|
||
if high is not None and value > float(high):
|
||
return f"「{label}」数值 {value:g} 高于上限 {high}|片段:{snippet}"
|
||
return None
|
||
if rtype == "calc_check":
|
||
total_label = params.get("total_label", "合计金额|总额")
|
||
tolerance = float(params.get("tolerance", 0.01))
|
||
total = _extract_number(text, total_label)
|
||
if not total:
|
||
return None
|
||
total_value, snippet = total
|
||
part_numbers = []
|
||
for m in re.finditer(r"(?:金额|价款|费用)[^0-9\-]{0,8}([0-9][0-9,,.]*(?:\.[0-9]+)?)", text):
|
||
try:
|
||
part_numbers.append(float(m.group(1).replace(",", "").replace(",", "")))
|
||
except Exception:
|
||
pass
|
||
parts = [x for x in part_numbers if abs(x - total_value) > 1e-6]
|
||
if len(parts) < 2:
|
||
return None
|
||
diff = abs(sum(parts) - total_value)
|
||
if total_value and diff / total_value > tolerance:
|
||
return f"分项金额合计 {sum(parts):,.2f} 与合计 {total_value:,.2f} 不一致(偏差 {diff / total_value:.1%})|片段:{snippet}"
|
||
return None
|
||
return None
|
||
|
||
|
||
def _hits_for_project_rules(rules, docs):
|
||
"""项目级规则:相似度、跨文档勾稽、时间逻辑。返回 hits 列表。"""
|
||
import difflib
|
||
hits = []
|
||
texts = [(d, _text_of(d)) for d in docs if _text_of(d)]
|
||
for rule in rules:
|
||
params = rule.get("params") or {}
|
||
rtype = rule.get("rule_type")
|
||
base = (rule["id"], rule["name"], rule["risk_level"], rule.get("hit_type") or rtype)
|
||
if rtype == "similarity":
|
||
threshold = float(params.get("threshold", 0.85))
|
||
pair = texts[:]
|
||
for i in range(len(pair)):
|
||
for j in range(i + 1, len(pair)):
|
||
d1, t1 = pair[i]
|
||
d2, t2 = pair[j]
|
||
ratio = difflib.SequenceMatcher(None, t1[:3000], t2[:3000]).ratio()
|
||
if ratio >= threshold:
|
||
desc = f"《{d1['title']}》与《{d2['title']}》相似度 {ratio:.1%},超过阈值 {threshold:.0%}"
|
||
hits.append({"rule_id": rule["id"], "rule_name": rule["name"],
|
||
"risk_level": rule["risk_level"], "doc_id": d1["id"],
|
||
"doc_title": d1["title"], "hit_type": "similarity",
|
||
"description": desc})
|
||
elif rtype == "cross_doc":
|
||
a_docs = [d for d in docs if _match_title(d, params.get("a_title", []))]
|
||
b_docs = [d for d in docs if _match_title(d, params.get("b_title", []))]
|
||
tolerance = float(params.get("tolerance", 0.0))
|
||
for a in a_docs:
|
||
fa = _extract_number(_text_of(a), params.get("a_label", "合同金额|合同总价|总金额"))
|
||
if not fa:
|
||
continue
|
||
a_value = fa[0]
|
||
for b in b_docs:
|
||
if b["id"] == a["id"]:
|
||
continue
|
||
fb = _extract_number(_text_of(b), params.get("b_label", "验收金额|结算金额|合计金额"))
|
||
if not fb:
|
||
continue
|
||
b_value = fb[0]
|
||
base_value = max(abs(a_value), 1e-9)
|
||
diff_ratio = abs(a_value - b_value) / base_value
|
||
if diff_ratio > tolerance:
|
||
desc = (f"《{a['title']}》与《{b['title']}》金额不一致:"
|
||
f"{a_value:,.2f} vs {b_value:,.2f},偏差 {diff_ratio:.1%},超过容忍度 {tolerance:.0%}")
|
||
hits.append({"rule_id": rule["id"], "rule_name": rule["name"],
|
||
"risk_level": rule["risk_level"], "doc_id": a["id"],
|
||
"doc_title": a["title"], "hit_type": "cross_doc",
|
||
"description": desc})
|
||
elif rtype == "time_logic":
|
||
a_docs = [d for d in docs if _match_title(d, params.get("a_title", []))]
|
||
b_docs = [d for d in docs if _match_title(d, params.get("b_title", []))]
|
||
order = params.get("order", "A<=B")
|
||
for a in a_docs:
|
||
da, _ = _extract_date(_text_of(a), params.get("a_date", "签订日期|签署日期"))
|
||
if not da:
|
||
continue
|
||
for b in b_docs:
|
||
if a["id"] == b["id"]:
|
||
continue
|
||
db, _ = _extract_date(_text_of(b), params.get("b_date", "验收日期|到货日期"))
|
||
if not db:
|
||
continue
|
||
bad = (da > db) if order == "A<=B" else (da < db)
|
||
if bad:
|
||
desc = (f"《{a['title']}》({da[0]}-{da[1]:02d}-{da[2]:02d}) 与 "
|
||
f"《{b['title']}》({db[0]}-{db[1]:02d}-{db[2]:02d}) 时间顺序不符合 {order}")
|
||
hits.append({"rule_id": rule["id"], "rule_name": rule["name"],
|
||
"risk_level": rule["risk_level"], "doc_id": a["id"],
|
||
"doc_title": a["title"], "hit_type": "time_logic",
|
||
"description": desc})
|
||
return hits
|
||
|
||
|
||
def _load_rules(conn, rule_ids):
|
||
rules = []
|
||
for rid in rule_ids:
|
||
r = conn.execute("SELECT * FROM da_rules WHERE id=?", (rid,)).fetchone()
|
||
if r:
|
||
d = dict(r)
|
||
d["params"] = _json(d.get("params"), {})
|
||
rules.append(d)
|
||
return rules
|
||
|
||
|
||
def simulate_rules(rule_ids, project_id=None):
|
||
"""规则模拟运行:不写任务和疑点,仅返回预览结果。"""
|
||
conn = _conn()
|
||
try:
|
||
rules = _load_rules(conn, rule_ids)
|
||
docs = _load_docs(project_id)
|
||
hits = []
|
||
per_doc_rules = [r for r in rules if r["rule_type"] not in PROJECT_RULE_TYPES]
|
||
for doc in docs:
|
||
for rule in per_doc_rules:
|
||
desc = _eval_rule(rule, doc)
|
||
if desc:
|
||
hits.append({"rule_id": rule["id"], "rule_name": rule["name"],
|
||
"risk_level": rule["risk_level"], "doc_id": doc["id"],
|
||
"doc_title": doc["title"], "hit_type": rule["rule_type"],
|
||
"description": desc})
|
||
project_rules = [r for r in rules if r["rule_type"] in PROJECT_RULE_TYPES]
|
||
hits.extend(_hits_for_project_rules(project_rules, docs))
|
||
conn.close()
|
||
return {"rule_count": len(rules), "doc_count": len(docs), "hit_count": len(hits), "hits": hits}
|
||
finally:
|
||
try:
|
||
conn.close()
|
||
except Exception:
|
||
pass
|
||
|
||
|
||
def run_task(tid):
|
||
conn = _conn()
|
||
try:
|
||
task = conn.execute("SELECT * FROM da_tasks WHERE id=?", (tid,)).fetchone()
|
||
if not task:
|
||
return None
|
||
conn.execute("UPDATE da_tasks SET status='执行中', started_at=? WHERE id=?", (_now(), tid))
|
||
conn.commit()
|
||
rules = _load_rules(conn, _json(task["rule_ids"], []))
|
||
docs = _load_docs(task["project_id"])
|
||
hits = []
|
||
per_doc_rules = [r for r in rules if r["rule_type"] not in PROJECT_RULE_TYPES]
|
||
for doc in docs:
|
||
for rule in per_doc_rules:
|
||
desc = _eval_rule(rule, doc)
|
||
if desc:
|
||
hits.append((rule["id"], rule["name"], rule["risk_level"], doc["id"], doc["title"],
|
||
rule["rule_type"], desc[:500], desc))
|
||
project_hits = _hits_for_project_rules([r for r in rules if r["rule_type"] in PROJECT_RULE_TYPES], docs)
|
||
for h in project_hits:
|
||
hits.append((h["rule_id"], h["rule_name"], h["risk_level"], h["doc_id"], h["doc_title"],
|
||
h["hit_type"], h["description"][:500], h["description"]))
|
||
for h in hits:
|
||
conn.execute("""INSERT INTO da_task_hits(task_id,rule_id,rule_name,risk_level,doc_id,doc_title,
|
||
hit_type,snippet,description,created_at) VALUES (?,?,?,?,?,?,?,?,?,?)""",
|
||
(tid, h[0], h[1], h[2], h[3], h[4], h[5], h[6], h[7], _now()))
|
||
now = _now()
|
||
schedule_type = task["schedule_type"] if "schedule_type" in task.keys() else "立即"
|
||
next_run = ""
|
||
status = "已完成"
|
||
if schedule_type in ("每日", "每周"):
|
||
next_run = _fmt_dt(_calc_next_run(schedule_type, task["scheduled_at"]))
|
||
status = "已排期"
|
||
conn.execute("""UPDATE da_tasks SET status=?, progress=100, doc_total=?, hit_total=?,
|
||
finished_at=?, last_run=?, next_run=?, fail_reason='',
|
||
run_count=COALESCE(run_count,0)+1 WHERE id=?""",
|
||
(status, len(docs), len(hits), now, now, next_run, tid))
|
||
log(conn, "任务执行", f"任务 {task['name']}:扫描 {len(docs)} 份文档,命中 {len(hits)} 条疑点")
|
||
conn.commit()
|
||
return {"task_id": tid, "docs": len(docs), "hits": len(hits), "status": status}
|
||
except Exception as e:
|
||
try:
|
||
conn.execute("""UPDATE da_tasks SET status='执行失败', fail_reason=?, finished_at=?,
|
||
last_run=?, run_count=COALESCE(run_count,0)+1 WHERE id=?""",
|
||
(str(e), _now(), _now(), tid))
|
||
conn.commit()
|
||
log(conn, "任务执行失败", f"任务ID {tid}:{e}")
|
||
except Exception:
|
||
pass
|
||
return {"task_id": tid, "error": str(e)}
|
||
finally:
|
||
conn.close()
|
||
|
||
|
||
def submit_rule(rid):
|
||
conn = _conn()
|
||
try:
|
||
conn.execute("UPDATE da_rules SET publish_status='待审批', submitted_at=? WHERE id=?", (_now(), rid))
|
||
log(conn, "规则提交审批", f"规则ID {rid}")
|
||
conn.commit()
|
||
return True
|
||
finally:
|
||
conn.close()
|
||
|
||
|
||
def review_rule(rid, approve, comment=""):
|
||
conn = _conn()
|
||
try:
|
||
status = "已发布" if approve else "草稿"
|
||
conn.execute("""UPDATE da_rules SET publish_status=?, review_comment=?, approved_at=?
|
||
WHERE id=?""", (status, comment, _now() if approve else "", rid))
|
||
log(conn, "规则审批", f"规则ID {rid} → {status}")
|
||
conn.commit()
|
||
return status
|
||
finally:
|
||
conn.close()
|
||
|
||
|
||
def export_task_hits_xlsx(tid):
|
||
from openpyxl import Workbook
|
||
from io import BytesIO
|
||
conn = _conn()
|
||
try:
|
||
task = conn.execute("SELECT * FROM da_tasks WHERE id=?", (tid,)).fetchone()
|
||
rows = conn.execute("SELECT * FROM da_task_hits WHERE task_id=? ORDER BY risk_level, id", (tid,)).fetchall()
|
||
conn.close()
|
||
wb = Workbook()
|
||
ws = wb.active
|
||
ws.title = "审计疑点"
|
||
ws.append(["任务", "规则", "风险等级", "资料", "类型", "疑点描述", "时间"])
|
||
for r in rows:
|
||
ws.append([task["name"] if task else "", r["rule_name"], r["risk_level"],
|
||
r["doc_title"], r["hit_type"], r["description"], r["created_at"]])
|
||
buf = BytesIO()
|
||
wb.save(buf)
|
||
return buf.getvalue()
|
||
finally:
|
||
try:
|
||
conn.close()
|
||
except Exception:
|
||
pass
|
||
|
||
|
||
def task_hits(tid):
|
||
conn = _conn()
|
||
try:
|
||
return [dict(r) for r in conn.execute(
|
||
"SELECT * FROM da_task_hits WHERE task_id=? ORDER BY risk_level, id", (tid,)).fetchall()]
|
||
finally:
|
||
conn.close()
|
||
|
||
|
||
def delete_task(tid):
|
||
conn = _conn()
|
||
try:
|
||
conn.execute("DELETE FROM da_tasks WHERE id=?", (tid,))
|
||
conn.execute("DELETE FROM da_task_hits WHERE task_id=?", (tid,))
|
||
conn.commit()
|
||
finally:
|
||
conn.close()
|
||
|
||
|
||
# ==================== 驾驶舱(真实数据) ====================
|
||
def overview():
|
||
result = {"kpi": {}, "project_status": [], "risk_level": [], "contract_risk": [],
|
||
"rect_status": [], "doc_trend": [], "updated": _now()}
|
||
try:
|
||
a = _ro(AUDIT_DB)
|
||
result["kpi"]["projects"] = a.execute("SELECT COUNT(*) FROM projects").fetchone()[0]
|
||
result["kpi"]["active"] = a.execute(
|
||
"SELECT COUNT(*) FROM projects WHERE status IN ('进行中','未开始')").fetchone()[0]
|
||
result["kpi"]["completed"] = a.execute(
|
||
"SELECT COUNT(*) FROM projects WHERE status='已完成'").fetchone()[0]
|
||
result["kpi"]["steps"] = a.execute("SELECT COUNT(*) FROM steps").fetchone()[0]
|
||
result["kpi"]["docs"] = a.execute("SELECT COUNT(*) FROM audit_docs").fetchone()[0]
|
||
result["kpi"]["analyses"] = a.execute("SELECT COUNT(*) FROM analysis_results").fetchone()[0]
|
||
result["project_status"] = [{"name": r["status"] or "未设置", "value": r["c"]}
|
||
for r in a.execute(
|
||
"SELECT status, COUNT(*) c FROM projects GROUP BY status ORDER BY c DESC")]
|
||
result["doc_trend"] = [{"month": r["m"], "value": r["c"]} for r in a.execute(
|
||
"SELECT substr(created_at,1,7) m, COUNT(*) c FROM audit_docs "
|
||
"WHERE created_at IS NOT NULL GROUP BY m ORDER BY m DESC LIMIT 6").fetchall()][::-1]
|
||
a.close()
|
||
except Exception as e:
|
||
result["error_audit"] = str(e)
|
||
|
||
try:
|
||
r = _ro(RISK_DB)
|
||
result["kpi"]["risk_items"] = r.execute("SELECT COUNT(*) FROM risk_items").fetchone()[0]
|
||
result["risk_level"] = [{"name": x["risk_level"] or "未评估", "value": x["c"]} for x in r.execute(
|
||
"SELECT risk_level, COUNT(*) c FROM risk_items GROUP BY risk_level ORDER BY c DESC")]
|
||
result["kpi"]["inspection"] = r.execute("SELECT COUNT(*) FROM inspection_risk_data").fetchone()[0]
|
||
result["kpi"]["high_risk"] = r.execute(
|
||
"SELECT COUNT(*) FROM inspection_risk_data WHERE final_risk_level IN ('高','极高','高风险')").fetchone()[0]
|
||
r.close()
|
||
except Exception as e:
|
||
result["error_risk"] = str(e)
|
||
|
||
try:
|
||
c = _ro(CONTRACT_DB)
|
||
result["kpi"]["contracts"] = c.execute("SELECT COUNT(*) FROM contracts").fetchone()[0]
|
||
result["kpi"]["contracts_reviewed"] = c.execute(
|
||
"SELECT COUNT(*) FROM contracts WHERE status='reviewed'").fetchone()[0]
|
||
result["contract_risk"] = [{"name": x["risk_level"] or "未审核", "value": x["c"]} for x in c.execute(
|
||
"SELECT risk_level, COUNT(*) c FROM contracts GROUP BY risk_level ORDER BY c DESC")]
|
||
result["kpi"]["contracts_high"] = c.execute(
|
||
"SELECT COUNT(*) FROM contracts WHERE risk_level IN ('高','极高')").fetchone()[0]
|
||
c.close()
|
||
except Exception as e:
|
||
result["error_contract"] = str(e)
|
||
|
||
conn = _conn()
|
||
try:
|
||
result["kpi"]["rect_total"] = conn.execute("SELECT COUNT(*) FROM da_rectifications").fetchone()[0]
|
||
result["kpi"]["rect_done"] = conn.execute(
|
||
"SELECT COUNT(*) FROM da_rectifications WHERE status='已验收'").fetchone()[0]
|
||
result["kpi"]["rect_over"] = conn.execute(
|
||
"SELECT COUNT(*) FROM da_rectifications WHERE status='已超期' OR "
|
||
"(status NOT IN ('已验收') AND deadline IS NOT NULL AND deadline != '' AND deadline < ?)",
|
||
(_today(),)).fetchone()[0]
|
||
result["kpi"]["model_runs"] = conn.execute("SELECT COUNT(*) FROM da_model_runs").fetchone()[0]
|
||
result["kpi"]["models"] = conn.execute("SELECT COUNT(*) FROM da_models WHERE status='启用'").fetchone()[0]
|
||
result["kpi"]["rules"] = conn.execute("SELECT COUNT(*) FROM da_rules WHERE status='启用'").fetchone()[0]
|
||
result["kpi"]["tasks"] = conn.execute("SELECT COUNT(*) FROM da_tasks").fetchone()[0]
|
||
result["kpi"]["hits"] = conn.execute("SELECT COUNT(*) FROM da_task_hits").fetchone()[0]
|
||
result["rect_status"] = [{"name": x["status"], "value": x["c"]} for x in conn.execute(
|
||
"SELECT status, COUNT(*) c FROM da_rectifications GROUP BY status")]
|
||
finally:
|
||
conn.close()
|
||
return result
|
||
|
||
|
||
# ==================== 计划(读取真实年度计划) ====================
|
||
def list_plans():
|
||
try:
|
||
a = _ro(AUDIT_DB)
|
||
rows = a.execute("""
|
||
SELECT y.id, y.year, y.name, y.goal, y.budget, y.status,
|
||
c.name category, p.name leader,
|
||
(SELECT COUNT(*) FROM projects pr WHERE pr.year_id = y.id) project_count,
|
||
(SELECT ROUND(AVG(s.progress),0) FROM steps s JOIN projects pr ON s.project_id=pr.id
|
||
WHERE pr.year_id = y.id) avg_progress
|
||
FROM years y
|
||
LEFT JOIN categories c ON y.category_id = c.id
|
||
LEFT JOIN persons p ON y.leader_id = p.id
|
||
ORDER BY y.year DESC, y.id DESC
|
||
""").fetchall()
|
||
a.close()
|
||
return [dict(r) for r in rows]
|
||
except Exception:
|
||
return []
|
||
|
||
|
||
# ==================== 项目(读取真实项目) ====================
|
||
def list_projects():
|
||
try:
|
||
a = _ro(AUDIT_DB)
|
||
rows = a.execute("""
|
||
SELECT p.id, p.name, p.description, p.status, p.priority, p.budget,
|
||
p.start_date, p.end_date, y.year, y.name plan_name,
|
||
c.name category, per.name leader,
|
||
(SELECT COUNT(*) FROM steps s WHERE s.project_id = p.id) step_count,
|
||
(SELECT ROUND(AVG(s.progress),0) FROM steps s WHERE s.project_id = p.id) avg_progress,
|
||
(SELECT COUNT(*) FROM audit_docs d WHERE d.project_id = p.id) doc_count
|
||
FROM projects p
|
||
LEFT JOIN years y ON p.year_id = y.id
|
||
LEFT JOIN categories c ON p.category_id = c.id
|
||
LEFT JOIN persons per ON p.leader_id = per.id
|
||
ORDER BY p.id DESC
|
||
""").fetchall()
|
||
a.close()
|
||
return [dict(r) for r in rows]
|
||
except Exception:
|
||
return []
|
||
|
||
|
||
# ==================== 审计资料(读取真实文档) ====================
|
||
def list_docs():
|
||
try:
|
||
a = _ro(AUDIT_DB)
|
||
rows = a.execute("""
|
||
SELECT d.id, d.title, d.doc_type, d.status, d.created_at,
|
||
p.name project_name,
|
||
(SELECT COUNT(*) FROM attachments at WHERE at.doc_id = d.id) attachment_count,
|
||
(SELECT COUNT(*) FROM analysis_results ar WHERE ar.doc_id = d.id) analysis_count
|
||
FROM audit_docs d
|
||
LEFT JOIN projects p ON d.project_id = p.id
|
||
ORDER BY d.id DESC
|
||
""").fetchall()
|
||
a.close()
|
||
return [dict(r) for r in rows]
|
||
except Exception:
|
||
return []
|
||
|
||
|
||
# ==================== 整改管理(真实台账) ====================
|
||
def list_rectifications():
|
||
conn = _conn()
|
||
try:
|
||
return [dict(r) for r in conn.execute(
|
||
"SELECT * FROM da_rectifications ORDER BY id DESC").fetchall()]
|
||
finally:
|
||
conn.close()
|
||
|
||
|
||
def save_rectification(data):
|
||
conn = _conn()
|
||
try:
|
||
fields = ("project_id", "project_name", "issue", "dept", "level", "status",
|
||
"deadline", "owner", "progress", "source_type", "source_id")
|
||
vals = [data.get(f, "") for f in fields]
|
||
cur = conn.execute("INSERT INTO da_rectifications(" + ",".join(fields) + ",created_at) VALUES (" +
|
||
",".join("?" * len(fields)) + ",?)", vals + [_now()])
|
||
log(conn, "整改新增", data.get("issue", ""))
|
||
conn.commit()
|
||
return cur.lastrowid
|
||
finally:
|
||
conn.close()
|
||
|
||
|
||
def update_rectification(rid, data):
|
||
conn = _conn()
|
||
try:
|
||
allowed = ("issue", "dept", "level", "status", "deadline", "owner", "progress",
|
||
"q1", "q2", "q3", "q4", "q5", "q6", "result")
|
||
fields = [f for f in allowed if f in data]
|
||
if fields:
|
||
conn.execute("UPDATE da_rectifications SET " + ",".join(f"{f}=?" for f in fields) + " WHERE id=?",
|
||
[data[f] for f in fields] + [rid])
|
||
log(conn, "整改更新", f"整改ID {rid} 状态 {data.get('status','')}")
|
||
conn.commit()
|
||
return dict(conn.execute("SELECT * FROM da_rectifications WHERE id=?", (rid,)).fetchone())
|
||
finally:
|
||
conn.close()
|
||
|
||
|
||
def delete_rectification(rid):
|
||
conn = _conn()
|
||
try:
|
||
conn.execute("DELETE FROM da_rectifications WHERE id=?", (rid,))
|
||
log(conn, "整改删除", f"整改ID {rid}")
|
||
conn.commit()
|
||
finally:
|
||
conn.close()
|
||
|
||
|
||
def import_findings():
|
||
"""从既有审计分析结果、检查风险数据中导入高风险问题,生成整改台账(去重)。"""
|
||
conn = _conn()
|
||
created = 0
|
||
try:
|
||
# 1) 审计资料分析结果(高风险/极高)
|
||
try:
|
||
a = _ro(AUDIT_DB)
|
||
rows = a.execute("""
|
||
SELECT ar.id, ar.summary, ar.risk_level, ar.findings,
|
||
d.project_id, p.name project_name
|
||
FROM analysis_results ar
|
||
LEFT JOIN audit_docs d ON ar.doc_id = d.id
|
||
LEFT JOIN projects p ON d.project_id = p.id
|
||
WHERE ar.risk_level IN ('高','极高','高风险')
|
||
""").fetchall()
|
||
a.close()
|
||
for r in rows:
|
||
exists = conn.execute(
|
||
"SELECT 1 FROM da_rectifications WHERE source_type='analysis' AND source_id=?",
|
||
(r["id"],)).fetchone()
|
||
if exists:
|
||
continue
|
||
issue = (r["summary"] or "").strip()
|
||
if not issue:
|
||
findings = _json(r["findings"], [])
|
||
if isinstance(findings, list) and findings:
|
||
f0 = findings[0]
|
||
issue = f0.get("title") or f0.get("description") or str(f0) if isinstance(f0, dict) else str(f0)
|
||
if not issue:
|
||
continue
|
||
level = "高" if r["risk_level"] in ("高", "极高", "高风险") else "中"
|
||
conn.execute("""INSERT INTO da_rectifications(project_id,project_name,issue,dept,level,status,
|
||
deadline,owner,progress,source_type,source_id,created_at)
|
||
VALUES (?,?,?,?,?,?,?,?,?,?,?,?)""",
|
||
(r["project_id"], r["project_name"], issue[:500], "待明确", level, "待整改",
|
||
(datetime.date.today() + datetime.timedelta(days=30)).strftime("%Y-%m-%d"),
|
||
"", 0, "analysis", r["id"], _now()))
|
||
created += 1
|
||
except Exception:
|
||
pass
|
||
# 2) 检查风险数据(高/极高)
|
||
try:
|
||
r = _ro(RISK_DB)
|
||
rows = r.execute("""SELECT id, risk_desc, department, final_risk_level
|
||
FROM inspection_risk_data
|
||
WHERE final_risk_level IN ('高','极高','高风险')""").fetchall()
|
||
r.close()
|
||
for x in rows:
|
||
exists = conn.execute(
|
||
"SELECT 1 FROM da_rectifications WHERE source_type='inspection' AND source_id=?",
|
||
(x["id"],)).fetchone()
|
||
if exists:
|
||
continue
|
||
conn.execute("""INSERT INTO da_rectifications(project_id,project_name,issue,dept,level,status,
|
||
deadline,owner,progress,source_type,source_id,created_at)
|
||
VALUES (?,?,?,?,?,?,?,?,?,?,?,?)""",
|
||
(None, "检查风险数据", (x["risk_desc"] or "")[:500], x["department"] or "待明确",
|
||
"高", "待整改",
|
||
(datetime.date.today() + datetime.timedelta(days=30)).strftime("%Y-%m-%d"),
|
||
"", 0, "inspection", x["id"], _now()))
|
||
created += 1
|
||
except Exception:
|
||
pass
|
||
log(conn, "整改导入", f"从审计发现导入 {created} 项")
|
||
conn.commit()
|
||
return created
|
||
finally:
|
||
conn.close()
|
||
|
||
|
||
# ==================== 文档解析中心(Word / PDF / Excel / 图片 OCR) ====================
|
||
PARSE_MAX_CHARS = 300000
|
||
|
||
|
||
def _decode_text(raw):
|
||
for enc in ("utf-8-sig", "utf-8", "gbk", "gb18030"):
|
||
try:
|
||
return raw.decode(enc)
|
||
except Exception:
|
||
continue
|
||
return raw.decode("utf-8", errors="ignore")
|
||
|
||
|
||
def _extract_docx(raw):
|
||
from docx import Document
|
||
doc = Document(io.BytesIO(raw))
|
||
parts = []
|
||
for p in doc.paragraphs:
|
||
if p.text.strip():
|
||
parts.append(p.text.strip())
|
||
for ti, table in enumerate(doc.tables):
|
||
parts.append(f"\n[表格 {ti + 1}]")
|
||
for row in table.rows:
|
||
cells = [c.text.replace("\n", " ").strip() for c in row.cells]
|
||
parts.append(" | ".join(cells))
|
||
return "\n".join(parts), 1, "文本提取"
|
||
|
||
|
||
def _extract_xlsx(raw):
|
||
from openpyxl import load_workbook
|
||
wb = load_workbook(io.BytesIO(raw), read_only=True, data_only=True)
|
||
ws = wb.active
|
||
parts = []
|
||
for i, row in enumerate(ws.iter_rows(values_only=True)):
|
||
if i >= 3000:
|
||
break
|
||
parts.append(" | ".join("" if v is None else str(v) for v in row))
|
||
wb.close()
|
||
return "\n".join(parts), 1, "表格提取"
|
||
|
||
|
||
OCR_ENGINE_CONFIG = {
|
||
"general": "",
|
||
"table": "--psm 6",
|
||
"handwritten": "--psm 7",
|
||
}
|
||
|
||
|
||
def _ocr_image(image, engine="general"):
|
||
import pytesseract
|
||
config = OCR_ENGINE_CONFIG.get(engine, "")
|
||
return pytesseract.image_to_string(image, lang="chi_sim+eng", config=config)
|
||
|
||
|
||
def _extract_pdf(raw, engine="general"):
|
||
import pdf_tools
|
||
pages = pdf_tools.page_count(raw)
|
||
text = pdf_tools.extract_text(raw)
|
||
mode = "文本提取"
|
||
if len(text.strip()) >= 30:
|
||
return text, pages, mode
|
||
# 扫描件:渲染页面后 OCR(最多 20 页,避免过慢);PIL/pytesseract 仅在需要时导入
|
||
try:
|
||
from PIL import Image
|
||
parts = []
|
||
for png in pdf_tools.render_pages_png(raw, scale=2.0, max_pages=20):
|
||
img = Image.open(io.BytesIO(png))
|
||
parts.append(_ocr_image(img, engine))
|
||
ocr_text = "\n".join(parts)
|
||
if ocr_text.strip():
|
||
return ocr_text, pages, f"OCR识别({min(pages, 20)}/{pages} 页)"
|
||
return "", pages, "OCR识别"
|
||
except Exception as e:
|
||
raise RuntimeError(f"扫描件需要 OCR,但 OCR 组件不可用:{e}") from e
|
||
|
||
|
||
def _extract_image(raw, engine="general"):
|
||
from PIL import Image
|
||
img = Image.open(io.BytesIO(raw))
|
||
text = _ocr_image(img)
|
||
return text, 1, "图片 OCR"
|
||
|
||
|
||
def _extract_legacy_office(raw):
|
||
raise RuntimeError("暂不支持 .doc/.xls 旧格式,请先另存为 .docx/.xlsx 后上传")
|
||
|
||
|
||
def parse_document(filename, raw, engine="general"):
|
||
"""解析文档并返回统一结构(不写库)。
|
||
|
||
engine:general 通用印刷体;table 表格结构;handwritten 手写体(实验)。
|
||
"""
|
||
name = (filename or "upload").lower()
|
||
if name.endswith(".docx"):
|
||
text, pages, mode = _extract_docx(raw)
|
||
elif name.endswith(".doc") or name.endswith(".xls") or name.endswith(".ppt"):
|
||
text, pages, mode = _extract_legacy_office(raw)
|
||
elif name.endswith(".xlsx"):
|
||
text, pages, mode = _extract_xlsx(raw)
|
||
elif name.endswith(".pdf"):
|
||
text, pages, mode = _extract_pdf(raw, engine)
|
||
elif name.endswith((".png", ".jpg", ".jpeg", ".bmp", ".webp")):
|
||
text, pages, mode = _extract_image(raw, engine)
|
||
elif name.endswith((".txt", ".csv", ".md")):
|
||
text, pages, mode = _decode_text(raw), 1, "文本读取"
|
||
else:
|
||
raise ValueError("不支持的文件类型,仅支持 Word / PDF / Excel / 图片 / 文本")
|
||
text = (text or "").strip()
|
||
if len(text) > PARSE_MAX_CHARS:
|
||
text = text[:PARSE_MAX_CHARS] + "\n…(内容过长,已截断)"
|
||
if not text:
|
||
raise ValueError("未提取到文字内容(可能是空文件或加密文件)")
|
||
return {
|
||
"mode": mode,
|
||
"pages": pages,
|
||
"char_count": len(text),
|
||
"preview": text[:300].replace("\n", " "),
|
||
"content": text,
|
||
"status": "解析成功",
|
||
}
|
||
|
||
|
||
def save_parsed(filename, result):
|
||
conn = _conn()
|
||
try:
|
||
cur = conn.execute("""INSERT INTO da_parsed_docs(filename,file_type,mode,status,pages,char_count,
|
||
preview,content,error,created_at) VALUES (?,?,?,?,?,?,?,?,?,?)""",
|
||
(filename, Path(filename or "").suffix.lower(), result.get("mode", ""),
|
||
result.get("status", "解析成功"), result.get("pages", 0),
|
||
result.get("char_count", 0), result.get("preview", ""),
|
||
result.get("content", ""), result.get("error", ""), _now()))
|
||
log(conn, "文档解析", f"{filename}:{result.get('mode','')},{result.get('char_count',0)} 字")
|
||
conn.commit()
|
||
return cur.lastrowid
|
||
finally:
|
||
conn.close()
|
||
|
||
|
||
def list_parsed():
|
||
conn = _conn()
|
||
try:
|
||
rows = [dict(r) for r in conn.execute(
|
||
"SELECT id,filename,file_type,mode,status,pages,char_count,preview,created_at "
|
||
"FROM da_parsed_docs ORDER BY id DESC").fetchall()]
|
||
return rows
|
||
finally:
|
||
conn.close()
|
||
|
||
|
||
def get_parsed(pid):
|
||
conn = _conn()
|
||
try:
|
||
row = conn.execute("SELECT * FROM da_parsed_docs WHERE id=?", (pid,)).fetchone()
|
||
return dict(row) if row else None
|
||
finally:
|
||
conn.close()
|
||
|
||
|
||
def delete_parsed(pid):
|
||
conn = _conn()
|
||
try:
|
||
conn.execute("DELETE FROM da_parsed_docs WHERE id=?", (pid,))
|
||
log(conn, "删除解析文档", f"ID {pid}")
|
||
conn.commit()
|
||
finally:
|
||
conn.close()
|
||
|
||
|
||
# ==================== 数据资源 ====================
|
||
def list_datasources():
|
||
assets = []
|
||
for name, path, typ in [
|
||
("审计业务数据库", AUDIT_DB, "数据库"),
|
||
("风险业务数据库", RISK_DB, "数据库"),
|
||
("合同审核数据库", CONTRACT_DB, "数据库"),
|
||
]:
|
||
st = _db_stat(path)
|
||
assets.append({
|
||
"id": None, "name": name, "type": typ, "endpoint": str(path.name),
|
||
"auth_type": "本地文件", "schedule": "实时", "status": "正常" if path.exists() else "异常",
|
||
"last_error": "" if path.exists() else "数据库文件不存在",
|
||
"last_test": _now(), "builtin": True,
|
||
"tables": st["tables"], "rows": st["rows"], "size": st["size"],
|
||
})
|
||
for name, path in [("审计上传附件", AUDIT_UPLOADS), ("合同原文", CONTRACT_FILES), ("审核报告", REPORT_FILES)]:
|
||
st = _dir_stat(path)
|
||
assets.append({
|
||
"id": None, "name": name, "type": "文件", "endpoint": path.name,
|
||
"auth_type": "本地目录", "schedule": "实时", "status": "正常" if path.exists() else "异常",
|
||
"last_error": "", "last_test": _now(), "builtin": True,
|
||
"tables": 0, "rows": st["count"], "size": st["size"],
|
||
})
|
||
conn = _conn()
|
||
try:
|
||
for r in conn.execute("SELECT * FROM da_external_sources ORDER BY id DESC").fetchall():
|
||
d = dict(r)
|
||
d["builtin"] = False
|
||
assets.append(d)
|
||
finally:
|
||
conn.close()
|
||
return assets
|
||
|
||
|
||
def save_datasource(data):
|
||
conn = _conn()
|
||
try:
|
||
fields = ("name", "type", "endpoint", "auth_type", "schedule", "status", "last_error")
|
||
vals = [data.get(f, "") for f in fields]
|
||
if data.get("id"):
|
||
conn.execute("UPDATE da_external_sources SET " + ",".join(f"{f}=?" for f in fields) + " WHERE id=?",
|
||
vals + [data["id"]])
|
||
sid = data["id"]
|
||
else:
|
||
cur = conn.execute("INSERT INTO da_external_sources(" + ",".join(fields) +
|
||
",created_at) VALUES (" + ",".join("?" * len(fields)) + ",?)", vals + [_now()])
|
||
sid = cur.lastrowid
|
||
log(conn, "数据源保存", data.get("name", ""))
|
||
conn.commit()
|
||
return sid
|
||
finally:
|
||
conn.close()
|
||
|
||
|
||
def _sqlite_endpoint(endpoint):
|
||
"""解析 sqlite 数据源地址,支持 sqlite:路径#表名 或直接路径#表名。"""
|
||
s = (endpoint or "").strip()
|
||
table = ""
|
||
if "#" in s:
|
||
s, table = s.rsplit("#", 1)
|
||
for prefix in ("sqlite:///", "sqlite://", "sqlite:"):
|
||
if s.startswith(prefix):
|
||
s = s[len(prefix):]
|
||
break
|
||
return s.strip(), table.strip()
|
||
|
||
|
||
def _parse_records(payload):
|
||
if isinstance(payload, list):
|
||
return payload
|
||
if isinstance(payload, dict):
|
||
for key in ("data", "items", "list", "records", "rows", "result"):
|
||
value = payload.get(key)
|
||
if isinstance(value, list):
|
||
return value
|
||
return [payload]
|
||
return []
|
||
|
||
|
||
def _http_get(endpoint, timeout=25):
|
||
import urllib.request
|
||
req = urllib.request.Request(endpoint, headers={"User-Agent": "audit-data-access/1.0"})
|
||
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
||
raw = resp.read(2 * 1024 * 1024)
|
||
content_type = resp.headers.get("Content-Type", "")
|
||
return raw, content_type
|
||
|
||
|
||
def test_datasource(sid):
|
||
conn = _conn()
|
||
try:
|
||
row = conn.execute("SELECT * FROM da_external_sources WHERE id=?", (sid,)).fetchone()
|
||
if not row:
|
||
return None
|
||
endpoint = row["endpoint"] or ""
|
||
status, error = "正常", ""
|
||
try:
|
||
if endpoint.startswith("http://") or endpoint.startswith("https://"):
|
||
_http_get(endpoint, timeout=8)
|
||
else:
|
||
path, table = _sqlite_endpoint(endpoint)
|
||
if not Path(path).exists():
|
||
raise FileNotFoundError(f"数据库文件不存在:{path}")
|
||
ro = _ro(path)
|
||
tables = [r[0] for r in ro.execute(
|
||
"SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'")]
|
||
ro.close()
|
||
if table and table not in tables:
|
||
raise ValueError(f"表 {table} 不存在,可用表:{', '.join(tables[:8])}")
|
||
if not tables:
|
||
raise ValueError("数据库中没有业务表")
|
||
except Exception as e:
|
||
status, error = "异常", f"连接失败:{e}"
|
||
conn.execute("UPDATE da_external_sources SET status=?, last_error=?, last_test=? WHERE id=?",
|
||
(status, error, _now(), sid))
|
||
conn.commit()
|
||
return {"status": status, "error": error, "last_test": _now()}
|
||
finally:
|
||
conn.close()
|
||
|
||
|
||
def delete_datasource(sid):
|
||
conn = _conn()
|
||
try:
|
||
conn.execute("DELETE FROM da_external_sources WHERE id=?", (sid,))
|
||
log(conn, "数据源删除", f"ID {sid}")
|
||
conn.commit()
|
||
finally:
|
||
conn.close()
|
||
|
||
|
||
def pull_datasource(sid, limit=5000):
|
||
"""从外部数据源真实抽取数据,写入 da_pulled_data,供后续审计分析使用。"""
|
||
conn = _conn()
|
||
try:
|
||
row = conn.execute("SELECT * FROM da_external_sources WHERE id=?", (sid,)).fetchone()
|
||
if not row:
|
||
return None
|
||
source_name = row["name"] or f"数据源{sid}"
|
||
endpoint = row["endpoint"] or ""
|
||
pull_type = "HTTP接口" if endpoint.startswith(("http://", "https://")) else "SQLite文件"
|
||
records, columns = [], []
|
||
try:
|
||
if endpoint.startswith(("http://", "https://")):
|
||
raw, content_type = _http_get(endpoint)
|
||
text = _decode_text(raw)
|
||
if "json" in content_type.lower() or text.lstrip().startswith(("{", "[")):
|
||
payload = json.loads(text)
|
||
records = _parse_records(payload)
|
||
elif "csv" in content_type.lower() or "," in text[:500]:
|
||
reader = csv.DictReader(io.StringIO(text))
|
||
records = [dict(r) for r in reader]
|
||
else:
|
||
raise ValueError("接口返回内容无法识别(仅支持 JSON / CSV)")
|
||
else:
|
||
path, table = _sqlite_endpoint(endpoint)
|
||
if not Path(path).exists():
|
||
raise FileNotFoundError(f"数据库文件不存在:{path}")
|
||
ro = _ro(path)
|
||
if not table:
|
||
first = ro.execute(
|
||
"SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' ORDER BY name").fetchone()
|
||
if not first:
|
||
raise ValueError("数据库中没有业务表")
|
||
table = first[0]
|
||
cur = ro.execute(f"SELECT * FROM {table} LIMIT {int(limit)}")
|
||
records = [dict(r) for r in cur.fetchall()]
|
||
ro.close()
|
||
records = records[:limit]
|
||
columns = list(records[0].keys()) if records else []
|
||
cur = conn.execute("""INSERT INTO da_pulled_data(source_id,source_name,pull_type,record_count,
|
||
columns,data,status,error,created_at) VALUES (?,?,?,?,?,?,?,?,?)""",
|
||
(sid, source_name, pull_type, len(records),
|
||
json.dumps(columns, ensure_ascii=False),
|
||
json.dumps(records, ensure_ascii=False), "成功", "", _now()))
|
||
conn.execute("UPDATE da_external_sources SET status='正常', last_test=?, last_error='' WHERE id=?",
|
||
(_now(), sid))
|
||
log(conn, "数据抽取", f"{source_name}:{len(records)} 条")
|
||
conn.commit()
|
||
return {"ok": True, "id": cur.lastrowid, "count": len(records),
|
||
"columns": columns, "preview": records[:5]}
|
||
except Exception as e:
|
||
conn.execute("""INSERT INTO da_pulled_data(source_id,source_name,pull_type,record_count,
|
||
columns,data,status,error,created_at) VALUES (?,?,?,?,?,?,?,?,?)""",
|
||
(sid, source_name, pull_type, 0, "[]", "[]", "失败", str(e), _now()))
|
||
conn.execute("UPDATE da_external_sources SET status='异常', last_error=? WHERE id=?",
|
||
(f"抽取失败:{e}", sid))
|
||
log(conn, "数据抽取失败", f"{source_name}:{e}")
|
||
conn.commit()
|
||
return {"ok": False, "error": str(e)}
|
||
finally:
|
||
conn.close()
|
||
|
||
|
||
def list_pulled():
|
||
conn = _conn()
|
||
try:
|
||
return [dict(r) for r in conn.execute(
|
||
"SELECT id,source_id,source_name,pull_type,record_count,columns,status,error,created_at "
|
||
"FROM da_pulled_data ORDER BY id DESC LIMIT 100").fetchall()]
|
||
finally:
|
||
conn.close()
|
||
|
||
|
||
def get_pulled(pid):
|
||
conn = _conn()
|
||
try:
|
||
row = conn.execute("SELECT * FROM da_pulled_data WHERE id=?", (pid,)).fetchone()
|
||
if not row:
|
||
return None
|
||
d = dict(row)
|
||
d["columns"] = _json(d.get("columns"), [])
|
||
d["data"] = _json(d.get("data"), [])
|
||
return d
|
||
finally:
|
||
conn.close()
|
||
|
||
|
||
def delete_pulled(pid):
|
||
conn = _conn()
|
||
try:
|
||
conn.execute("DELETE FROM da_pulled_data WHERE id=?", (pid,))
|
||
conn.commit()
|
||
finally:
|
||
conn.close()
|
||
|
||
|
||
# ==================== 模型(真实查询) ====================
|
||
MODEL_QUERIES = {
|
||
"contract_risk": ("SELECT COALESCE(risk_level,'未审核') AS risk_level, COUNT(*) AS count FROM contracts GROUP BY 1 ORDER BY count DESC", CONTRACT_DB),
|
||
"contract_high": ("SELECT id, name, risk_level, upload_date FROM contracts WHERE risk_level IN ('高','极高') ORDER BY upload_date DESC", CONTRACT_DB),
|
||
"risk_level": ("SELECT COALESCE(risk_level,'未评估') AS risk_level, COUNT(*) AS count FROM risk_items GROUP BY 1 ORDER BY count DESC", RISK_DB),
|
||
"risk_dept": ("SELECT department, COUNT(*) AS count FROM inspection_risk_data WHERE final_risk_level IN ('高','极高','高风险') GROUP BY department ORDER BY count DESC", RISK_DB),
|
||
"audit_progress": ("SELECT p.name, ROUND(AVG(s.progress),0) AS progress FROM projects p LEFT JOIN steps s ON s.project_id=p.id GROUP BY p.id ORDER BY progress DESC", AUDIT_DB),
|
||
"doc_analysis": ("SELECT COALESCE(risk_level,'未分析') AS risk_level, COUNT(*) AS count FROM analysis_results GROUP BY 1 ORDER BY count DESC", AUDIT_DB),
|
||
}
|
||
|
||
|
||
def list_models():
|
||
conn = _conn()
|
||
try:
|
||
return [dict(r) for r in conn.execute("SELECT * FROM da_models ORDER BY id").fetchall()]
|
||
finally:
|
||
conn.close()
|
||
|
||
|
||
def save_model(data):
|
||
conn = _conn()
|
||
try:
|
||
fields = ("name", "category", "risk_level", "rule_type", "description", "query_key", "expression", "status")
|
||
vals = [data.get(f, "") for f in fields]
|
||
if data.get("id"):
|
||
conn.execute("UPDATE da_models SET " + ",".join(f"{f}=?" for f in fields) + " WHERE id=?",
|
||
vals + [data["id"]])
|
||
mid = data["id"]
|
||
else:
|
||
cur = conn.execute("INSERT INTO da_models(" + ",".join(fields) +
|
||
",created_at) VALUES (" + ",".join("?" * len(fields)) + ",?)", vals + [_now()])
|
||
mid = cur.lastrowid
|
||
log(conn, "模型保存", data.get("name", ""))
|
||
conn.commit()
|
||
return mid
|
||
finally:
|
||
conn.close()
|
||
|
||
|
||
def run_model(mid):
|
||
conn = _conn()
|
||
try:
|
||
m = conn.execute("SELECT * FROM da_models WHERE id=?", (mid,)).fetchone()
|
||
if not m:
|
||
return None
|
||
key = m["query_key"]
|
||
if key not in MODEL_QUERIES:
|
||
return {"error": "该模型暂未绑定数据查询,请在模型配置中选择内置模型类型"}
|
||
sql, db = MODEL_QUERIES[key]
|
||
ro = _ro(db)
|
||
rows = [dict(x) for x in ro.execute(sql).fetchall()[:200]]
|
||
ro.close()
|
||
total = 0
|
||
for x in rows:
|
||
for v in x.values():
|
||
if isinstance(v, int):
|
||
total += v
|
||
if key in ("contract_risk", "risk_level", "doc_analysis"):
|
||
summary = f"共统计 {len(rows)} 个分组、{total} 条记录"
|
||
else:
|
||
summary = f"命中 {len(rows)} 条记录"
|
||
conn.execute("INSERT INTO da_model_runs(model_id, summary, matched, detail, created_at) VALUES (?,?,?,?,?)",
|
||
(mid, summary, total, json.dumps(rows, ensure_ascii=False), _now()))
|
||
conn.execute("UPDATE da_models SET run_count=run_count+1 WHERE id=?", (mid,))
|
||
log(conn, "模型运行", f"{m['name']}:{summary}")
|
||
conn.commit()
|
||
return {"model": m["name"], "summary": summary, "matched": total, "rows": rows, "time": _now()}
|
||
finally:
|
||
conn.close()
|
||
|
||
|
||
def model_runs():
|
||
conn = _conn()
|
||
try:
|
||
return [dict(x) for x in conn.execute(
|
||
"SELECT r.*, m.name model_name FROM da_model_runs r "
|
||
"LEFT JOIN da_models m ON r.model_id=m.id ORDER BY r.id DESC LIMIT 50").fetchall()]
|
||
finally:
|
||
conn.close()
|
||
|
||
|
||
def delete_model(mid):
|
||
conn = _conn()
|
||
try:
|
||
conn.execute("DELETE FROM da_models WHERE id=?", (mid,))
|
||
conn.commit()
|
||
finally:
|
||
conn.close()
|
||
|
||
|
||
# ==================== ETL 导入(真实文件解析) ====================
|
||
def import_file(filename, raw):
|
||
"""解析 CSV / Excel,写入临时结果表,返回任务ID与行列数。"""
|
||
rows = []
|
||
lower = filename.lower()
|
||
if lower.endswith(".csv"):
|
||
text = None
|
||
for enc in ("utf-8-sig", "gbk", "utf-8"):
|
||
try:
|
||
text = raw.decode(enc)
|
||
break
|
||
except Exception:
|
||
continue
|
||
if text is None:
|
||
raise ValueError("CSV 编码无法识别,请使用 UTF-8 或 GBK 编码")
|
||
reader = csv.reader(io.StringIO(text))
|
||
for i, row in enumerate(reader):
|
||
if i >= 5000:
|
||
break
|
||
rows.append(row)
|
||
elif lower.endswith(".xlsx") or lower.endswith(".xls"):
|
||
from openpyxl import load_workbook
|
||
wb = load_workbook(io.BytesIO(raw), read_only=True, data_only=True)
|
||
ws = wb.active
|
||
for i, row in enumerate(ws.iter_rows(values_only=True)):
|
||
if i >= 5000:
|
||
break
|
||
rows.append(["" if v is None else str(v) for v in row])
|
||
wb.close()
|
||
else:
|
||
raise ValueError("仅支持 CSV / Excel(.xlsx)文件")
|
||
if not rows:
|
||
raise ValueError("文件内容为空")
|
||
header = rows[0]
|
||
data_rows = rows[1:] if len(rows) > 1 else []
|
||
objects = []
|
||
for r in data_rows:
|
||
obj = {}
|
||
for idx, key in enumerate(header):
|
||
obj[str(key) if key else f"列{idx+1}"] = r[idx] if idx < len(r) else ""
|
||
objects.append(obj)
|
||
conn = _conn()
|
||
try:
|
||
cur = conn.execute("""INSERT INTO da_etl_tasks(name,source_file,target_table,status,row_count,last_run,created_at)
|
||
VALUES (?,?,?,?,?,?,?)""",
|
||
(filename, filename, "da_etl_results", "已导入", len(objects), _now(), _now()))
|
||
tid = cur.lastrowid
|
||
conn.execute("INSERT INTO da_etl_results(task_id,data,created_at) VALUES (?,?,?)",
|
||
(tid, json.dumps(objects, ensure_ascii=False), _now()))
|
||
log(conn, "ETL导入", f"{filename}:{len(objects)} 行")
|
||
conn.commit()
|
||
return {"id": tid, "rows": len(objects), "columns": [str(h) for h in header]}
|
||
finally:
|
||
conn.close()
|
||
|
||
|
||
def list_etl():
|
||
conn = _conn()
|
||
try:
|
||
return [dict(r) for r in conn.execute("SELECT * FROM da_etl_tasks ORDER BY id DESC").fetchall()]
|
||
finally:
|
||
conn.close()
|
||
|
||
|
||
def etl_results(tid):
|
||
conn = _conn()
|
||
try:
|
||
row = conn.execute("SELECT data FROM da_etl_results WHERE task_id=? ORDER BY id DESC LIMIT 1",
|
||
(tid,)).fetchone()
|
||
return _json(row["data"], []) if row else []
|
||
finally:
|
||
conn.close()
|
||
|
||
|
||
def delete_etl(tid):
|
||
conn = _conn()
|
||
try:
|
||
conn.execute("DELETE FROM da_etl_tasks WHERE id=?", (tid,))
|
||
conn.execute("DELETE FROM da_etl_results WHERE task_id=?", (tid,))
|
||
conn.commit()
|
||
finally:
|
||
conn.close()
|
||
|
||
|
||
# ==================== 流程配置 ====================
|
||
def list_workflows():
|
||
conn = _conn()
|
||
try:
|
||
rows = []
|
||
for r in conn.execute("SELECT * FROM da_workflows ORDER BY id").fetchall():
|
||
d = dict(r)
|
||
d["nodes"] = _json(d.get("nodes"), [])
|
||
rows.append(d)
|
||
return rows
|
||
finally:
|
||
conn.close()
|
||
|
||
|
||
def save_workflow(data):
|
||
conn = _conn()
|
||
try:
|
||
fields = ("name", "business", "nodes", "status")
|
||
vals = [data.get(f, "") for f in fields]
|
||
if isinstance(data.get("nodes"), (list, dict)):
|
||
vals[2] = json.dumps(data["nodes"], ensure_ascii=False)
|
||
if data.get("id"):
|
||
conn.execute("UPDATE da_workflows SET " + ",".join(f"{f}=?" for f in fields) + " WHERE id=?",
|
||
vals + [data["id"]])
|
||
wid = data["id"]
|
||
else:
|
||
cur = conn.execute("INSERT INTO da_workflows(" + ",".join(fields) +
|
||
",created_at) VALUES (" + ",".join("?" * len(fields)) + ",?)", vals + [_now()])
|
||
wid = cur.lastrowid
|
||
log(conn, "流程保存", data.get("name", ""))
|
||
conn.commit()
|
||
return wid
|
||
finally:
|
||
conn.close()
|
||
|
||
|
||
def delete_workflow(wid):
|
||
conn = _conn()
|
||
try:
|
||
conn.execute("DELETE FROM da_workflows WHERE id=?", (wid,))
|
||
conn.commit()
|
||
finally:
|
||
conn.close()
|
||
|
||
|
||
# ==================== 日志 ====================
|
||
def logs(limit=100):
|
||
conn = _conn()
|
||
try:
|
||
return [dict(r) for r in conn.execute("SELECT * FROM da_logs ORDER BY id DESC LIMIT ?", (limit,)).fetchall()]
|
||
finally:
|
||
conn.close()
|
||
|
||
|
||
init_db()
|