browser_ops.py
13.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
"""browser-use 封装:在有头 Chrome 里真实点击 / 填写 / 爬取仿 DMS 页面。
每次点击前先让页面画出红框 + 光标 + 文字标签(agent_overlay.js),观众能看到 Agent 点了哪里;
真正的点击走 browser-use 的 CDP 鼠标事件(actor.Element.click),不是 JS 模拟。
"""
import asyncio
import base64
import json
import os
import shutil
import subprocess
import tempfile
from pathlib import Path
from typing import Awaitable, Callable
from browser_use import Browser
StepCb = Callable[[str], Awaitable[None] | None]
ORDER_TYPE_SO = "SO/库存补充订单"
CHROME_MARK = "browser-use-user-data-dir-stock-demo" # Agent 专用 Chrome 配置目录前缀(须含 browser-use-user-data-dir-,否则 browser-use 会另建临时副本),用来精确关闭它,不碰你自己的 Chrome
def kill_demo_chrome() -> None:
"""强制关闭 Agent 启动的 Chrome(只匹配专用配置目录),并清理临时配置目录。"""
try:
if os.name == "nt":
subprocess.run(
["powershell", "-NoProfile", "-Command",
"Get-CimInstance Win32_Process -Filter \"Name='chrome.exe'\" | "
f"Where-Object {{ $_.CommandLine -like '*{CHROME_MARK}*' }} | "
"ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue }"],
capture_output=True, timeout=20, creationflags=0x08000000,
)
else:
subprocess.run(["pkill", "-f", CHROME_MARK], capture_output=True, timeout=10)
except Exception:
pass
for d in Path(tempfile.gettempdir()).glob(f"{CHROME_MARK}-*"):
shutil.rmtree(d, ignore_errors=True)
class DmsError(RuntimeError):
"""DMS 页面返回业务错误(如超出当日可订)或等待超时。"""
class DmsBrowser:
def __init__(self, base_url: str, user: str, password: str, on_step: StepCb | None = None, pace: float | None = None):
self.base = base_url.rstrip("/")
self.user, self.password = user, password
self.on_step = on_step
# 演示节奏:AGENT_SLOW 越大越慢(默认 2 = 在原速基础上放慢一倍;设 0.1 可快速跑通测试)
self.k = float(os.environ.get("AGENT_SLOW", "2"))
self.pace = 0.7 * self.k if pace is None else pace # 每次点击前红框停留秒数
self.b: Browser | None = None
self.logged_in = False
# ---------- 基础 ----------
async def step(self, text: str) -> None:
if self.on_step:
r = self.on_step(text)
if asyncio.iscoroutine(r):
await r
await asyncio.sleep(0.3 * self.k)
async def start(self) -> None:
if self.b is not None:
return
headless = os.environ.get("DEMO_HEADLESS", "false").lower() in ("1", "true", "yes")
kill_demo_chrome() # 清掉上次遗留的 Agent Chrome
self.b = Browser(
headless=headless, keep_alive=True,
user_data_dir=tempfile.mkdtemp(prefix=f"{CHROME_MARK}-"),
window_size={"width": 1366, "height": 820},
window_position={"width": 0, "height": 0},
)
await self.b.start()
async def close(self) -> None:
if self.b is not None:
try:
await self.b.kill()
except Exception:
pass
self.b, self.logged_in = None, False
await asyncio.get_event_loop().run_in_executor(None, kill_demo_chrome)
async def page(self):
page = await self.b.get_current_page()
if page is None:
raise DmsError("浏览器没有可用页面")
return page
async def js(self, code: str, *args) -> str:
return await (await self.page()).evaluate(code, *args)
async def js_json(self, code: str, *args):
return json.loads(await self.js(code, *args))
async def url(self) -> str:
return await (await self.page()).get_url()
async def goto(self, path: str) -> None:
await self.b.navigate_to(self.base + path)
async def wait_for(self, cond_js: str, *args, timeout: float = 15.0, what: str = "") -> None:
"""轮询页面条件(箭头函数,返回 truthy)。页面跳转中的瞬时错误忽略。"""
end = asyncio.get_event_loop().time() + timeout
while True:
try:
if (await self.js(cond_js, *args)) in ("True", "true", "1"):
return
except Exception:
pass
if asyncio.get_event_loop().time() > end:
raise DmsError(f"等待超时:{what or cond_js}")
await asyncio.sleep(0.15)
async def wait_selector(self, selector: str, timeout: float = 15.0) -> None:
await self.wait_for("(s) => !!document.querySelector(s)", selector, timeout=timeout, what=selector)
async def _element(self, selector: str):
await self.wait_selector(selector)
els = await (await self.page()).get_elements_by_css_selector(selector)
if not els:
raise DmsError(f"找不到元素 {selector}")
return els[0]
async def highlight(self, selector: str, label: str) -> None:
await self.js("(s,l) => !!(window.__agentHighlight && window.__agentHighlight(s,l))", selector, label)
await asyncio.sleep(self.pace)
# ---------- 动作 ----------
async def click(self, selector: str, label: str) -> None:
await self.step(f"点击『{label}』")
el = await self._element(selector)
await self.highlight(selector, f"Agent:点击『{label}』")
try:
await self.js("() => window.__agentRipple && window.__agentRipple()")
await el.click()
except Exception:
await self.js("(s) => document.querySelector(s).click()", selector)
await asyncio.sleep(0.25 * self.k)
async def fill(self, selector: str, text: str, label: str) -> None:
await self.step(f"在『{label}』输入 {text}")
el = await self._element(selector)
await self.highlight(selector, f"Agent:输入『{text}』")
await el.fill(text)
await asyncio.sleep(0.2 * self.k)
async def select(self, selector: str, option: str, label: str) -> None:
await self.step(f"『{label}』选择 {option}")
el = await self._element(selector)
await self.highlight(selector, f"Agent:选择『{option}』")
await el.select_option(option)
await asyncio.sleep(0.2 * self.k)
async def screenshot(self, path: Path) -> Path:
"""截系统真实页面(截图前隐藏 Agent 的红框/光标,保证截到的是系统页面)。"""
hide = "(v) => document.querySelectorAll('.agent-box,.agent-cursor,.agent-badge').forEach(e => e.style.visibility = v)"
await self.js(hide, "hidden")
await asyncio.sleep(0.15)
data = await (await self.page()).screenshot(format="png")
await self.js(hide, "visible")
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(base64.b64decode(data))
return path
# ---------- 业务步骤 ----------
async def login(self) -> None:
if self.logged_in:
return
await self.start()
await self.step("打开厂家 DMS 登录页")
await self.goto("/dms-login")
await self.wait_selector("#username")
await self.js("() => { try { localStorage.setItem('agent_mode', '1'); } catch (e) {} }")
await self.fill("#username", self.user, "账号")
await self.fill("#password", self.password, "密码")
await self.click("#login-btn", "登录")
await self.wait_selector("#nav-purchase")
self.logged_in = True
async def _open_menu(self, nav: str, nav_label: str, link: str, link_label: str, path_part: str) -> None:
if path_part in await self.url():
return
await self.click(nav, nav_label)
await self.click(link, link_label)
await self.wait_for("(p) => location.pathname.includes(p)", path_part, what=f"进入 {link_label}")
async def read_store_inventory(self) -> list[dict]:
"""库存管理 → 零件库存查询:读 库存 / 在途 / 当日剩余可订。"""
await self.login()
await self._open_menu("#nav-stock", "库存管理", "#menu-part-inventory", "零件库存查询", "part-inventory")
await self.wait_selector("#part-inventory-table tbody tr")
rows = await self.js_json(
"""() => JSON.stringify([...document.querySelectorAll('#part-inventory-table tbody tr')].map(tr => ({
part_no: tr.querySelector('.c-part').textContent.trim(),
name: tr.querySelector('.c-name').textContent.trim(),
stock: +tr.querySelector('.c-stock').textContent,
in_transit: +tr.querySelector('.c-transit').textContent,
daily_remaining: +tr.querySelector('.c-remaining').textContent})))"""
)
await self.step(f"读取到 {len(rows)} 个零件的库存 / 在途 / 当日剩余可订")
return rows
async def query_warehouses(self, part_no: str) -> list[dict]:
"""库存管理 → 全国仓库库存查询:输零件号检索,返回各仓可销售数量。"""
await self.login()
await self._open_menu("#nav-stock", "库存管理", "#menu-national-inventory", "全国仓库库存查询", "national-inventory")
await self.fill("#part-no-input", part_no, "零件号码")
await self.click("#search-btn", "检索")
await self.wait_for(
"(p) => { const t = document.querySelector('#warehouse-table'); return !!t && t.dataset.resultFor === p && "
"!!(t.querySelector('tbody tr[data-warehouse]') || document.querySelector('#query-message')); }",
part_no, what=f"{part_no} 仓库存结果",
)
rows = await self.js_json(
"""() => JSON.stringify([...document.querySelectorAll('#warehouse-table tbody tr[data-warehouse]')].map(tr => ({
warehouse: tr.dataset.warehouse, qty: +tr.querySelector('.c-qty').textContent})))"""
)
sel = [r for r in rows if r["warehouse"] in ("GTMC广州", "华南GTMC")]
await self.step(f"{part_no} 仓库存:" + "、".join(f"{r['warehouse']} {r['qty']}" for r in sel))
return rows
async def _open_po_list(self) -> None:
if "purchaseOrderManage" in await self.url():
return
await self.click("#nav-purchase", "采购管理")
await self.click("#menu-po-manage", "采购订单管理")
await self.wait_selector("#po-table")
async def create_order(self, part_no: str, qty: int, name: str = "") -> str:
"""采购订单管理 → 创建新订单 → 选 SO → 快速添加 → 保存。返回 PO 单号(状态:待提交)。"""
await self.login()
if os.environ.get("AGENT_MODE", "script") == "llm":
from .llm_mode import create_order_llm
return await create_order_llm(self, part_no, qty, name)
await self._open_po_list()
await self.click("#create-order-btn", "创建新订单")
await self.wait_selector("#order-type")
await self.select("#order-type", ORDER_TYPE_SO, "订单类型")
await self.fill("#quick-add-input", f"{part_no}*{qty}", "快速添加")
await self.click("#add-item-btn", "添加订购项")
await self.wait_for("(p) => !!document.querySelector(`#detail-body tr[data-part-no=\"${p}\"]`)", part_no,
what=f"明细行 {part_no}")
await self.click("#save-btn", "保存")
await self.wait_for(
"() => !!document.body.dataset.savedPo || !!document.querySelector('.toast.err:not([hidden])')", what="保存结果"
)
err = await self.js("() => { const e = document.querySelector('.toast.err:not([hidden])'); return e ? e.textContent : ''; }")
if err:
raise DmsError(f"{name or part_no}:{err}")
po_no = await self.js("() => document.body.dataset.savedPo")
await self.wait_selector("#po-table")
await self.wait_for("(p) => !!document.querySelector(`tr[data-po=\"${p}\"]`)", po_no, what="订单出现在列表")
await self.step(f"已保存订单 {po_no}(待提交)")
return po_no
async def submit_orders(self, po_nos: list[str]) -> None:
"""回列表 → 逐个选中圆形控件 → 点『检查并提交』。"""
await self.login()
await self._open_po_list()
for po in po_nos:
await self.click(f'.circle[data-po-select="{po}"]', f"选中订单 {po}")
await self.click("#submit-btn", "检查并提交")
await self.wait_for(
"(ps) => ps.every(p => { const r = document.querySelector(`tr[data-po=\"${p}\"]`); return r && r.dataset.status === '已提交'; })",
po_nos, timeout=20, what="订单变为已提交",
)
await self.step("订单状态已变为「已提交」")
async def show_po_list(self) -> None:
"""回到采购订单列表(用于截图)。"""
await self.login()
if "purchaseOrderManage" in await self.url():
await self.js("() => location.reload()")
await self.wait_selector("#po-table")
await asyncio.sleep(0.4)
else:
await self._open_po_list()