Files
xieyi-weixin-/proactive_contact_ui.py
T
2026-11-02 14:05:03 +08:00

315 lines
16 KiB
Python

"""Task mutations and scheduling are serialized; read-only search runs separately."""
import json
import queue
import threading
import uuid
from PySide6.QtCore import QObject, Signal, Slot
from proactive_contact_service import ContactService, PatientGateway
from proactive_contact_scheduler import ContactScheduler, NativeContactTransport, verified_receipt
def operation_result(command, status, message):
action = command.get("action", "")
titles = {
"preview": ("正在生成预览 · 尚未创建任务", "预览已就绪 · 尚未创建任务", "预览失败 · 未创建任务"),
"confirm": ("正在创建任务,请勿重复点击", "任务创建成功", "创建失败 · 本次未创建任务"),
"text": ("正在保存文字", "文字已保存 · 未创建任务", "文字保存失败"),
"add": ("正在核验患者绑定", "客户添加结果", "客户添加失败"),
"resume": ("正在核验任务", "恢复调度结果 · 不代表已发送", "任务恢复失败"),
"pause": ("正在暂停任务", "任务暂停结果", "任务暂停失败"),
"cancel": ("正在取消任务", "任务取消结果", "任务取消失败"),
"delete": ("正在删除任务", "任务删除结果", "任务删除失败"),
"reconcile": ("正在核对回执,不会重发", "发送结果核对完成", "回执暂无法核对"),
}
index = {"running": 0, "success": 1, "error": 2}[status]
return {"id": command.get("request_id") or uuid.uuid4().hex, "action": action, "status": status,
"title": titles.get(action, ("正在处理,请稍候", "操作已完成", "操作失败"))[index],
"message": message}
class ProactiveController(QObject):
changed = Signal(object)
bindingReady = Signal(object)
repliesRequested = Signal(object)
candidatesUpdated = Signal(object)
def __init__(self, root, parent=None, *, reply_active=lambda: False):
super().__init__(parent)
self.root = root
self._reply_active = reply_active
self.state = {"customers": [], "tasks": [], "enabled": True, "busy": False}
self._stop = threading.Event()
self._halt = threading.Event()
self._binding = threading.Event()
self._interrupted = set()
self._jobs = queue.Queue(maxsize=8)
self._thread = None
self._reply_notified = set()
self._candidate_gateway = PatientGateway()
self._candidate_lock = threading.Lock()
self._candidate_wake = threading.Event()
self._candidate_thread = None
self._candidate_serial = 0
self._candidate_pending = None
self._candidate_query = ""
self._candidate_state = {}
self._candidate_owner = ""
self.changed.connect(self._accept)
self.candidatesUpdated.connect(self._accept_candidates)
@Slot(object)
def _accept(self, state):
if state.get("_owner") != self._candidate_owner:
self._candidate_state = {}
self.state = {**state, **self._candidate_state}
@Slot(object)
def _accept_candidates(self, update):
if self._stop.is_set() or update["serial"] != self._candidate_serial:
return
try:
owner = self._candidate_gateway.owner()
except Exception:
owner = ""
if owner != update["owner"]:
update = {**update, "candidates": {}, "candidateSearch": {
"id": update["candidateSearch"]["id"], "status": "error", "message": "登录账号已切换,请重新搜索"}}
self._candidate_owner = owner
self._candidate_state = {"candidates": update.get("candidates", {}),
"candidateSearch": update["candidateSearch"]}
base = self.state if self.state.get("_owner") == owner else {"customers": [], "tasks": [], "busy": False}
self.changed.emit({**base, **self._candidate_state, "_owner": owner})
def _search_candidates(self, command):
command = dict(command)
with self._candidate_lock:
command.setdefault("query", self._candidate_query)
if not command.get("warm"):
self._candidate_query = str(command["query"])
command["server_initiated"] = not bool(command.get("request_id"))
self._candidate_serial += 1
self._candidate_pending = (self._candidate_serial, command)
if self._candidate_thread is None:
self._candidate_thread = threading.Thread(target=self._run_candidates,
daemon=True, name="proactive-customer-search")
self._candidate_thread.start()
self._candidate_wake.set()
def _run_candidates(self):
while not self._stop.is_set():
self._candidate_wake.wait(.2)
self._candidate_wake.clear()
with self._candidate_lock:
pending, self._candidate_pending = self._candidate_pending, None
if pending is None:
continue
serial, command = pending
owner = ""
request_id = command.get("request_id") or uuid.uuid4().hex
def cancelled(expected=serial):
return self._stop.is_set() or expected != self._candidate_serial
def publish(page, status="running", message=""):
if cancelled():
return
rows = page.get("items", [])
checked = sum(not row.get("binding_loading") for row in rows)
self.candidatesUpdated.emit({"serial": serial, "owner": owner, "candidates": page,
"candidateSearch": {"id": request_id, "status": status, "message": message,
"checked": checked, "count": len(rows), "serverInitiated": command.get("server_initiated", False)}})
try:
if command.get("warm"):
self._candidate_gateway.warm_candidates()
continue
owner = self._candidate_gateway.owner()
publish({}, message="正在搜索客户…")
page = self._candidate_gateway.candidates(str(command.get("query", ""))[:100],
max(0, int(command.get("offset", 0))), progress=publish, cancelled=cancelled,
refresh_bindings=command.get("refresh_bindings") is True)
publish(page, "success")
except Exception as exc:
if not command.get("warm"):
publish({}, "error", str(exc)[:300])
def submit(self, payload):
command = {}
try:
command = json.loads(payload) if isinstance(payload, str) else dict(payload)
if not isinstance(command, dict):
raise ValueError("操作参数格式不正确")
action = command.get("action")
if action == "candidates":
self._search_candidates(command)
return
if action == "cancel-candidates":
with self._candidate_lock:
self._candidate_serial += 1
self._candidate_pending = None
return
if action in {"bind", "refresh"}:
self._candidate_gateway.invalidate_candidates()
if action == "bind":
self._binding.set()
if action == "enable" and command.get("enabled") is False:
self._halt.set()
if action in {"pause", "cancel", "delete"}:
self._interrupted.update(str(key) for key in command.get("ids", []))
self._jobs.put_nowait(command)
if self._thread is None:
self._thread = threading.Thread(target=self._run, daemon=True, name="proactive-contact")
self._thread.start()
except (ValueError, TypeError, queue.Full) as exc:
message = str(exc) or "操作队列已满,请稍后重试"
self.changed.emit({**self.state, "message": message, "busy": False,
"operation": operation_result(command if isinstance(command, dict) else {}, "error", message)})
def start(self):
# Starts scheduling persisted, previously confirmed tasks without fetching contacts.
self.submit({"action": "snapshot"})
if self._candidate_thread is None:
self._search_candidates({"warm": True})
def _run(self):
try:
service = ContactService(self.root, PatientGateway(), NativeContactTransport(self.root))
service.transport.reply_active = self._reply_active
except Exception as exc:
message = f"主动联系任务库无法打开:{exc}"
try:
failed_command = self._jobs.get_nowait()
except queue.Empty:
failed_command = {}
self.changed.emit({"customers": [], "tasks": [], "busy": False, "message": message,
"operation": operation_result(failed_command, "error", message)})
self._thread = None
return
scheduler = ContactScheduler(service, stopped=self._stop.is_set,
interrupted=lambda task: self._halt.is_set() or self._binding.is_set() or task["id"] in self._interrupted)
def snapshot(owner):
value = service.snapshot(owner)
value["_owner"] = owner
value["enabled"] = value["enabled"] and not self._halt.is_set()
return value
state = {}
previous_owner = ""
while not self._stop.is_set():
command = None
try:
command = self._jobs.get(timeout=2)
except queue.Empty:
pass
try:
owner = service.gateway.owner()
if owner != previous_owner:
state = {}
service.previews.clear()
previous_owner = owner
if command:
action = command.get("action")
command.setdefault("request_id", uuid.uuid4().hex)
visible = action not in {"snapshot", "discard-preview", "reply-activation-done"}
if visible:
state.update(rejected=[], operation=operation_result(command, "running", "正在核验与处理,请稍候…"))
self.changed.emit({**state, **snapshot(owner), "busy": True})
result = {}
if action == "add":
result = service.add(owner, command.get("items"))
elif action == "text":
result = service.set_text(owner, command.get("ids"), command.get("text"))
result["preview"] = None
service.previews.clear()
elif action == "preview":
state["preview"] = None
service.previews.clear()
result = service.preview(owner, command.get("ids"), command.get("schedule"), text=command.get("text"))
elif action == "discard-preview":
service.previews.clear()
result["preview"] = None
elif action == "confirm":
result = service.confirm(owner, command.get("key"))
result["preview"] = None
elif action in {"pause", "cancel", "resume"}:
result = service.control(owner, command.get("ids"), action)
self._interrupted.difference_update(str(key) for key in command.get("ids", []))
elif action == "delete":
result = service.delete_tasks(owner, command.get("ids"))
self._interrupted.difference_update(str(key) for key in command.get("ids", []))
elif action == "enable":
service.store.enabled(owner, command.get("enabled") is True)
if command.get("enabled") is True:
self._halt.clear()
result["message"] = "主动联系调度已开启" if command.get("enabled") else "主动联系调度已暂停"
elif action == "refresh":
confirmed = service.recheck(owner)
result["message"] = f"客户绑定与任务状态已刷新,补确认 {confirmed} 条已发送任务"
elif action == "reconcile":
confirmed = service.reconcile_receipts(owner)
result["message"] = f"已确认 {confirmed} 条任务发送成功,未重发任何消息" if confirmed else "尚无可确认的新回执,未重发任何消息"
elif action == "reply-activation-done":
if command.get("owner") == owner:
service.store.acknowledge_reply_activations(owner, command.get("ids", []))
elif action == "bind":
import backend_client
account, conversation = str(command.get("account", "")), str(command.get("conversation", ""))
context = backend_client.desktop_patient_context(account, conversation)
if service.gateway.owner() != owner:
raise ValueError("登录账号已切换")
self.bindingReady.emit({"account": account, "conversation": conversation, "context": context})
elif action != "snapshot":
raise ValueError("不支持的主动联系操作")
state.update(result)
if visible:
state["operation"] = operation_result(command, "success", result.get("message", "操作已完成"))
if result.get("rejected") or result.get("errors"):
state["operation"]["status"] = "error"
if service.gateway.owner() != owner:
raise ValueError("登录账号已切换,请刷新")
# A persisted task is acknowledged before scheduling/sending
# can block on the native client or on a network check.
command = None
state.update(snapshot(owner), busy=False)
self.changed.emit(dict(state))
changed = False if self._stop.is_set() else scheduler.tick(owner)
if changed or not state:
if service.gateway.owner() != owner:
raise ValueError("登录账号已切换,请刷新")
state.update(snapshot(owner), busy=False)
self.changed.emit(dict(state))
if not self._stop.is_set() and service.gateway.owner() == owner:
completed = [t for t in service.store.pending_reply_activations(owner)
if (owner, t["id"]) not in self._reply_notified and verified_receipt(t.get("receipt"), t)]
if completed:
self._reply_notified.update((owner, t["id"]) for t in completed)
self.repliesRequested.emit({"owner": owner, "ids": [t["id"] for t in completed]})
except Exception as exc:
if command and command.get("action") == "bind":
self._binding.clear()
state.update(busy=False, message=str(exc)[:500])
state["operation"] = operation_result(command or {"action": "scheduler"}, "error", str(exc)[:500])
if not command and state.get("creation"):
state["operation"]["title"] = "任务已创建,执行状态暂未更新"
# Database state is reloaded even after partial batch failure.
try:
current_owner = service.gateway.owner()
if current_owner != previous_owner:
state = {"busy": False, "message": "登录账号已变化,请刷新",
"operation": operation_result(command or {}, "error", "登录账号已变化,请刷新")}
service.previews.clear()
state.update(snapshot(current_owner))
except Exception:
state = {"customers": [], "tasks": [], "busy": False, "message": str(exc)[:500],
"operation": operation_result(command or {}, "error", str(exc)[:500])}
self.changed.emit(dict(state))
def close(self):
self._stop.set()
self._halt.set()
self._candidate_wake.set()
self._candidate_gateway.close_candidates()