CI / check (push) Failing after 15m48s
Signed-off-by: 南通一次元科技有限公司 <guwangtu@icimeta.com>
595 lines
25 KiB
Python
595 lines
25 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""整改闭环完整版(阶段 C1)
|
||
|
||
工单生命周期:
|
||
草稿 / 待派发 → 整改中 → 待审核 → 待初验 → 待评估 → 已办结
|
||
↑ ↓ 驳回 ↓ 驳回 / 评估不到位
|
||
数据表:da_rectifications(在原表上补列)+ da_rect_history(流转记录)
|
||
"""
|
||
import json
|
||
import sqlite3
|
||
import datetime
|
||
from pathlib import Path
|
||
import operator_context as opctx
|
||
|
||
BASE_DIR = Path(__file__).parent.resolve()
|
||
DB_PATH = BASE_DIR / "digital_audit.db"
|
||
AUDIT_DB = BASE_DIR.parent / "审计项目管理平台" / "audit_data.db"
|
||
RISK_DB = BASE_DIR.parent / "风险管理项目" / "risk_data.db"
|
||
|
||
STATUSES = ["草稿", "待派发", "整改中", "待审核", "待初验", "待评估", "已办结"]
|
||
ACTIONS = {
|
||
"dispatch": ("派发", ["草稿", "待派发"], "整改中"),
|
||
"feedback": ("提交反馈", ["整改中"], "待审核"),
|
||
"audit_pass": ("审核通过", ["待审核"], "待初验"),
|
||
"audit_reject": ("审核驳回", ["待审核"], "整改中"),
|
||
"initial_pass": ("初验通过", ["待初验"], "待评估"),
|
||
"initial_reject": ("初验驳回", ["待初验"], "整改中"),
|
||
"evaluate_pass": ("评估到位", ["待评估"], "已办结"),
|
||
"evaluate_reject": ("评估不到位", ["待评估"], "待初验"),
|
||
}
|
||
|
||
SIX_QUESTIONS = [
|
||
("q1", "问题是否查清"),
|
||
("q2", "责任是否落实"),
|
||
("q3", "整改是否到位"),
|
||
("q4", "制度是否完善"),
|
||
("q5", "问责是否严格"),
|
||
("q6", "效果是否明显"),
|
||
]
|
||
|
||
EXPORT_HEADERS = ["工单编号", "关联项目", "问题描述", "整改要求", "责任部门", "责任人", "分院",
|
||
"问题等级", "优先级", "整改期限", "当前状态", "整改进度", "反馈内容",
|
||
"实际完成日期", "审核意见", "初验意见", "评估意见", "创建时间"]
|
||
|
||
|
||
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=15)
|
||
conn.row_factory = sqlite3.Row
|
||
conn.execute("PRAGMA journal_mode=WAL")
|
||
conn.execute("PRAGMA busy_timeout=15000")
|
||
return conn
|
||
|
||
|
||
def _audit_ro():
|
||
return sqlite3.connect(f"file:{AUDIT_DB.as_posix()}?mode=ro", uri=True, timeout=10)
|
||
|
||
|
||
def _risk_ro():
|
||
return sqlite3.connect(f"file:{RISK_DB.as_posix()}?mode=ro", uri=True, timeout=10)
|
||
|
||
|
||
def _log(action, detail):
|
||
try:
|
||
conn = _conn()
|
||
conn.execute("INSERT INTO da_logs(action, detail, operator, created_at) VALUES (?,?,?,?)",
|
||
(action, detail, opctx.get_operator(), _now()))
|
||
conn.commit()
|
||
conn.close()
|
||
except Exception:
|
||
pass
|
||
|
||
|
||
DIMENSIONS = {
|
||
"branch": ("分院", "COALESCE(NULLIF(branch,''),'总院区')"),
|
||
"dept": ("责任部门", "COALESCE(NULLIF(dept,''),'未明确')"),
|
||
"project": ("关联项目", "COALESCE(NULLIF(project_name,''),'未关联')"),
|
||
"year": ("年度", "substr(COALESCE(created_at,''),1,4)"),
|
||
}
|
||
|
||
|
||
def _filter_sql(filters):
|
||
sql, args = "", []
|
||
if filters.get("branch"):
|
||
sql += " AND COALESCE(branch,'总院区')=?"
|
||
args.append(filters["branch"])
|
||
if filters.get("dept"):
|
||
sql += " AND COALESCE(dept,'未明确')=?"
|
||
args.append(filters["dept"])
|
||
if filters.get("year"):
|
||
sql += " AND substr(COALESCE(created_at,''),1,4)=?"
|
||
args.append(filters["year"])
|
||
if filters.get("status"):
|
||
sql += " AND status=?"
|
||
args.append(filters["status"])
|
||
return sql, args
|
||
|
||
|
||
def report(dimension="dept", filters=None):
|
||
filters = filters or {}
|
||
if dimension not in DIMENSIONS:
|
||
dimension = "dept"
|
||
label, expr = DIMENSIONS[dimension]
|
||
where, args = _filter_sql(filters)
|
||
conn = _conn()
|
||
try:
|
||
rows = conn.execute(f"""
|
||
SELECT {expr} AS name, COUNT(*) AS total,
|
||
SUM(CASE WHEN status='已办结' THEN 1 ELSE 0 END) AS done,
|
||
SUM(CASE WHEN status!='已办结' AND deadline!='' AND deadline<? THEN 1 ELSE 0 END) AS overdue,
|
||
SUM(CASE WHEN status IN ('待派发','整改中','待审核','待初验','待评估') THEN 1 ELSE 0 END) AS pending
|
||
FROM da_rectifications WHERE 1=1 {where}
|
||
GROUP BY name ORDER BY total DESC
|
||
""", [_today()] + args).fetchall()
|
||
result = []
|
||
for r in rows:
|
||
d = dict(r)
|
||
d["done_rate"] = round((d["done"] or 0) * 100 / d["total"], 1) if d["total"] else 0
|
||
result.append(d)
|
||
# 月度趋势(近 6 个月创建/办结)
|
||
trend = []
|
||
for i in range(5, -1, -1):
|
||
month = (datetime.date.today().replace(day=1) - datetime.timedelta(days=30 * i)).strftime("%Y-%m")
|
||
created = conn.execute("SELECT COUNT(*) c FROM da_rectifications WHERE substr(created_at,1,7)=?", (month,)).fetchone()["c"]
|
||
closed = conn.execute("SELECT COUNT(*) c FROM da_rectifications WHERE substr(closed_at,1,7)=?", (month,)).fetchone()["c"]
|
||
trend.append({"month": month, "created": created, "closed": closed})
|
||
return {"dimension": dimension, "dimension_label": label, "rows": result, "trend": trend}
|
||
finally:
|
||
conn.close()
|
||
|
||
|
||
def map_data():
|
||
"""组织分布:分院 → 科室,用于整改地图/下钻。"""
|
||
conn = _conn()
|
||
try:
|
||
branches = {}
|
||
rows = conn.execute("""
|
||
SELECT COALESCE(branch,'总院区') branch, COALESCE(dept,'未明确') dept, status, deadline
|
||
FROM da_rectifications
|
||
""").fetchall()
|
||
for r in rows:
|
||
b = branches.setdefault(r["branch"], {"name": r["branch"], "total": 0, "done": 0,
|
||
"overdue": 0, "departments": {}})
|
||
d = b["departments"].setdefault(r["dept"], {"name": r["dept"], "total": 0, "done": 0, "overdue": 0})
|
||
b["total"] += 1
|
||
d["total"] += 1
|
||
if r["status"] == "已办结":
|
||
b["done"] += 1
|
||
d["done"] += 1
|
||
elif r["deadline"] and r["deadline"] < _today():
|
||
b["overdue"] += 1
|
||
d["overdue"] += 1
|
||
out = []
|
||
for b in branches.values():
|
||
b["departments"] = sorted(b["departments"].values(), key=lambda x: -x["total"])
|
||
b["done_rate"] = round(b["done"] * 100 / b["total"], 1) if b["total"] else 0
|
||
out.append(b)
|
||
out.sort(key=lambda x: -x["total"])
|
||
return out
|
||
finally:
|
||
conn.close()
|
||
|
||
|
||
def report_export(dimension="dept", filters=None):
|
||
from openpyxl import Workbook
|
||
from io import BytesIO
|
||
data = report(dimension, filters)
|
||
wb = Workbook()
|
||
ws = wb.active
|
||
ws.title = "整改报表"
|
||
ws.append([data["dimension_label"], "工单总数", "已办结", "未办结", "超期", "完成率(%)"])
|
||
for r in data["rows"]:
|
||
ws.append([r["name"], r["total"], r["done"], r["pending"], r["overdue"], r["done_rate"]])
|
||
ws2 = wb.create_sheet("趋势")
|
||
ws2.append(["月份", "新建", "办结"])
|
||
for t in data["trend"]:
|
||
ws2.append([t["month"], t["created"], t["closed"]])
|
||
buf = BytesIO()
|
||
wb.save(buf)
|
||
return buf.getvalue()
|
||
|
||
|
||
def init_db():
|
||
conn = _conn()
|
||
cols = [r[1] for r in conn.execute("PRAGMA table_info(da_rectifications)")]
|
||
if not cols:
|
||
# 兼容首次运行:创建基础表(正常情况下由 digital_audit_service 创建)
|
||
conn.execute("""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)""")
|
||
cols = [r[1] for r in conn.execute("PRAGMA table_info(da_rectifications)")]
|
||
for col, ddl in [
|
||
("work_no", "TEXT DEFAULT ''"),
|
||
("branch", "TEXT DEFAULT '总院区'"),
|
||
("priority", "TEXT DEFAULT '中'"),
|
||
("requirement", "TEXT DEFAULT ''"),
|
||
("feedback", "TEXT DEFAULT ''"),
|
||
("actual_date", "TEXT DEFAULT ''"),
|
||
("audit_comment", "TEXT DEFAULT ''"),
|
||
("initial_comment", "TEXT DEFAULT ''"),
|
||
("evaluate_comment", "TEXT DEFAULT ''"),
|
||
("dispatched_at", "TEXT DEFAULT ''"),
|
||
("feedback_at", "TEXT DEFAULT ''"),
|
||
("audited_at", "TEXT DEFAULT ''"),
|
||
("verified_at", "TEXT DEFAULT ''"),
|
||
("evaluated_at", "TEXT DEFAULT ''"),
|
||
("closed_at", "TEXT DEFAULT ''"),
|
||
("updated_at", "TEXT DEFAULT ''"),
|
||
]:
|
||
if col not in cols:
|
||
conn.execute(f"ALTER TABLE da_rectifications ADD COLUMN {col} {ddl}")
|
||
conn.execute("UPDATE da_rectifications SET branch='总院区' WHERE branch IS NULL OR branch=''")
|
||
conn.execute("""CREATE TABLE IF NOT EXISTS da_rect_history (
|
||
id INTEGER PRIMARY KEY AUTOINCREMENT, rect_id INTEGER, action TEXT,
|
||
from_status TEXT, to_status TEXT, comment TEXT, operator TEXT, created_at TEXT)""")
|
||
conn.executescript("""
|
||
CREATE INDEX IF NOT EXISTS idx_da_rect_branch ON da_rectifications(branch);
|
||
CREATE INDEX IF NOT EXISTS idx_da_rect_owner ON da_rectifications(owner);
|
||
CREATE INDEX IF NOT EXISTS idx_da_rect_history_rect ON da_rect_history(rect_id);
|
||
""")
|
||
# 旧状态迁移
|
||
conn.execute("UPDATE da_rectifications SET status='待派发' WHERE status IN ('待整改','') OR status IS NULL")
|
||
conn.execute("UPDATE da_rectifications SET status='待初验' WHERE status='待验收'")
|
||
conn.execute("UPDATE da_rectifications SET status='已办结' WHERE status='已验收'")
|
||
conn.execute("UPDATE da_rectifications SET status='整改中' WHERE status='已超期'")
|
||
# 补工单编号
|
||
rows = conn.execute("SELECT id,created_at,work_no FROM da_rectifications").fetchall()
|
||
counter = {}
|
||
for r in rows:
|
||
if r["work_no"]:
|
||
continue
|
||
day = (r["created_at"] or _now())[:10].replace("-", "") or datetime.datetime.now().strftime("%Y%m%d")
|
||
counter[day] = counter.get(day, 0) + 1
|
||
conn.execute("UPDATE da_rectifications SET work_no=? WHERE id=?",
|
||
(f"ZG-{day}-{counter[day]:03d}", r["id"]))
|
||
conn.commit()
|
||
conn.close()
|
||
|
||
|
||
def _project_name(project_id):
|
||
if not project_id:
|
||
return ""
|
||
try:
|
||
conn = _audit_ro()
|
||
row = conn.execute("SELECT name FROM projects WHERE id=?", (project_id,)).fetchone()
|
||
conn.close()
|
||
return row[0] if row else ""
|
||
except Exception:
|
||
return ""
|
||
|
||
|
||
def _work_no(conn):
|
||
day = datetime.datetime.now().strftime("%Y%m%d")
|
||
row = conn.execute("SELECT COUNT(*) c FROM da_rectifications WHERE work_no LIKE ?", (f"ZG-{day}-%",)).fetchone()
|
||
return f"ZG-{day}-{(row['c'] if row else 0) + 1:03d}"
|
||
|
||
|
||
def _is_overdue(row):
|
||
deadline = (row["deadline"] or "")[:10]
|
||
return bool(deadline and deadline < _today() and row["status"] != "已办结")
|
||
|
||
|
||
def _to_item(row, project_names=None):
|
||
d = dict(row)
|
||
d["overdue"] = _is_overdue(d)
|
||
if not d.get("project_name") and d.get("project_id"):
|
||
d["project_name"] = (project_names or {}).get(d["project_id"]) or _project_name(d["project_id"])
|
||
return d
|
||
|
||
|
||
def list_rectifications(status=None, keyword=None, level=None, overdue=False):
|
||
conn = _conn()
|
||
try:
|
||
sql = "SELECT * FROM da_rectifications WHERE 1=1"
|
||
args = []
|
||
if status:
|
||
sql += " AND status=?"
|
||
args.append(status)
|
||
if level:
|
||
sql += " AND level=?"
|
||
args.append(level)
|
||
if keyword:
|
||
sql += " AND (issue LIKE ? OR dept LIKE ? OR owner LIKE ? OR work_no LIKE ?)"
|
||
args += [f"%{keyword}%"] * 4
|
||
sql += " ORDER BY id DESC"
|
||
rows = [_to_item(r) for r in conn.execute(sql, args).fetchall()]
|
||
if overdue:
|
||
rows = [r for r in rows if r["overdue"]]
|
||
return rows
|
||
finally:
|
||
conn.close()
|
||
|
||
|
||
def stats():
|
||
rows = list_rectifications()
|
||
by_status = {s: 0 for s in STATUSES}
|
||
for r in rows:
|
||
by_status[r["status"]] = by_status.get(r["status"], 0) + 1
|
||
return {
|
||
"total": len(rows),
|
||
"by_status": by_status,
|
||
"overdue": sum(1 for r in rows if r["overdue"]),
|
||
"done": by_status.get("已办结", 0),
|
||
"done_rate": round(by_status.get("已办结", 0) * 100 / len(rows), 1) if rows else 0,
|
||
}
|
||
|
||
|
||
def create(data):
|
||
conn = _conn()
|
||
try:
|
||
fields = ("project_id", "project_name", "issue", "dept", "owner", "level", "priority",
|
||
"requirement", "status", "deadline", "progress", "source_type", "source_id", "branch")
|
||
vals = [data.get(f, "") for f in fields]
|
||
if not vals[1] and vals[0]:
|
||
vals[1] = _project_name(vals[0])
|
||
if not vals[8] or vals[8] not in STATUSES:
|
||
vals[8] = "待派发"
|
||
vals[10] = 0 if vals[10] in ("", None) else vals[10]
|
||
if not vals[13]:
|
||
vals[13] = "总院区"
|
||
work_no = _work_no(conn)
|
||
now = _now()
|
||
cur = conn.execute("INSERT INTO da_rectifications(" + ",".join(fields) +
|
||
",work_no,created_at,updated_at) VALUES (" +
|
||
",".join("?" * len(fields)) + ",?,?,?)", vals + [work_no, now, now])
|
||
rid = cur.lastrowid
|
||
conn.execute("""INSERT INTO da_rect_history(rect_id,action,from_status,to_status,comment,operator,created_at)
|
||
VALUES (?,?,?,?,?,?,?)""", (rid, "创建工单", "", vals[8], "", opctx.get_operator(), now))
|
||
conn.commit()
|
||
_log("整改工单创建", f"{work_no}:{vals[2]}")
|
||
return {"id": rid, "work_no": work_no}
|
||
finally:
|
||
conn.close()
|
||
|
||
|
||
def update_basic(rid, data):
|
||
conn = _conn()
|
||
try:
|
||
allowed = ("project_id", "project_name", "issue", "dept", "owner", "level",
|
||
"priority", "requirement", "deadline", "progress", "branch")
|
||
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) +
|
||
",updated_at=? WHERE id=?", [data[f] for f in fields] + [_now(), rid])
|
||
conn.commit()
|
||
row = conn.execute("SELECT * FROM da_rectifications WHERE id=?", (rid,)).fetchone()
|
||
return _to_item(row) if row else None
|
||
finally:
|
||
conn.close()
|
||
|
||
|
||
def action(rid, action_key, data):
|
||
"""执行工单状态流转。返回 (ok, message, item)。"""
|
||
if action_key not in ACTIONS:
|
||
return False, "未知操作", None
|
||
label, allowed_from, to_status = ACTIONS[action_key]
|
||
conn = _conn()
|
||
try:
|
||
row = conn.execute("SELECT * FROM da_rectifications WHERE id=?", (rid,)).fetchone()
|
||
if not row:
|
||
return False, "工单不存在", None
|
||
from_status = row["status"]
|
||
if from_status not in allowed_from:
|
||
return False, f"当前状态「{from_status}」不能执行「{label}」", _to_item(row)
|
||
now = _now()
|
||
updates = {"status": to_status, "updated_at": now}
|
||
comment = data.get("comment", "")
|
||
if action_key == "dispatch":
|
||
updates["dispatched_at"] = now
|
||
if data.get("deadline"):
|
||
updates["deadline"] = data["deadline"]
|
||
if data.get("owner"):
|
||
updates["owner"] = data["owner"]
|
||
elif action_key == "feedback":
|
||
updates["feedback"] = data.get("feedback", "")
|
||
updates["actual_date"] = data.get("actual_date", "")
|
||
updates["feedback_at"] = now
|
||
if data.get("progress") is not None:
|
||
updates["progress"] = int(data.get("progress") or 0)
|
||
elif action_key in ("audit_pass", "audit_reject"):
|
||
updates["audit_comment"] = comment
|
||
updates["audited_at"] = now
|
||
elif action_key in ("initial_pass", "initial_reject"):
|
||
for k, _ in SIX_QUESTIONS:
|
||
updates[k] = data.get(k, row[k] or "")
|
||
updates["initial_comment"] = comment
|
||
updates["verified_at"] = now
|
||
if action_key == "initial_pass":
|
||
updates["progress"] = max(int(row["progress"] or 0), 90)
|
||
elif action_key in ("evaluate_pass", "evaluate_reject"):
|
||
updates["evaluate_comment"] = comment
|
||
updates["evaluated_at"] = now
|
||
if action_key == "evaluate_pass":
|
||
updates["status"] = "已办结"
|
||
updates["closed_at"] = now
|
||
updates["progress"] = 100
|
||
updates["result"] = "整改到位"
|
||
else:
|
||
updates["result"] = "整改不到位"
|
||
sets = ",".join(f"{k}=?" for k in updates)
|
||
conn.execute(f"UPDATE da_rectifications SET {sets} WHERE id=?", list(updates.values()) + [rid])
|
||
conn.execute("""INSERT INTO da_rect_history(rect_id,action,from_status,to_status,comment,operator,created_at)
|
||
VALUES (?,?,?,?,?,?,?)""", (rid, label, from_status, updates["status"], comment, opctx.get_operator(), now))
|
||
if action_key == "dispatch":
|
||
conn.execute("""INSERT INTO da_rect_history(rect_id,action,from_status,to_status,comment,operator,created_at)
|
||
VALUES (?,?,?,?,?,?,?)""", (rid, "派发通知", from_status, "整改中", "已派发责任部门", opctx.get_operator(), now))
|
||
conn.commit()
|
||
_log("整改流转", f"工单 {row['work_no']}:{label}({from_status}→{updates['status']})")
|
||
new_row = conn.execute("SELECT * FROM da_rectifications WHERE id=?", (rid,)).fetchone()
|
||
return True, "操作成功", _to_item(new_row)
|
||
finally:
|
||
conn.close()
|
||
|
||
|
||
def history(rid):
|
||
conn = _conn()
|
||
try:
|
||
return [dict(r) for r in conn.execute(
|
||
"SELECT * FROM da_rect_history WHERE rect_id=? ORDER BY id", (rid,)).fetchall()]
|
||
finally:
|
||
conn.close()
|
||
|
||
|
||
def delete(rid):
|
||
conn = _conn()
|
||
try:
|
||
conn.execute("DELETE FROM da_rect_history WHERE rect_id=?", (rid,))
|
||
conn.execute("DELETE FROM da_rectifications WHERE id=?", (rid,))
|
||
conn.commit()
|
||
_log("整改删除", f"ID {rid}")
|
||
finally:
|
||
conn.close()
|
||
|
||
|
||
def import_findings():
|
||
"""从审计分析结果、检查风险数据导入高风险问题(生成待派发工单,去重)。"""
|
||
created = 0
|
||
conn = _conn()
|
||
try:
|
||
try:
|
||
a = _audit_ro()
|
||
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:
|
||
try:
|
||
findings = json.loads(r["findings"] or "[]")
|
||
if isinstance(findings, list) and findings:
|
||
f0 = findings[0]
|
||
issue = (f0.get("title") or f0.get("description") or "") if isinstance(f0, dict) else str(f0)
|
||
except Exception:
|
||
pass
|
||
if not issue:
|
||
continue
|
||
_insert_import(conn, r["project_id"], r["project_name"], issue[:500], "待明确", "高", "analysis", r["id"])
|
||
created += 1
|
||
except Exception:
|
||
pass
|
||
try:
|
||
r = _risk_ro()
|
||
rows = r.execute("""SELECT id, risk_desc, department, final_risk_level, project_id
|
||
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
|
||
_insert_import(conn, None, "检查风险数据", (x["risk_desc"] or "")[:500],
|
||
x["department"] or "待明确", "高", "inspection", x["id"])
|
||
created += 1
|
||
except Exception:
|
||
pass
|
||
conn.commit()
|
||
_log("整改导入", f"从审计发现导入 {created} 项")
|
||
return created
|
||
finally:
|
||
conn.close()
|
||
|
||
|
||
def _insert_import(conn, project_id, project_name, issue, dept, level, source_type, source_id):
|
||
now = _now()
|
||
work_no = _work_no(conn)
|
||
deadline = (datetime.date.today() + datetime.timedelta(days=30)).strftime("%Y-%m-%d")
|
||
cur = conn.execute("""INSERT INTO da_rectifications(project_id,project_name,issue,dept,owner,level,priority,
|
||
requirement,status,deadline,progress,source_type,source_id,work_no,created_at,updated_at)
|
||
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""",
|
||
(project_id, project_name, issue, dept, "", level, "中", "", "待派发", deadline,
|
||
0, source_type, source_id, work_no, now, now))
|
||
conn.execute("""INSERT INTO da_rect_history(rect_id,action,from_status,to_status,comment,operator,created_at)
|
||
VALUES (?,?,?,?,?,?,?)""", (cur.lastrowid, "导入工单", "", "待派发", "从审计发现导入", "系统", now))
|
||
|
||
|
||
def import_rows(rows):
|
||
"""批量导入工单。rows 为 dict 列表,字段使用中文表头。"""
|
||
conn = _conn()
|
||
ok, errors = 0, []
|
||
try:
|
||
for i, row in enumerate(rows, start=2):
|
||
issue = (row.get("问题描述") or row.get("issue") or "").strip()
|
||
if not issue:
|
||
errors.append(f"第 {i} 行:问题描述为空")
|
||
continue
|
||
project_id = row.get("关联项目ID") or row.get("project_id")
|
||
try:
|
||
project_id = int(project_id) if str(project_id).strip().isdigit() else None
|
||
except Exception:
|
||
project_id = None
|
||
project_name = row.get("关联项目") or _project_name(project_id)
|
||
deadline = (row.get("整改期限") or row.get("deadline") or "").strip()
|
||
level = (row.get("问题等级") or row.get("level") or "中").strip()
|
||
if level not in ("高", "中", "低"):
|
||
level = "中"
|
||
now = _now()
|
||
work_no = _work_no(conn)
|
||
fields = ("project_id", "project_name", "issue", "requirement", "dept", "owner",
|
||
"level", "priority", "status", "deadline", "progress", "work_no", "branch", "created_at", "updated_at")
|
||
vals = [project_id, project_name, issue[:500],
|
||
row.get("整改要求") or row.get("requirement") or "",
|
||
row.get("责任部门") or row.get("dept") or "",
|
||
row.get("责任人") or row.get("owner") or "",
|
||
level, row.get("优先级") or "中", "待派发", deadline, 0, work_no,
|
||
row.get("分院") or row.get("院区") or "总院区", now, now]
|
||
cur = conn.execute("INSERT INTO da_rectifications(" + ",".join(fields) + ") VALUES (" +
|
||
",".join("?" * len(fields)) + ")", vals)
|
||
conn.execute("""INSERT INTO da_rect_history(rect_id,action,from_status,to_status,comment,operator,created_at)
|
||
VALUES (?,?,?,?,?,?,?)""", (cur.lastrowid, "批量导入", "", "待派发", "", opctx.get_operator(), now))
|
||
ok += 1
|
||
conn.commit()
|
||
_log("整改批量导入", f"成功 {ok} 条,失败 {len(errors)} 条")
|
||
return {"ok": ok, "errors": errors[:20]}
|
||
finally:
|
||
conn.close()
|
||
|
||
|
||
def export_xlsx():
|
||
from openpyxl import Workbook
|
||
from io import BytesIO
|
||
rows = list_rectifications()
|
||
wb = Workbook()
|
||
ws = wb.active
|
||
ws.title = "整改工单"
|
||
ws.append(EXPORT_HEADERS)
|
||
for r in rows:
|
||
ws.append([r.get("work_no"), r.get("project_name"), r.get("issue"), r.get("requirement"),
|
||
r.get("dept"), r.get("owner"), r.get("branch") or "总院区",
|
||
r.get("level"), r.get("priority"),
|
||
r.get("deadline"), r.get("status"), r.get("progress"), r.get("feedback"),
|
||
r.get("actual_date"), r.get("audit_comment"), r.get("initial_comment"),
|
||
r.get("evaluate_comment"), r.get("created_at")])
|
||
buf = BytesIO()
|
||
wb.save(buf)
|
||
return buf.getvalue()
|
||
|
||
|
||
def template_xlsx():
|
||
from openpyxl import Workbook
|
||
from io import BytesIO
|
||
wb = Workbook()
|
||
ws = wb.active
|
||
ws.title = "整改工单导入模板"
|
||
ws.append(["关联项目ID", "关联项目", "问题描述", "整改要求", "责任部门", "责任人",
|
||
"问题等级", "优先级", "整改期限", "分院"])
|
||
ws.append(["", "", "示例:部分耗材供应商准入资料不完整", "补充供应商资质材料", "采购科", "张三",
|
||
"中", "中", "2026-12-31", "总院区"])
|
||
buf = BytesIO()
|
||
wb.save(buf)
|
||
return buf.getvalue()
|
||
|
||
|
||
init_db()
|