@whyshu/argent-engine 0.8.0-rc.13 → 0.8.0-rc.15
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/MANIFEST.json +71 -36
- package/engine/VERSION +1 -1
- package/engine/configs/mcp-tools.snapshot.json +8 -1
- package/engine/core/contracts/argent.contracts.json +2 -2
- package/engine/core/mcp/erp-server.mjs +10 -6
- package/engine/core/mcp/gateway.mjs +3 -3
- package/engine/core/mcp/server.mjs +245 -0
- package/engine/scripts/appointment-worker.mjs +456 -35
- package/engine/scripts/appointment_grab.py +1329 -284
- package/engine/scripts/appointment_rules.py +118 -0
- package/engine/scripts/argent-timers.mjs +227 -0
- package/engine/scripts/capability-packs.lock.json +323 -300
- package/engine/scripts/check-version-consistency.mjs +14 -1
- package/engine/scripts/collect-intel.mjs +108 -0
- package/engine/scripts/daily-report-timer-plist.sh +18 -4
- package/engine/scripts/daily-report-timers.sh +1 -1
- package/engine/scripts/daily-report.mjs +22 -0
- package/engine/scripts/engine-manifest.mjs +90 -0
- package/engine/scripts/flow-requirements.json +122 -99
- package/engine/scripts/full-exec-worker.mjs +251 -0
- package/engine/scripts/gen-preset-rows.mjs +1 -1
- package/engine/scripts/invoice_lip_runner.py +1 -0
- package/engine/scripts/invoice_runner.py +3 -1
- package/engine/scripts/lib/bootcheck-wiring.mjs +7 -5
- package/engine/scripts/lib/intel-card.mjs +43 -0
- package/engine/scripts/lib/invoice_names.py +23 -0
- package/engine/scripts/lib/ml-ads-core.mjs +100 -18
- package/engine/scripts/lib/ml-ads-rules.mjs +275 -0
- package/engine/scripts/lib/ml-bridge-auth.mjs +50 -0
- package/engine/scripts/lib/ml-category-core.mjs +120 -0
- package/engine/scripts/lib/ml-insight-core.mjs +621 -0
- package/engine/scripts/lib/ml-insight-facts.mjs +424 -0
- package/engine/scripts/lib/ml-items.mjs +40 -0
- package/engine/scripts/lib/ml-listing-core.mjs +342 -0
- package/engine/scripts/lib/ml-market-core.mjs +774 -0
- package/engine/scripts/lib/webdriver_ipc.py +61 -1
- package/engine/scripts/line_pack.py +196 -0
- package/engine/scripts/ml-ads-advice.mjs +140 -0
- package/engine/scripts/ml-ads.mjs +40 -0
- package/engine/scripts/ml-category-baseline.mjs +174 -0
- package/engine/scripts/ml-insight-diagnose.mjs +247 -0
- package/engine/scripts/ml-insight-run.sh +183 -0
- package/engine/scripts/ml-insight-timers.sh +224 -0
- package/engine/scripts/ml-listing-audit.mjs +170 -0
- package/engine/scripts/ml-market-matrix.mjs +84 -0
- package/engine/scripts/ml-market-snapshot.mjs +261 -0
- package/engine/scripts/ml-messages.mjs +145 -0
- package/engine/scripts/npm-publish-argent.mjs +14 -0
- package/engine/scripts/ops-codefix-pr.mjs +87 -0
- package/engine/scripts/ops-codefix-queue.mjs +30 -0
- package/engine/scripts/ops-digest.mjs +98 -0
- package/engine/scripts/ops-verify.mjs +67 -0
- package/engine/scripts/orchestrator.py +410 -20
- package/engine/scripts/orchestrator_br.py +146 -4
- package/engine/scripts/plugin-bootcheck.mjs +50 -1
- package/engine/scripts/publish-engine.mjs +111 -0
- package/engine/scripts/restart-dsh-with-tunnel.sh +129 -0
- package/engine/scripts/skuflow_invoice_runner.py +24 -3
- package/engine/scripts/vertical-lint.mjs +12 -1
- package/engine/scripts/wenyao_fill_template.py +52 -15
- package/engine/scripts/wenyao_run.py +2 -1
- package/engine/skills/ml-appointment-safety/SKILL.md +42 -0
- package/engine/skills/ml-full-appointment/SKILL.md +23 -0
- package/engine/skills/ml-invoice/SKILL.md +2 -2
- package/engine/skills/ml-invoice/references/template-fill-contract.md +1 -1
- package/engine/skills/ml-label-recovery/SKILL.md +43 -0
- package/engine/skills/ml-listing-audit/SKILL.md +66 -0
- package/engine/skills/ml-store-daily-report/scripts/generate.js +35 -0
- package/engine/skills/ml-store-insight/SKILL.md +81 -0
- package/engine/version.mjs +1 -1
- package/engine/verticals/README.md +7 -0
- package/engine/verticals/_engine-words.baseline.txt +27 -59
- package/engine/verticals/mercadolibre/manifest.json +132 -6
- package/package.json +1 -1
|
@@ -1,57 +1,335 @@
|
|
|
1
1
|
#!/usr/bin/env python3
|
|
2
2
|
"""FULL 抢预约 worker 的浏览器执行器(参数全部来自 AppointmentTask,不读 lip)。
|
|
3
3
|
|
|
4
|
-
-
|
|
5
|
-
|
|
4
|
+
2026-11-16 FULL 预约循环改造(黑五不放号 ⇒ 长期值守)。把原来的「3 次重试失败就抛、
|
|
5
|
+
周期循环 maxCycles 到点就退」拆成**显式状态机 + 滚动游标**:
|
|
6
|
+
|
|
7
|
+
PREPARING ──页面就绪──────────────→ SCANNING
|
|
8
|
+
PREPARING ──A 态:无配送方式选项───→ NO_DELIVERY_OPTION ─┐
|
|
9
|
+
PREPARING ──页面/导航异常──────────→ PAGE_ERROR ─────────┤
|
|
10
|
+
SCANNING ──B 态:6 个月扫完全灰───→ CALENDAR_ALL_DISABLED ┤→ 刷新该 tab 的页面
|
|
11
|
+
SCANNING ──发现可选日─────────────→ BOOKING │ (page.reload,⛔ 不新开 tab)
|
|
12
|
+
BOOKING ──成功──────────────────→ BOOKED(结束) │ 等待 20–40s 随机抖动(防风控)
|
|
13
|
+
BOOKING ──不可选/无时段/提交失败─→ BOOKING_FAILED ──────┘ 游标重置到今天 → 回到 PREPARING
|
|
14
|
+
|
|
15
|
+
· A 态(`Vehículo` 下拉无选项 / 直接提示不可预约)与 B 态(日历能渲染、日期全灰)各自的
|
|
16
|
+
下一步写在 `STATE_NEXT_STEP` 里,由 `_refresh_and_wait()` 这一个出口执行。
|
|
17
|
+
· `BOOKING_FAILED` 的下一步不是立刻刷新:先把该日标记为「本窗口已尝试」,在同一窗口继续
|
|
18
|
+
下一候选/下一月;**窗口耗尽**才刷新+重置游标(见 `_window_exhausted()`)。
|
|
19
|
+
· 日期扫描 = **滚动游标**(`ScanCursor`):记住上次扫到哪个月,同一窗口内不从头重扫;
|
|
20
|
+
刷新后游标重置到今天所在月(刷新后平台可能出现新的可选日)。
|
|
21
|
+
· 盲扫上限 = 从今天所在月起最多 `MAX_SCAN_MONTHS`(=6) 个自然月(含当月,即最多翻 5 次月);
|
|
22
|
+
到上限仍无可选 ⇒ 刷新。range 模式的上界 = 运营给定的 `dateTo`(显式目标不受盲扫上限约束)。
|
|
23
|
+
· 循环**不设最大轮数**:唯一终止 = 抢到 / 运营停止(ERP `stopRequestedAt` → worker SIGTERM
|
|
24
|
+
→ `main()` 里的 KeyboardInterrupt 收尾)。
|
|
25
|
+
· ⛔ 循环里**不新开标签页**(每店 5 tab 并发,预约步骤长期占用 1 个 tab);刷新 = 当前页 reload。
|
|
26
|
+
· range / available_days 两种模式语义保留;range 每轮只打开一次日历(2026-10-21 修复,别改回去)。
|
|
27
|
+
· JSONL 事件形状不变:`{'event':'cycle'|'progress','cycle':n,'checks':n,'dateStates':{...}}`
|
|
28
|
+
(cycle 事件另带既有可选键 `summary`;状态迁移细节走 `_log`/stderr,不往事件里加新键)。
|
|
29
|
+
· dateStates 取值沿用旧口径:disabled / selectable / selectable_no_slot /
|
|
30
|
+
selectable_booking_failed / date_not_found / pending / booked。
|
|
31
|
+
|
|
32
|
+
- 日期范围严格使用任务 dateFrom/dateTo(range 模式只点运营给的日期,⛔ 不跳日出范围);
|
|
6
33
|
- 预约成功即停,不执行 FULL 步骤 5-8;
|
|
7
34
|
- 由 appointment-worker.mjs 启动;stdout 最后一行 JSON 为结果。
|
|
8
35
|
"""
|
|
9
36
|
import argparse
|
|
10
37
|
import asyncio
|
|
11
|
-
import time
|
|
12
38
|
import json
|
|
13
|
-
import urllib.request
|
|
14
39
|
import os
|
|
40
|
+
import random
|
|
41
|
+
import re
|
|
15
42
|
import signal
|
|
16
43
|
import sys
|
|
44
|
+
import urllib.request
|
|
45
|
+
from dataclasses import dataclass, field
|
|
17
46
|
from datetime import date, datetime, timedelta, timezone
|
|
18
47
|
from pathlib import Path
|
|
19
48
|
from types import SimpleNamespace
|
|
49
|
+
from typing import Any, Awaitable, Callable, Optional
|
|
20
50
|
|
|
21
51
|
ROOT = Path(__file__).resolve().parent
|
|
22
52
|
sys.path.insert(0, str(ROOT))
|
|
23
53
|
|
|
24
54
|
import orchestrator as O # noqa: E402
|
|
55
|
+
from appointment_rules import compile_rule as compile_rule_dates # noqa: E402
|
|
25
56
|
|
|
26
57
|
|
|
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
|
-
|
|
58
|
+
# ══════════════════════════════════════════════════════════════════════════════
|
|
59
|
+
# 显式状态机(把原来的"等号"拆开:每个状态只有一个明确的下一步)
|
|
60
|
+
# ══════════════════════════════════════════════════════════════════════════════
|
|
61
|
+
STATE_PREPARING = 'preparing'
|
|
62
|
+
STATE_SCANNING = 'scanning'
|
|
63
|
+
STATE_BOOKING = 'booking'
|
|
64
|
+
# A 态:配送方式下拉无选项 / 平台直接提示不可预约
|
|
65
|
+
STATE_NO_DELIVERY_OPTION = 'no_delivery_option'
|
|
66
|
+
# B 态:日历能渲染,但 6 个月窗口内日期全灰
|
|
67
|
+
STATE_CALENDAR_ALL_DISABLED = 'calendar_all_disabled'
|
|
68
|
+
# 有可选日,但点日/选时段/提交没成功
|
|
69
|
+
STATE_BOOKING_FAILED = 'booking_failed'
|
|
70
|
+
# 页面/翻月/日历读取异常(刷新自愈)
|
|
71
|
+
STATE_PAGE_ERROR = 'page_error'
|
|
72
|
+
# 终态
|
|
73
|
+
STATE_BOOKED = 'booked'
|
|
74
|
+
STATE_EXISTING = 'existing'
|
|
75
|
+
# 平台把 appointment-v2 重定向到 /details(货件已处理完成/无需预约)⇒ 终态失败,别空转
|
|
76
|
+
STATE_NOT_APPLICABLE = 'not_applicable'
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
# ── 改约(2026-11-17):把页面上「已有预约」的日期/时段解析出来,与任务窗口比对 ──
|
|
80
|
+
# 平台是西语界面:日期形如 "18 de noviembre de 2026" / "18/11/2026" / "nov 18",
|
|
81
|
+
# 时段形如 "09:30" / "9:30 a. m."。只做保守解析:解析不出就返回空,交给人工判断(不猜)。
|
|
82
|
+
ES_MONTHS = {
|
|
83
|
+
'enero': 1, 'febrero': 2, 'marzo': 3, 'abril': 4, 'mayo': 5, 'junio': 6,
|
|
84
|
+
'julio': 7, 'agosto': 8, 'septiembre': 9, 'setiembre': 9, 'octubre': 10,
|
|
85
|
+
'noviembre': 11, 'diciembre': 12,
|
|
86
|
+
'ene': 1, 'feb': 2, 'mar': 3, 'abr': 4, 'may': 5, 'jun': 6,
|
|
87
|
+
'jul': 7, 'ago': 8, 'sep': 9, 'sept': 9, 'oct': 10, 'nov': 11, 'dic': 12,
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def parse_existing_appointment(text: str) -> dict:
|
|
92
|
+
"""从「已有预约」卡片文本里解析日期与时段。
|
|
93
|
+
|
|
94
|
+
返回 {'date': 'YYYY-MM-DD'|'', 'slot': 'HH:MM'|''};解析不出即空串。
|
|
95
|
+
"""
|
|
96
|
+
out = {'date': '', 'slot': ''}
|
|
97
|
+
t = str(text or '')
|
|
98
|
+
if not t:
|
|
99
|
+
return out
|
|
100
|
+
low = t.lower()
|
|
101
|
+
# ① 18 de noviembre de 2026 / 18 noviembre 2026
|
|
102
|
+
m = re.search(r'(\d{1,2})\s+de?\s*([a-záéíóú]+)\.?\s*(?:de\s*)?(\d{4})', low)
|
|
103
|
+
if m:
|
|
104
|
+
day = int(m.group(1))
|
|
105
|
+
mon = ES_MONTHS.get(m.group(2).strip('.'))
|
|
106
|
+
year = int(m.group(3))
|
|
107
|
+
if mon and 1 <= day <= 31:
|
|
108
|
+
try:
|
|
109
|
+
out['date'] = date(year, mon, day).isoformat()
|
|
110
|
+
except ValueError:
|
|
111
|
+
pass
|
|
112
|
+
# ② 18/11/2026 或 2026-11-18
|
|
113
|
+
if not out['date']:
|
|
114
|
+
m = re.search(r'(\d{1,2})/(\d{1,2})/(\d{4})', t)
|
|
115
|
+
if m:
|
|
116
|
+
try:
|
|
117
|
+
out['date'] = date(int(m.group(3)), int(m.group(2)), int(m.group(1))).isoformat()
|
|
118
|
+
except ValueError:
|
|
119
|
+
pass
|
|
120
|
+
if not out['date']:
|
|
121
|
+
m = re.search(r'(\d{4})-(\d{2})-(\d{2})', t)
|
|
122
|
+
if m:
|
|
123
|
+
try:
|
|
124
|
+
out['date'] = date(int(m.group(1)), int(m.group(2)), int(m.group(3))).isoformat()
|
|
125
|
+
except ValueError:
|
|
126
|
+
pass
|
|
127
|
+
# ③ 时段 09:30 / 9:30 a. m.
|
|
128
|
+
m = re.search(r'(\d{1,2}):(\d{2})\s*(a\.?\s*m\.?|p\.?\s*m\.?)?', low)
|
|
129
|
+
if m:
|
|
130
|
+
hour = int(m.group(1))
|
|
131
|
+
minute = int(m.group(2))
|
|
132
|
+
ampm = (m.group(3) or '').replace('.', '').replace(' ', '')
|
|
133
|
+
if ampm.startswith('p') and hour < 12:
|
|
134
|
+
hour += 12
|
|
135
|
+
if ampm.startswith('a') and hour == 12:
|
|
136
|
+
hour = 0
|
|
137
|
+
if 0 <= hour <= 23 and 0 <= minute <= 59:
|
|
138
|
+
out['slot'] = f'{hour:02d}:{minute:02d}'
|
|
139
|
+
return out
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def window_matches(date_iso: str, slot: str, task: dict) -> bool:
|
|
143
|
+
"""已有预约是否已满足任务窗口(日期在范围/星期内、时段在时间窗内)。缺信息 ⇒ 不认定满足。"""
|
|
144
|
+
if not date_iso:
|
|
145
|
+
return False
|
|
146
|
+
try:
|
|
147
|
+
d = date.fromisoformat(date_iso)
|
|
148
|
+
except ValueError:
|
|
149
|
+
return False
|
|
150
|
+
mode = str(task.get('dateMode') or 'range')
|
|
151
|
+
if mode == 'available_days':
|
|
152
|
+
days = int(task.get('availableDays') or 0)
|
|
153
|
+
if days <= 0:
|
|
154
|
+
return False
|
|
155
|
+
if d < date.today() or d > date.today() + timedelta(days=days):
|
|
156
|
+
return False
|
|
157
|
+
else:
|
|
158
|
+
try:
|
|
159
|
+
lo = date.fromisoformat(str(task.get('dateFrom') or '')[:10])
|
|
160
|
+
hi = date.fromisoformat(str(task.get('dateTo') or '')[:10])
|
|
161
|
+
except ValueError:
|
|
162
|
+
return False
|
|
163
|
+
if not (lo <= d <= hi):
|
|
164
|
+
return False
|
|
165
|
+
weekdays = [int(x) for x in (task.get('weekdays') or []) if str(x).isdigit()]
|
|
166
|
+
if weekdays and (d.isoweekday() not in weekdays):
|
|
167
|
+
return False
|
|
168
|
+
tf = str(task.get('timeFrom') or '')
|
|
169
|
+
tt = str(task.get('timeTo') or '')
|
|
170
|
+
if slot and tf and tt:
|
|
171
|
+
def mins(hhmm):
|
|
172
|
+
try:
|
|
173
|
+
h, m = hhmm.split(':')[:2]
|
|
174
|
+
return int(h) * 60 + int(m)
|
|
175
|
+
except Exception:
|
|
176
|
+
return None
|
|
177
|
+
cur, lo_t, hi_t = mins(slot), mins(tf), mins(tt)
|
|
178
|
+
if cur is not None and lo_t is not None and hi_t is not None and not (lo_t <= cur <= hi_t):
|
|
179
|
+
return False
|
|
180
|
+
return True
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
# 每个异常态的**唯一下一步**(实现见 `AppointmentLoop._refresh_and_wait` / `_try_candidates`)
|
|
184
|
+
STATE_NEXT_STEP = {
|
|
185
|
+
STATE_NO_DELIVERY_OPTION:
|
|
186
|
+
'刷新该 tab 的页面(page.reload)→ 等 20–40s 抖动 → 游标重置到今天 → 重新准备页面(继续等平台放号)',
|
|
187
|
+
STATE_CALENDAR_ALL_DISABLED:
|
|
188
|
+
'刷新该 tab 的页面(page.reload)→ 等 20–40s 抖动 → 游标重置到今天 → 从今天重扫(刷新后可能有新可选日)',
|
|
189
|
+
STATE_BOOKING_FAILED:
|
|
190
|
+
'该日标记为「本窗口已尝试」→ 同窗口继续下一候选/下一月;窗口耗尽才刷新+重置游标',
|
|
191
|
+
STATE_PAGE_ERROR:
|
|
192
|
+
'刷新该 tab 的页面(page.reload)→ 等 20–40s 抖动 → 游标重置到今天 → 重新准备页面',
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
# 盲扫窗口:从今天所在月起最多看 6 个自然月(含当月,即最多翻 5 次月)。
|
|
196
|
+
MAX_SCAN_MONTHS = 6
|
|
197
|
+
# 未知内部异常(不是平台形态类)连续这么多次 ⇒ 判失败收手,避免 bug 把 tab 焊死。
|
|
198
|
+
# ⚠️ 平台形态类(A/B 三态 + page_error)**不计入**该上限,它们是无限值守的一部分。
|
|
199
|
+
MAX_UNEXPECTED_ERRORS = 5
|
|
53
200
|
|
|
201
|
+
MONTHS_ES = ['enero', 'febrero', 'marzo', 'abril', 'mayo', 'junio', 'julio',
|
|
202
|
+
'agosto', 'septiembre', 'octubre', 'noviembre', 'diciembre']
|
|
54
203
|
|
|
204
|
+
# 预约失败文案 → dateStates 口径(沿用旧实现的 marker 判定,⛔ 不再改口径)
|
|
205
|
+
_DISABLED_MARKERS = ('不可选', '目标日期')
|
|
206
|
+
_NO_SLOT_MARKERS = ('可用时段不足', '未渲染出可选时段', '时间选择失败', '未写入日期时间',
|
|
207
|
+
'指定时间范围内无可预约时段')
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
class PageError(RuntimeError):
|
|
211
|
+
"""页面/日历读取或翻月异常(可刷新自愈)。"""
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
class PrepareError(RuntimeError):
|
|
215
|
+
"""预约页准备失败,带机器可判状态:no_delivery_option / page_error / existing。"""
|
|
216
|
+
|
|
217
|
+
def __init__(self, state: str, message: str):
|
|
218
|
+
super().__init__(message)
|
|
219
|
+
self.state = state
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
class BookingError(RuntimeError):
|
|
223
|
+
"""单日预约失败;kind ∈ {disabled, selectable_no_slot, selectable_booking_failed}。"""
|
|
224
|
+
|
|
225
|
+
def __init__(self, kind: str, message: str):
|
|
226
|
+
super().__init__(message)
|
|
227
|
+
self.kind = kind
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
# `_try_candidates` 的哨兵:本轮已刷新(页面刚重开、未准备好)⇒ 本轮到此结束
|
|
231
|
+
_PASS_ENDED = object()
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def classify_booking_error(message: str) -> str:
|
|
235
|
+
"""预约失败文案 → dateStates 口径(旧实现的 marker 判定,集中一处)。"""
|
|
236
|
+
msg = str(message or '')
|
|
237
|
+
if any(k in msg for k in _DISABLED_MARKERS):
|
|
238
|
+
return 'disabled'
|
|
239
|
+
if any(k in msg for k in _NO_SLOT_MARKERS):
|
|
240
|
+
return 'selectable_no_slot'
|
|
241
|
+
return 'selectable_booking_failed'
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def month_index(year: int, month: int) -> int:
|
|
245
|
+
return int(year) * 12 + (int(month) - 1)
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
def month_from_index(idx: int) -> tuple[int, int]:
|
|
249
|
+
return idx // 12, idx % 12 + 1
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def parse_header_month(header: str) -> Optional[tuple[int, int]]:
|
|
253
|
+
"""日历 header(如 `octubre 2026` / `oct 2026`)→ (year, month);读不出返回 None。"""
|
|
254
|
+
h = str(header or '').lower()
|
|
255
|
+
ym = re.search(r'(\d{4})', h)
|
|
256
|
+
if not ym:
|
|
257
|
+
return None
|
|
258
|
+
hits = [i for i, m in enumerate(MONTHS_ES) if m in h]
|
|
259
|
+
if not hits:
|
|
260
|
+
return None
|
|
261
|
+
return int(ym.group(1)), hits[0] + 1
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
# ══════════════════════════════════════════════════════════════════════════════
|
|
265
|
+
# 可注入的节奏("刷新节奏 20–40 秒随机抖动";测试传 0 + 立即返回的 sleep)
|
|
266
|
+
# ══════════════════════════════════════════════════════════════════════════════
|
|
267
|
+
@dataclass
|
|
268
|
+
class Pacing:
|
|
269
|
+
"""值守节奏。`sleep` 也一并注入,测试用 0 延迟即可把整条状态机跑成同步。"""
|
|
270
|
+
|
|
271
|
+
refresh_min_sec: float = 20.0
|
|
272
|
+
refresh_max_sec: float = 40.0
|
|
273
|
+
scan_pause_sec: float = 0.8
|
|
274
|
+
prepare_attempts: int = 3
|
|
275
|
+
prepare_retry_sec: float = 3.0
|
|
276
|
+
sleep: Callable[[float], Awaitable[None]] = asyncio.sleep
|
|
277
|
+
rng: random.Random = field(default_factory=random.Random)
|
|
278
|
+
|
|
279
|
+
def refresh_delay(self) -> float:
|
|
280
|
+
lo, hi = float(self.refresh_min_sec), float(self.refresh_max_sec)
|
|
281
|
+
if hi < lo:
|
|
282
|
+
lo, hi = hi, lo
|
|
283
|
+
return self.rng.uniform(lo, hi) if hi > lo else lo
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
@dataclass
|
|
287
|
+
class ScanCursor:
|
|
288
|
+
"""滚动游标:记住「上次扫到哪个月」。
|
|
289
|
+
|
|
290
|
+
`start_idx` = 本窗口起点(游标重置时的今天所在月);`idx` = 当前应扫的月。
|
|
291
|
+
`flips` = 本窗口已翻月次数(用于 6 个月盲扫上限判定)。
|
|
292
|
+
刷新页面后由 `reset(today)` 重置到今天所在月 —— 这是"刷新后从今天重来"的唯一实现点。
|
|
293
|
+
"""
|
|
294
|
+
|
|
295
|
+
start_idx: int
|
|
296
|
+
idx: int
|
|
297
|
+
|
|
298
|
+
@classmethod
|
|
299
|
+
def at(cls, today: date) -> 'ScanCursor':
|
|
300
|
+
i = month_index(today.year, today.month)
|
|
301
|
+
return cls(i, i)
|
|
302
|
+
|
|
303
|
+
def reset(self, today: date) -> None:
|
|
304
|
+
i = month_index(today.year, today.month)
|
|
305
|
+
self.start_idx = i
|
|
306
|
+
self.idx = i
|
|
307
|
+
|
|
308
|
+
def sync(self, idx: int) -> None:
|
|
309
|
+
"""视图实际停的月比游标更靠后时前移游标(⛔ 不回退,避免重复扫已扫月)。"""
|
|
310
|
+
if idx > self.idx:
|
|
311
|
+
self.idx = idx
|
|
312
|
+
|
|
313
|
+
def advance(self) -> None:
|
|
314
|
+
self.idx += 1
|
|
315
|
+
|
|
316
|
+
@property
|
|
317
|
+
def flips(self) -> int:
|
|
318
|
+
return max(0, self.idx - self.start_idx)
|
|
319
|
+
|
|
320
|
+
@property
|
|
321
|
+
def year_month(self) -> tuple[int, int]:
|
|
322
|
+
return month_from_index(self.idx)
|
|
323
|
+
|
|
324
|
+
def as_dict(self) -> dict:
|
|
325
|
+
y, m = self.year_month
|
|
326
|
+
sy, sm = month_from_index(self.start_idx)
|
|
327
|
+
return {'month': f'{y:04d}-{m:02d}', 'windowStart': f'{sy:04d}-{sm:02d}', 'flips': self.flips}
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
# ══════════════════════════════════════════════════════════════════════════════
|
|
331
|
+
# 页面脚本(沿用原实现;DATE_CELL_JS 已删 —— 逐日状态改由 SCAN_DAYS_JS 一次读全月)
|
|
332
|
+
# ══════════════════════════════════════════════════════════════════════════════
|
|
55
333
|
SCAN_DAYS_JS = r"""() => {
|
|
56
334
|
const days = [...document.querySelectorAll('div.day')];
|
|
57
335
|
const MONTHS = ['enero','febrero','marzo','abril','mayo','junio','julio','agosto','septiembre','octubre','noviembre','diciembre'];
|
|
@@ -79,11 +357,19 @@ SCAN_DAYS_JS = r"""() => {
|
|
|
79
357
|
}"""
|
|
80
358
|
|
|
81
359
|
|
|
360
|
+
_CLI_PACING = {'refresh_min': None, 'refresh_max': None}
|
|
361
|
+
|
|
362
|
+
|
|
82
363
|
def load_task() -> dict:
|
|
83
364
|
ap = argparse.ArgumentParser()
|
|
84
365
|
ap.add_argument('--task-json', required=True)
|
|
85
366
|
ap.add_argument('--cdp-hint', default='')
|
|
367
|
+
# 2026-11-18:刷新节奏可由 worker 从 ERP 实时下发(运营自调),默认沿用 Pacing 的 20–40s
|
|
368
|
+
ap.add_argument('--refresh-min', type=float, default=None)
|
|
369
|
+
ap.add_argument('--refresh-max', type=float, default=None)
|
|
86
370
|
args = ap.parse_args()
|
|
371
|
+
_CLI_PACING['refresh_min'] = args.refresh_min
|
|
372
|
+
_CLI_PACING['refresh_max'] = args.refresh_max
|
|
87
373
|
return json.loads(args.task_json)
|
|
88
374
|
|
|
89
375
|
|
|
@@ -96,80 +382,167 @@ def iso_day(d) -> date:
|
|
|
96
382
|
return dt.astimezone(timezone(timedelta(hours=8))).date()
|
|
97
383
|
|
|
98
384
|
|
|
99
|
-
|
|
100
|
-
|
|
385
|
+
# ══════════════════════════════════════════════════════════════════════════════
|
|
386
|
+
# 预约页准备(真实页面动作;失败一律翻译成带状态的 PrepareError)
|
|
387
|
+
# ══════════════════════════════════════════════════════════════════════════════
|
|
388
|
+
async def prepare_appointment_page(orch, *, attempts: int = 3, retry_delay: float = 3.0,
|
|
389
|
+
sleep: Optional[Callable[[float], Awaitable[None]]] = None) -> None:
|
|
390
|
+
"""进入预约页并选好运输方式/地址,打开日期日历;页面慢/弹窗允许重试。
|
|
101
391
|
|
|
102
|
-
|
|
103
|
-
·
|
|
104
|
-
·
|
|
105
|
-
·
|
|
392
|
+
⛔ 不再用裸 RuntimeError:失败必须带状态,状态机才知道下一步(A 态要刷新继续等)。
|
|
393
|
+
· 下拉打不开 / 下拉里没有 `Vehículo` 选项 / 平台直接提示不可预约 ⇒ `no_delivery_option`
|
|
394
|
+
· 其它页面/超时/导航异常 ⇒ `page_error`
|
|
395
|
+
· 页面显示已有预约(`Cancelar reserva`) ⇒ `existing`(调用方按"不重复抢"处理)
|
|
106
396
|
"""
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
397
|
+
sleep = sleep or asyncio.sleep
|
|
398
|
+
attempts = max(1, int(attempts))
|
|
399
|
+
|
|
400
|
+
async def _guard_url(_stage: str) -> None:
|
|
401
|
+
"""交互后检查 URL:被跳到卖家菜单/登录页等 ⇒ 立刻判 page_error(附阶段与 URL)。"""
|
|
402
|
+
try:
|
|
403
|
+
_u = str(orch.browser.page.url or "")
|
|
404
|
+
except Exception:
|
|
405
|
+
return
|
|
406
|
+
marks = ('personas-interesadas', 'seller-menu', 'ato-complaint', '/login', 'identification')
|
|
407
|
+
if _u and any(mk in _u for mk in marks):
|
|
408
|
+
raise PrepareError(STATE_PAGE_ERROR,
|
|
409
|
+
f'[{_stage}] 后页面被跳转到 {_u[:120]}')
|
|
410
|
+
|
|
411
|
+
async def _dismiss_blockers(_page) -> None:
|
|
412
|
+
"""关掉会拦截点击的 cookie 横幅/浮层(2026-11-18:实测点击超时多为覆盖层拦截)。"""
|
|
413
|
+
for name in ('Aceptar cookies', 'Aceptar todo', 'Aceptar', 'Entendido', 'Continuar sin aceptar'):
|
|
112
414
|
try:
|
|
113
|
-
|
|
415
|
+
btn = _page.get_by_role('button', name=name, exact=False).first
|
|
416
|
+
if await btn.count() and await btn.is_visible():
|
|
417
|
+
await btn.click(timeout=2500)
|
|
418
|
+
await sleep(0.3)
|
|
419
|
+
return
|
|
114
420
|
except Exception:
|
|
115
421
|
continue
|
|
116
|
-
for page in pages:
|
|
117
|
-
try:
|
|
118
|
-
if page.is_closed():
|
|
119
|
-
continue
|
|
120
|
-
url = str(getattr(page, 'url', '') or '')
|
|
121
|
-
is_appt = ('appointment-v2' in url) or (
|
|
122
|
-
'appointment' in url and shipment_id and shipment_id in url
|
|
123
|
-
)
|
|
124
|
-
if not is_appt:
|
|
125
|
-
continue
|
|
126
|
-
if len(ctx.pages) <= 1:
|
|
127
|
-
try:
|
|
128
|
-
await ctx.new_page() # 占位,保持窗口不退出
|
|
129
|
-
except Exception:
|
|
130
|
-
return closed
|
|
131
|
-
await page.close()
|
|
132
|
-
closed += 1
|
|
133
|
-
orch._log(f' 🗂️ 已关闭抢预约任务标签页({url[:100]})')
|
|
134
|
-
except Exception as e:
|
|
135
|
-
try: orch._log(f' ⚠️ 关闭预约标签页失败:{str(e)[:120]}')
|
|
136
|
-
except Exception: pass
|
|
137
|
-
if not closed:
|
|
138
|
-
try: orch._log(' ⚠️ 停止时未找到待关闭的预约标签页(可能已被用户关闭)')
|
|
139
|
-
except Exception: pass
|
|
140
|
-
except Exception as e:
|
|
141
|
-
try: orch._log(f' ⚠️ 关闭预约标签页异常:{str(e)[:120]}')
|
|
142
|
-
except Exception: pass
|
|
143
|
-
return closed
|
|
144
422
|
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
setattr(orch, '_appt_page_checks', n)
|
|
149
|
-
return n
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
async def prepare_appointment_page(orch) -> None:
|
|
153
|
-
"""进入预约页并选好运输方式/地址,打开日期日历;页面慢/弹窗允许重试。"""
|
|
154
|
-
last = None
|
|
155
|
-
for attempt in range(3):
|
|
423
|
+
last_state = STATE_NO_DELIVERY_OPTION
|
|
424
|
+
last_msg = ''
|
|
425
|
+
for attempt in range(attempts):
|
|
156
426
|
try:
|
|
157
427
|
_bump_page_check(orch)
|
|
428
|
+
# 2026-11-18:先清掉同货件的残留标签页(多任务/重定向会留重复 tab,越积越多)
|
|
429
|
+
try:
|
|
430
|
+
await orch.browser.close_shipment_tabs(str(orch.state.shipment_id or ''))
|
|
431
|
+
# ⛔ 不在这里清「噪音标签」:同店多个任务共用窗口时,另一个正在跑的任务的 tab
|
|
432
|
+
# 可能刚好被平台跳到 personas-interesadas,清掉它等于把人家正在用的页面关掉
|
|
433
|
+
# (实测 2026-11-18:2店 2 条任务只剩 1 个 tab)。噪音标签由 URL 守卫自愈 + 人工清理。
|
|
434
|
+
except Exception:
|
|
435
|
+
pass
|
|
158
436
|
await orch.browser.visit_plan_page('appointment-v2', orch.state.shipment_id, step=4)
|
|
437
|
+
# 2026-11-18:有的货件平台不提供预约页,直接跳到 /details(如「Procesamiento finalizado」
|
|
438
|
+
# 的旧货件)⇒ 判「无需预约」终态;继续循环只会占着槽位空转(实测 74670907 卡了一天)。
|
|
439
|
+
try:
|
|
440
|
+
_page = orch.browser.page
|
|
441
|
+
_url = str(getattr(_page, 'url', '') or '')
|
|
442
|
+
_title = await _page.title()
|
|
443
|
+
except Exception:
|
|
444
|
+
_url, _title = '', ''
|
|
445
|
+
# 2026-11-18:预约页被平台/浏览器跳到别的页面(卖家菜单、登录页等)时,
|
|
446
|
+
# 之前会继续按"页面形态异常"空刷;这里明确识别并给出可读原因,交给刷新重试。
|
|
447
|
+
_redirect_marks = ('personas-interesadas', 'seller-menu', '/login', 'identification', 'ato-complaint')
|
|
448
|
+
if _url and any(_mk in _url for _mk in _redirect_marks):
|
|
449
|
+
raise PrepareError(STATE_PAGE_ERROR,
|
|
450
|
+
f'预约页被跳转到其他页面({_url[:120]})⇒ 按登录态/误导航处理,刷新重试')
|
|
451
|
+
if '/details' in _url or 'Detalle del envío' in str(_title or ''):
|
|
452
|
+
raise PrepareError(STATE_NOT_APPLICABLE,
|
|
453
|
+
f'平台把预约页重定向到货件详情页(该货件无需预约/已处理完成):{_url[:120]}')
|
|
454
|
+
await _guard_url('打开预约页')
|
|
455
|
+
# 2026-11-18:平台错误页/无号提示页上**不要点任何元素**——实测点击会触发页面跳转到
|
|
456
|
+
# 卖家菜单 personas-interesadas(导航历史:typed appointment → link personas 交替)。
|
|
457
|
+
_err_text = ''
|
|
458
|
+
try:
|
|
459
|
+
_err_text = await orch.browser.page.evaluate(
|
|
460
|
+
"() => ((document.title || '') + ' ' + ((document.body && document.body.innerText) || '').slice(0, 600))")
|
|
461
|
+
except Exception:
|
|
462
|
+
_err_text = ''
|
|
463
|
+
_err_marks = ('Algo salió mal', 'Tenemos más tráfico', 'No contamos con citas',
|
|
464
|
+
'vuelve a intentarlo en los próximos días')
|
|
465
|
+
if _err_text and any(_mk in str(_err_text) for _mk in _err_marks):
|
|
466
|
+
# 2026-11-19 用户实测:页面标题/顶部仍显示平台错误,但**预约表单实际已出现**
|
|
467
|
+
# (配送方式可选、日历可选)。旧逻辑只看错误文案就刷新 ⇒ 把可操作表单刷掉。
|
|
468
|
+
# ⇒ 表单存在时一律继续走预约步骤;只有"错误页且没有任何表单元素"才刷新。
|
|
469
|
+
_form_present = False
|
|
470
|
+
try:
|
|
471
|
+
_form_present = bool(await orch.browser.page.evaluate(
|
|
472
|
+
"""() => !!(document.querySelector('#shipment-type-selection-dropdown-id-trigger')
|
|
473
|
+
|| document.querySelector('input[readonly]')
|
|
474
|
+
|| document.querySelectorAll('div.day').length
|
|
475
|
+
|| document.querySelectorAll('div.hour').length
|
|
476
|
+
|| document.querySelectorAll('.andes-card').length)"""))
|
|
477
|
+
except Exception:
|
|
478
|
+
_form_present = False
|
|
479
|
+
if not _form_present:
|
|
480
|
+
raise PrepareError(STATE_NO_DELIVERY_OPTION,
|
|
481
|
+
f'平台错误页/无号提示(不交互,直接刷新等待):{str(_err_text)[:100]}')
|
|
482
|
+
_safe_log(orch, ' ℹ️ 平台顶部提示错误但预约表单已出现 ⇒ 继续走预约步骤(不刷新)')
|
|
483
|
+
try:
|
|
484
|
+
await _dismiss_blockers(orch.browser.page)
|
|
485
|
+
except PrepareError:
|
|
486
|
+
raise
|
|
487
|
+
except Exception:
|
|
488
|
+
pass
|
|
489
|
+
await _guard_url('关闭 cookie 横幅')
|
|
159
490
|
if await orch._has_existing_appointment():
|
|
160
|
-
|
|
491
|
+
# 2026-11-17 改约:把页面上的已有预约日期/时段解析出来,供 intent=reschedule 判断
|
|
492
|
+
text = ''
|
|
493
|
+
try:
|
|
494
|
+
text = await orch._existing_appointment_text()
|
|
495
|
+
except Exception:
|
|
496
|
+
text = ''
|
|
497
|
+
info = parse_existing_appointment(text)
|
|
498
|
+
info['text'] = str(text or '')[:400]
|
|
499
|
+
setattr(orch, '_appt_existing_info', info)
|
|
500
|
+
raise PrepareError(STATE_EXISTING,
|
|
501
|
+
'已有预约存在(页面显示 Cancelar reserva)')
|
|
161
502
|
page = orch.browser.page
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
503
|
+
try:
|
|
504
|
+
trigger = page.locator('#shipment-type-selection-dropdown-id-trigger')
|
|
505
|
+
await trigger.wait_for(state='visible', timeout=30000)
|
|
506
|
+
except Exception as exc:
|
|
507
|
+
# A 态:配送方式下拉压根没渲染出来(平台直接提示不可预约 / 表单未出)
|
|
508
|
+
raise PrepareError(STATE_NO_DELIVERY_OPTION,
|
|
509
|
+
f'配送方式下拉不可见(平台未放配送方式/页面不可预约):{str(exc)[:120]}') from exc
|
|
510
|
+
try:
|
|
511
|
+
await trigger.click(timeout=8000)
|
|
512
|
+
await _guard_url('点击配送方式下拉')
|
|
513
|
+
except PrepareError:
|
|
514
|
+
raise
|
|
515
|
+
except Exception as exc:
|
|
516
|
+
# 2026-11-18:页面可选但点击被 cookie 横幅/浮层拦截 ⇒ 关掉遮蔽物再试,最后 JS click 兜底
|
|
517
|
+
await _dismiss_blockers(orch.browser.page)
|
|
518
|
+
try:
|
|
519
|
+
await trigger.click(timeout=8000)
|
|
520
|
+
except Exception:
|
|
521
|
+
try:
|
|
522
|
+
await trigger.evaluate("el => el.click()")
|
|
523
|
+
except Exception:
|
|
524
|
+
raise PrepareError(STATE_NO_DELIVERY_OPTION,
|
|
525
|
+
f'配送方式下拉点击失败:{str(exc)[:120]}') from exc
|
|
526
|
+
await sleep(0.8)
|
|
166
527
|
option = page.get_by_role('option', name='Vehículo particular', exact=False).first
|
|
167
|
-
|
|
528
|
+
n_opt = await option.count()
|
|
529
|
+
if n_opt == 0:
|
|
168
530
|
option = page.get_by_role('option', name='Vehículo', exact=False).first
|
|
169
|
-
|
|
170
|
-
|
|
531
|
+
n_opt = await option.count()
|
|
532
|
+
if n_opt == 0:
|
|
533
|
+
# 兜底:部分版本下拉项不是 role=option(实测黑五改版),用文本定位
|
|
534
|
+
for sel in ('li:has-text("Vehículo particular")', 'li:has-text("Vehículo")',
|
|
535
|
+
'.andes-list__item:has-text("Vehículo")', '[role="listitem"]:has-text("Vehículo")'):
|
|
536
|
+
option = page.locator(sel).first
|
|
537
|
+
n_opt = await option.count()
|
|
538
|
+
if n_opt:
|
|
539
|
+
break
|
|
540
|
+
if n_opt == 0:
|
|
541
|
+
raise PrepareError(STATE_NO_DELIVERY_OPTION,
|
|
542
|
+
'配送方式下拉无 Vehículo 选项(平台未放配送方式)')
|
|
171
543
|
await option.click()
|
|
172
|
-
await
|
|
544
|
+
await _guard_url('选择 Vehículo')
|
|
545
|
+
await sleep(1.2)
|
|
173
546
|
try:
|
|
174
547
|
await orch.browser.page.wait_for_selector('.andes-list__item-action', timeout=8000)
|
|
175
548
|
btns = orch.browser.page.locator('.andes-list__item-action')
|
|
@@ -177,92 +550,755 @@ async def prepare_appointment_page(orch) -> None:
|
|
|
177
550
|
for i in range(await btns.count()):
|
|
178
551
|
txt = (await btns.nth(i).text_content() or '')
|
|
179
552
|
if 'MXCD05' in txt:
|
|
180
|
-
target = (btns.nth(i), txt)
|
|
553
|
+
target = (btns.nth(i), txt)
|
|
554
|
+
break
|
|
181
555
|
if target is None:
|
|
182
556
|
raise RuntimeError('未找到指定仓库 MXCD05')
|
|
183
557
|
await target[0].scroll_into_view_if_needed(timeout=5000)
|
|
184
|
-
await
|
|
558
|
+
await sleep(0.4)
|
|
185
559
|
await target[0].click()
|
|
186
560
|
try:
|
|
187
561
|
cont = orch.browser.page.locator('button', has_text='Continuar').first
|
|
188
562
|
await cont.click(force=True, timeout=5000)
|
|
189
563
|
except Exception:
|
|
190
564
|
pass
|
|
191
|
-
await
|
|
565
|
+
await sleep(1)
|
|
192
566
|
except Exception:
|
|
193
567
|
pass
|
|
194
568
|
await orch.browser.wait_for_selector('input[readonly]', timeout=15, step=4, action='date_input')
|
|
195
569
|
await orch.browser.click_selector_with_fallback(4, 'date_input')
|
|
196
|
-
await
|
|
570
|
+
await sleep(1)
|
|
197
571
|
return
|
|
572
|
+
except PrepareError as exc:
|
|
573
|
+
if exc.state == STATE_EXISTING:
|
|
574
|
+
raise
|
|
575
|
+
last_state, last_msg = exc.state, str(exc)
|
|
576
|
+
_safe_log(orch, f' ⚠️ 预约页准备第 {attempt + 1}/{attempts} 次失败({last_state}): {last_msg[:140]}')
|
|
577
|
+
except Exception as exc: # noqa: BLE001 —— 任何页面异常都不许把循环打死
|
|
578
|
+
last_state, last_msg = STATE_PAGE_ERROR, f'{type(exc).__name__}: {str(exc)[:140]}'
|
|
579
|
+
_safe_log(orch, f' ⚠️ 预约页准备第 {attempt + 1}/{attempts} 次失败(page_error): {last_msg[:140]}')
|
|
580
|
+
if attempt < attempts - 1:
|
|
581
|
+
await sleep(retry_delay)
|
|
582
|
+
# 2026-11-19 用户口径:预约页进不去时,先看 hub 的预约卡片再决定(⛔ 不要因为预约页报错就判失败)
|
|
583
|
+
if last_state in (STATE_NO_DELIVERY_OPTION, STATE_PAGE_ERROR):
|
|
584
|
+
try:
|
|
585
|
+
hub = await self.driver.probe_hub_appointment()
|
|
586
|
+
if hub.get('exists'):
|
|
587
|
+
_safe_log(orch, f' 📋 hub 显示已有预约:{hub.get("date") or "?"} {hub.get("slot") or ""}(预约页报错,改由 hub 判定)')
|
|
588
|
+
setattr(orch, '_appt_existing_info', {k: hub.get(k, '') for k in ('date', 'slot', 'text')})
|
|
589
|
+
return STATE_EXISTING
|
|
590
|
+
except Exception:
|
|
591
|
+
pass
|
|
592
|
+
raise PrepareError(last_state, f'预约页准备失败({attempts} 次,最后状态={last_state}):{last_msg}')
|
|
593
|
+
|
|
594
|
+
|
|
595
|
+
def _safe_log(orch, msg: str) -> None:
|
|
596
|
+
try:
|
|
597
|
+
orch._log(msg)
|
|
598
|
+
except Exception:
|
|
599
|
+
pass
|
|
600
|
+
|
|
601
|
+
|
|
602
|
+
def _bump_page_check(orch) -> int:
|
|
603
|
+
n = int(getattr(orch, '_appt_page_checks', 0)) + 1
|
|
604
|
+
setattr(orch, '_appt_page_checks', n)
|
|
605
|
+
return n
|
|
606
|
+
|
|
607
|
+
|
|
608
|
+
# ══════════════════════════════════════════════════════════════════════════════
|
|
609
|
+
# 页面驱动:状态机只认这组原语(测试用假 driver 顶替,零真实店铺)
|
|
610
|
+
# ══════════════════════════════════════════════════════════════════════════════
|
|
611
|
+
class OrchestratorDriver:
|
|
612
|
+
"""把 orchestrator 的页面动作收敛成状态机需要的几个原语。
|
|
613
|
+
|
|
614
|
+
· `prepare_page`:进预约页/选运输方式/开日历(失败抛 PrepareError 带状态)
|
|
615
|
+
· `reload_page`:**刷新当前 tab**(page.reload,⛔ 不新开标签页)
|
|
616
|
+
· `today` / `checks`:时钟与"页面检查次数"
|
|
617
|
+
· `calendar_state` / `scan_view` / `align_month`:日历状态、整月逐日状态、翻到指定月
|
|
618
|
+
· `book_day`:提交某天(range=严格目标日;available_days=今天+N 天偏移语义)
|
|
619
|
+
"""
|
|
620
|
+
|
|
621
|
+
def __init__(self, orch, *, pacing: Optional[Pacing] = None):
|
|
622
|
+
self.orch = orch
|
|
623
|
+
self.pacing = pacing or Pacing()
|
|
624
|
+
|
|
625
|
+
# ---- 日志 / 计数 ----
|
|
626
|
+
def log(self, msg: str) -> None:
|
|
627
|
+
_safe_log(self.orch, msg)
|
|
628
|
+
|
|
629
|
+
def checks(self) -> int:
|
|
630
|
+
return int(getattr(self.orch, '_appt_page_checks', 0))
|
|
631
|
+
|
|
632
|
+
async def today(self) -> date:
|
|
633
|
+
try:
|
|
634
|
+
return (await self.orch._platform_today()).date()
|
|
635
|
+
except Exception:
|
|
636
|
+
return datetime.now().date()
|
|
637
|
+
|
|
638
|
+
# ---- 页面生命周期 ----
|
|
639
|
+
async def prepare_page(self) -> None:
|
|
640
|
+
await prepare_appointment_page(self.orch,
|
|
641
|
+
attempts=self.pacing.prepare_attempts,
|
|
642
|
+
retry_delay=self.pacing.prepare_retry_sec,
|
|
643
|
+
sleep=self.pacing.sleep)
|
|
644
|
+
|
|
645
|
+
async def probe_hub_appointment(self) -> dict:
|
|
646
|
+
"""从 **hub 页**判断是否已有预约(2026-11-19 用户口径)。
|
|
647
|
+
|
|
648
|
+
背景:预约页(appointment-v2)在平台繁忙/改版时大概率进不去(Algo salió mal /
|
|
649
|
+
Tenemos más tráfico),拿它判断"是否已预约"会失败;而 hub 页能看到预约卡片。
|
|
650
|
+
做法:导航到 `…/inbounds/<shipment>/hub-v2`,dump 文本,识别 Cancelar reserva /
|
|
651
|
+
Reserva de cita / Cita programada 等卡片;返回 {exists, date, slot, text}。
|
|
652
|
+
⚠️ 只读(navigate + innerText),不点任何写按钮。
|
|
653
|
+
"""
|
|
654
|
+
try:
|
|
655
|
+
sid = str(getattr(getattr(self.orch, 'state', None), 'shipment_id', '') or '')
|
|
656
|
+
if not sid:
|
|
657
|
+
return {'exists': False}
|
|
658
|
+
base = str(getattr(O, 'ML_BASE_URL', 'https://vendedores.mercadolibre.com.mx') or 'https://vendedores.mercadolibre.com.mx').rstrip('/')
|
|
659
|
+
url = f'{base}/shipping/inbounds/{sid}/hub-v2'
|
|
660
|
+
page = self.orch.browser.page
|
|
661
|
+
await page.goto(url, wait_until='domcontentloaded', timeout=60000)
|
|
662
|
+
await asyncio.sleep(3.0)
|
|
663
|
+
text = str(await page.evaluate('() => (document.body ? document.body.innerText : "")') or '')
|
|
664
|
+
if not text:
|
|
665
|
+
return {'exists': False, 'url': url}
|
|
666
|
+
exists = bool(re.search(r'Cancelar reserva|Reserva de cita|Cita programada|Cita confirmada|ya (tienes|tiene) una (cita|reserva)', text, re.I))
|
|
667
|
+
info = {'exists': exists, 'url': url, 'text': text[:600]}
|
|
668
|
+
if exists:
|
|
669
|
+
parsed = parse_existing_appointment(text)
|
|
670
|
+
info.update({'date': parsed.get('date', ''), 'slot': parsed.get('slot', '')})
|
|
671
|
+
return info
|
|
672
|
+
except Exception as exc:
|
|
673
|
+
return {'exists': False, 'error': f'{type(exc).__name__}: {str(exc)[:120]}'}
|
|
674
|
+
|
|
675
|
+
async def calendar_has_choices(self) -> bool:
|
|
676
|
+
"""页面当前是否有可选日 / 可选时段可见(即使还没被选中)。刷新前复核用。"""
|
|
677
|
+
try:
|
|
678
|
+
return bool(await self.orch.browser.page.evaluate("""() => {
|
|
679
|
+
const days = [...document.querySelectorAll('div.day')];
|
|
680
|
+
for (const d of days) {
|
|
681
|
+
const cls = String(d.className || '');
|
|
682
|
+
const dis = d.getAttribute('aria-disabled');
|
|
683
|
+
if (dis === 'true' || /disabled/i.test(cls)) continue;
|
|
684
|
+
if (/^\\d+$/.test((d.textContent || '').trim())) return true;
|
|
685
|
+
}
|
|
686
|
+
if ([...document.querySelectorAll('div.hour')].length > 0) return true;
|
|
687
|
+
const cards = document.querySelectorAll('.andes-card');
|
|
688
|
+
for (const c of cards) { if (/Confirmar/i.test(c.innerText || '')) return true; }
|
|
689
|
+
return false;
|
|
690
|
+
}"""))
|
|
691
|
+
except Exception:
|
|
692
|
+
return False
|
|
693
|
+
|
|
694
|
+
async def has_selection_or_existing(self) -> bool:
|
|
695
|
+
"""页面是否处于「人工/自动选择进行中」或「已有预约」状态(⛔ 此时禁止刷新)。
|
|
696
|
+
|
|
697
|
+
2026-11-19 用户实测:日历已出现、时间已选中,但状态机下一轮判成"无号"就 reload,
|
|
698
|
+
把还没点确认的选择整个刷掉(浪费一次放号)。判据(任一):
|
|
699
|
+
· 有 Cancelar reserva 按钮(已有预约)
|
|
700
|
+
· 只读日期输入框已写入具体日期/时间(如 "20 de noviembre, 9:45 hs")
|
|
701
|
+
· 日历有选中日(div.day 带 selected/active)或时段带 selected/active
|
|
702
|
+
"""
|
|
703
|
+
try:
|
|
704
|
+
return bool(await self.orch.browser.page.evaluate("""() => {
|
|
705
|
+
if ([...document.querySelectorAll('button')].some(b => /Cancelar reserva/i.test(b.innerText || ''))) return true;
|
|
706
|
+
const inputs = [...document.querySelectorAll('input[readonly]')];
|
|
707
|
+
if (inputs.some(i => \\d{1,2}\\s+de\\s+[a-záéíóú]+.*\\d{1,2}[::]\\d{2}/i.test(String(i.value || '')))) return true;
|
|
708
|
+
if (document.querySelector('div.day.selected, div.day--selected, .day.selected, .focus-ui-datepicker__day--selected')) return true;
|
|
709
|
+
const hours = [...document.querySelectorAll('div.hour')].filter(h => /selected|active/i.test(String(h.className || '')));
|
|
710
|
+
if (hours.length) return true;
|
|
711
|
+
return false;
|
|
712
|
+
}"""))
|
|
713
|
+
except Exception:
|
|
714
|
+
return False
|
|
715
|
+
|
|
716
|
+
async def reload_page(self) -> None:
|
|
717
|
+
"""刷新当前 tab(同一标签页 reload;⛔ 不 new_page —— 每店 5 tab 并发,不能占更多)。"""
|
|
718
|
+
page = self.orch.browser.page
|
|
719
|
+
await page.reload(wait_until='domcontentloaded', timeout=30000)
|
|
720
|
+
await self.pacing.sleep(1.0)
|
|
721
|
+
|
|
722
|
+
# ---- 日历读取 ----
|
|
723
|
+
async def calendar_state(self) -> dict:
|
|
724
|
+
st = await self.orch._calendar_state()
|
|
725
|
+
return st if isinstance(st, dict) else {}
|
|
726
|
+
|
|
727
|
+
async def scan_view(self) -> dict:
|
|
728
|
+
raw = await self.orch.browser.page.evaluate(SCAN_DAYS_JS)
|
|
729
|
+
return raw if isinstance(raw, dict) else json.loads(raw)
|
|
730
|
+
|
|
731
|
+
async def align_month(self, year: int, month: int) -> None:
|
|
732
|
+
"""把日历停到 `year-month`(`_flip_month` 的 fiber 直达优先;失败抛 PageError)。"""
|
|
733
|
+
last = ''
|
|
734
|
+
for _ in range(3):
|
|
735
|
+
st = await self.calendar_state()
|
|
736
|
+
header = (st or {}).get('header') or ''
|
|
737
|
+
got = parse_header_month(header)
|
|
738
|
+
if got is None:
|
|
739
|
+
# 日历没打开/还没渲染 ⇒ 不猜月份、更不乱翻月:交状态机刷新自愈
|
|
740
|
+
raise PageError(f'日历未打开或 header 不可解析(header={header!r})')
|
|
741
|
+
if got == (int(year), int(month)):
|
|
742
|
+
return
|
|
743
|
+
try:
|
|
744
|
+
new_st = await self.orch._flip_month(st, int(month) - 1, int(year))
|
|
745
|
+
except Exception as exc:
|
|
746
|
+
raise PageError(f'翻月失败(→ {year}-{month:02d}):{str(exc)[:160]}') from exc
|
|
747
|
+
got = parse_header_month((new_st or {}).get('header') or '')
|
|
748
|
+
if got == (int(year), int(month)):
|
|
749
|
+
return
|
|
750
|
+
last = f'{(new_st or {}).get("header") or "?"}'
|
|
751
|
+
await self.pacing.sleep(0.8)
|
|
752
|
+
raise PageError(f'翻月未到达目标月 {year}-{month:02d}(最后视图={last or "?"})')
|
|
753
|
+
|
|
754
|
+
# ---- 预约 ----
|
|
755
|
+
async def book_day(self, day: date, *, today: date, exact: bool,
|
|
756
|
+
time_from: str = '', time_to: str = '',
|
|
757
|
+
time_ranges: Optional[list[dict]] = None,
|
|
758
|
+
min_lead_hours: float = 0) -> dict:
|
|
759
|
+
"""提交某天;成功返回 {date, slot},失败抛 BookingError(kind 即 dateStates 口径)。"""
|
|
760
|
+
offset = (day - today).days
|
|
761
|
+
try:
|
|
762
|
+
if not exact:
|
|
763
|
+
# available_days 语义(旧行为):每次尝试重新进预约页,再按"今天+N 天"偏移选日
|
|
764
|
+
_bump_page_check(self.orch)
|
|
765
|
+
await self.orch.browser.visit_plan_page('appointment-v2',
|
|
766
|
+
self.orch.state.shipment_id, step=4)
|
|
767
|
+
# 与 FULL 步骤4、其他抢预约任务共用同店预约锁:只串行化"提交预约",不占整个流程
|
|
768
|
+
self.orch._acquire_store_step4_lock(force=True)
|
|
769
|
+
try:
|
|
770
|
+
kwargs: dict[str, Any] = {'hour_idx': 0, 'date_offset': offset,
|
|
771
|
+
'time_from': time_from, 'time_to': time_to,
|
|
772
|
+
'time_ranges': time_ranges, 'min_lead_hours': min_lead_hours}
|
|
773
|
+
if exact:
|
|
774
|
+
# range 模式严格目标日期:只点运营给的日期,⛔ 不允许 _pick_date 跳到范围外
|
|
775
|
+
kwargs['exact_date'] = day.isoformat()
|
|
776
|
+
await self.orch._book_appointment(**kwargs)
|
|
777
|
+
finally:
|
|
778
|
+
self.orch._release_store_step4_lock()
|
|
198
779
|
except Exception as exc:
|
|
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
|
-
|
|
780
|
+
raise BookingError(classify_booking_error(str(exc)), str(exc)) from exc
|
|
781
|
+
actual = str(getattr(self.orch, '_last_booked_date', '') or day.isoformat())
|
|
782
|
+
slot = str(getattr(self.orch, '_last_booked_slot', '') or 'first')
|
|
783
|
+
if exact and actual != day.isoformat():
|
|
784
|
+
raise BookingError('selectable_booking_failed',
|
|
785
|
+
f'严格日期校验失败:目标 {day.isoformat()},实际页面选中 {actual}(不提交)')
|
|
786
|
+
return {'date': actual, 'slot': slot}
|
|
787
|
+
|
|
788
|
+
|
|
789
|
+
# ══════════════════════════════════════════════════════════════════════════════
|
|
790
|
+
# 值守循环(显式状态机 + 滚动游标;循环本身没有最大轮数)
|
|
791
|
+
# ══════════════════════════════════════════════════════════════════════════════
|
|
792
|
+
class AppointmentLoop:
|
|
793
|
+
"""FULL 预约值守循环。
|
|
794
|
+
|
|
795
|
+
· `run()` 的返回值与旧 run_task 的 result 形状兼容(status/date/slot/dateStates/summary)。
|
|
796
|
+
· 唯一正常终止:抢到(booked)。页面显示已有预约 ⇒ 按旧口径返回 failed(不重复抢)。
|
|
797
|
+
· `max_rounds` 仅供测试注入(生产默认 None = 无上限);`Pacing.sleep` 可注入 ⇒ 测试 0 延迟。
|
|
798
|
+
"""
|
|
799
|
+
|
|
800
|
+
def __init__(self, driver, *, date_mode: str = 'range',
|
|
801
|
+
from_date: Optional[date] = None, to_date: Optional[date] = None,
|
|
802
|
+
weekdays: Optional[set[int]] = None,
|
|
803
|
+
time_from: str = '', time_to: str = '',
|
|
804
|
+
rule_spec: Optional[dict] = None,
|
|
805
|
+
rule_min_lead_hours: float = 0,
|
|
806
|
+
available_days: int = 0,
|
|
807
|
+
pacing: Optional[Pacing] = None,
|
|
808
|
+
max_scan_months: int = MAX_SCAN_MONTHS,
|
|
809
|
+
max_rounds: Optional[int] = None,
|
|
810
|
+
task: Optional[dict] = None):
|
|
811
|
+
if date_mode not in ('range', 'available_days', 'rule'):
|
|
812
|
+
raise ValueError(f'未知 dateMode:{date_mode}')
|
|
813
|
+
self.driver = driver
|
|
814
|
+
self.task = dict(task or {})
|
|
815
|
+
self.existing_info: dict = {}
|
|
816
|
+
self.existing_cancelled = False
|
|
817
|
+
self.date_mode = date_mode
|
|
818
|
+
self.from_date = from_date
|
|
819
|
+
self.to_date = to_date
|
|
820
|
+
self.weekdays = frozenset(int(x) for x in (weekdays or ()))
|
|
821
|
+
self.time_from = time_from
|
|
822
|
+
self.time_to = time_to
|
|
823
|
+
self.need = max(1, int(available_days or 0))
|
|
824
|
+
self.rule_spec = rule_spec if isinstance(rule_spec, dict) else None
|
|
825
|
+
self.rule_min_lead_hours = float(rule_min_lead_hours or 0)
|
|
826
|
+
self.rule_windows: dict[str, list[dict]] = {}
|
|
827
|
+
self.pacing = pacing or Pacing()
|
|
828
|
+
self.max_scan_months = max(1, int(max_scan_months))
|
|
829
|
+
self.max_rounds = max_rounds
|
|
830
|
+
|
|
831
|
+
self.today: date = date.today()
|
|
832
|
+
self.cursor: Optional[ScanCursor] = None
|
|
833
|
+
self.targets: list[date] = []
|
|
834
|
+
self._target_set: set[str] = set()
|
|
835
|
+
self._max_target_idx: Optional[int] = None
|
|
836
|
+
|
|
837
|
+
self.state = STATE_PREPARING
|
|
838
|
+
self.round_no = 0
|
|
839
|
+
self.refreshes = 0
|
|
840
|
+
self.date_states: dict[str, str] = {}
|
|
841
|
+
self.saw_selectable = False
|
|
842
|
+
self.tried: set[str] = set()
|
|
843
|
+
self.trace: list[dict] = [] # 状态迁移轨迹(测试/复盘用)
|
|
844
|
+
self.events: list[dict] = [] # 已输出的 JSONL 事件(测试/复盘用)
|
|
845
|
+
self._consecutive_errors = 0
|
|
846
|
+
|
|
847
|
+
# ── 结果/事件 ──────────────────────────────────────────────────────────
|
|
848
|
+
def _result_booked(self, actual: str, slot: str, summary: str = '') -> dict:
|
|
849
|
+
self._transition(STATE_BOOKED, f'{actual} {slot}')
|
|
850
|
+
self._emit_progress()
|
|
851
|
+
return {'status': 'booked', 'date': actual, 'slot': slot,
|
|
852
|
+
'dateStates': dict(self.date_states), 'cycles': self.round_no,
|
|
853
|
+
'refreshes': self.refreshes, 'windowMode': self.date_mode,
|
|
854
|
+
'summary': summary or f'{actual} {slot} 预约成功'}
|
|
855
|
+
|
|
856
|
+
def _result_existing(self) -> dict:
|
|
857
|
+
# 2026-11-19 用户定调:**「已有预约」不是失败**(平台本来就有预约=目标已达成)。
|
|
858
|
+
# 改为成功收口(booked/succeeded),保留平台已有日期/时段;不在窗口时只作提示,不改判失败。
|
|
859
|
+
self._transition(STATE_EXISTING, 'page-shows-existing-appointment')
|
|
860
|
+
info = self.existing_info or {}
|
|
861
|
+
date_iso = str(info.get('date') or '')
|
|
862
|
+
slot = str(info.get('slot') or '')
|
|
863
|
+
when = f'{date_iso} {slot}'.strip() or '平台已有预约(日期/时段未解析)'
|
|
864
|
+
summary = f'平台已有预约:{when}(未重复抢,视为已预约)'
|
|
865
|
+
try:
|
|
866
|
+
if date_iso and not window_matches(date_iso, slot, self.task):
|
|
867
|
+
summary += ';不在本次窗口,如需改约请用改约流程'
|
|
868
|
+
except Exception:
|
|
869
|
+
pass
|
|
870
|
+
return {'status': 'booked', 'date': date_iso, 'slot': slot,
|
|
871
|
+
'dateStates': dict(self.date_states), 'cycles': self.round_no,
|
|
872
|
+
'refreshes': self.refreshes, 'windowMode': self.date_mode,
|
|
873
|
+
'existingDate': date_iso, 'existingSlot': slot, 'summary': summary}
|
|
874
|
+
|
|
875
|
+
async def _handle_existing(self) -> Optional[dict]:
|
|
876
|
+
"""页面出现已有预约时:
|
|
877
|
+
· 日期/时段已满足任务窗口 ⇒ 视为成功(不重复抢)
|
|
878
|
+
· intent=reschedule 且不满足 ⇒ 取消旧预约后继续按新窗口抢(只取消一次)
|
|
879
|
+
· 其它 ⇒ 旧口径收口(failed + existingDate/existingSlot)
|
|
880
|
+
"""
|
|
881
|
+
orch = getattr(self.driver, 'orch', None)
|
|
882
|
+
self.existing_info = dict(getattr(orch, '_appt_existing_info', {}) or {})
|
|
883
|
+
info = self.existing_info
|
|
884
|
+
self.driver.log(f' 📋 页面已有预约:{info.get("date") or "?"} {info.get("slot") or ""}'
|
|
885
|
+
f'(intent={self.task.get("intent") or "grab"})')
|
|
886
|
+
if info.get('date') and window_matches(str(info['date']), str(info.get('slot') or ''), self.task):
|
|
887
|
+
self.driver.log(' ✅ 已有预约已满足任务窗口 ⇒ 不重复抢,直接判定成功')
|
|
888
|
+
return self._result_booked(
|
|
889
|
+
str(info['date']), str(info.get('slot') or ''),
|
|
890
|
+
summary=f'改约确认:平台已有预约 {info["date"]} {info.get("slot") or ""},且满足任务窗口(未重复预约)')
|
|
891
|
+
if str(self.task.get('intent') or '') == 'reschedule' and not self.existing_cancelled:
|
|
892
|
+
if orch is None:
|
|
893
|
+
return self._result_failed('改约失败:无法访问 orchestrator 取消入口')
|
|
894
|
+
self.driver.log(' 🔁 改约:已有预约与窗口不符 ⇒ 先取消旧预约,再按新窗口抢号')
|
|
895
|
+
ok = await orch._safe_cancel_appointment()
|
|
896
|
+
if not ok:
|
|
897
|
+
return self._result_failed('改约失败:取消旧预约未成功,请人工在平台取消后重试')
|
|
898
|
+
self.existing_cancelled = True
|
|
899
|
+
setattr(orch, '_appt_existing_info', {})
|
|
900
|
+
self.driver.log(' ✅ 旧预约已取消,继续值守抢新窗口')
|
|
901
|
+
return None
|
|
902
|
+
return self._result_existing()
|
|
903
|
+
|
|
904
|
+
def _result_failed(self, summary: str) -> dict:
|
|
905
|
+
return {'status': 'failed', 'dateStates': dict(self.date_states), 'cycles': self.round_no,
|
|
906
|
+
'refreshes': self.refreshes, 'windowMode': self.date_mode, 'summary': summary}
|
|
907
|
+
|
|
908
|
+
def _transition(self, state: str, reason: str = '') -> None:
|
|
909
|
+
self.trace.append({'round': self.round_no, 'from': self.state, 'to': state,
|
|
910
|
+
'reason': reason})
|
|
911
|
+
self.driver.log(f' 🔀 {self.state} → {state}({reason or "-"})'
|
|
912
|
+
+ (f'|下一步:{STATE_NEXT_STEP[state]}' if state in STATE_NEXT_STEP else ''))
|
|
913
|
+
self.state = state
|
|
914
|
+
|
|
915
|
+
def _emit(self, event: str, summary: str = '') -> None:
|
|
916
|
+
"""输出事件。**形状保持旧口径**:core 四键 + cycle 的既有可选 summary。"""
|
|
917
|
+
payload = {'event': event, 'cycle': self.round_no, 'checks': self.driver.checks(),
|
|
918
|
+
'dateStates': dict(self.date_states)}
|
|
919
|
+
if summary:
|
|
920
|
+
payload['summary'] = summary
|
|
921
|
+
self.events.append(payload)
|
|
922
|
+
print(json.dumps(payload, ensure_ascii=False), flush=True)
|
|
923
|
+
|
|
924
|
+
def _emit_progress(self) -> None:
|
|
925
|
+
self._emit('progress')
|
|
926
|
+
|
|
927
|
+
def _emit_cycle(self, reason: str = '') -> None:
|
|
928
|
+
self._emit('cycle', f'{self.state}: {reason}' if reason else self.state)
|
|
929
|
+
|
|
930
|
+
# ── 刷新(A/B/page_error 的唯一出口)─────────────────────────────────────
|
|
931
|
+
async def _refresh_and_wait(self, state: str, reason: str) -> bool:
|
|
932
|
+
"""刷新该 tab 的页面 → 抖动等待 → 游标重置到今天 → 回到 PREPARING。
|
|
933
|
+
|
|
934
|
+
返回 True=已刷新;False=因页面处于选择/已预约状态而**暂缓刷新**(2026-11-19 修复):
|
|
935
|
+
⛔ 判断过程中(日历已出现、日期/时间已选中、已有预约)绝不强制 reload,
|
|
936
|
+
否则会把还没走完的预约步骤整个刷掉 == 浪费一次放号。
|
|
937
|
+
"""
|
|
938
|
+
if self.state != state:
|
|
939
|
+
self._transition(state, reason)
|
|
940
|
+
# 刷新前最后一道保险:页面已有选中/已预约 ⇒ 不刷新,稍等后返回让主循环再判断
|
|
941
|
+
try:
|
|
942
|
+
if await self.driver.has_selection_or_existing():
|
|
943
|
+
self.driver.log(' ⏸️ 页面已有选中日期/时间或已有预约 ⇒ 暂不刷新(避免刷掉未完成的预约操作)')
|
|
944
|
+
await self.pacing.sleep(2.0)
|
|
945
|
+
return False
|
|
946
|
+
except Exception:
|
|
947
|
+
pass
|
|
948
|
+
# 2026-11-19 二次修复:日历/时段刚渲染出来的竞态——等 1.2s 再复核一次,
|
|
949
|
+
# 有可选日/可选时段就绝不刷新(交回扫描/提交),避免"刚刷出日历就被刷掉"。
|
|
950
|
+
try:
|
|
951
|
+
await asyncio.sleep(1.2)
|
|
952
|
+
view = await self.driver.scan_view()
|
|
953
|
+
self._absorb_view(view)
|
|
954
|
+
cands = self._candidates(view)
|
|
955
|
+
if cands or await self.driver.calendar_has_choices():
|
|
956
|
+
self.driver.log(' ⏸️ 刷新前复核:日历/时段已出现 ⇒ 不刷新(改为继续提交/判断)')
|
|
957
|
+
return False
|
|
958
|
+
except Exception:
|
|
959
|
+
pass
|
|
960
|
+
self.refreshes += 1
|
|
961
|
+
try:
|
|
962
|
+
await self.driver.reload_page()
|
|
963
|
+
except Exception as exc: # noqa: BLE001 —— 刷新失败也不退出:下一轮 prepare 会重新进页面
|
|
964
|
+
self.driver.log(f' ⚠️ 刷新预约页失败(下一轮重新进入预约页兜底):{str(exc)[:160]}')
|
|
965
|
+
self.today = await self.driver.today()
|
|
966
|
+
self.cursor.reset(self.today) # 刷新后游标重置到今天(可能出现新可选日)
|
|
967
|
+
self.tried.clear() # 新窗口 ⇒ 已尝试日重新可试
|
|
968
|
+
delay = self.pacing.refresh_delay()
|
|
969
|
+
self.driver.log(f' ⏳ 刷新后等待 {delay:.1f}s(20–40s 抖动防风控)→ 游标重置到 '
|
|
970
|
+
f'{self.cursor.as_dict()["windowStart"]},从今天重扫')
|
|
971
|
+
self._emit_cycle(f'{reason}|refreshes={self.refreshes}|wait={delay:.1f}s')
|
|
972
|
+
await self.pacing.sleep(delay)
|
|
973
|
+
return True
|
|
974
|
+
|
|
975
|
+
# ── 日期目标 ───────────────────────────────────────────────────────────
|
|
976
|
+
def _min_lead_days(self) -> int:
|
|
977
|
+
"""最早可预约日 = 今天 + N 天。默认 1;巴西站点平台规则 = 至少 2 天后才可选。
|
|
978
|
+
|
|
979
|
+
env `ARGENT_APPOINTMENT_MIN_DAY` 可覆盖(运维/压测用);否则按店铺名站点判定。
|
|
980
|
+
"""
|
|
981
|
+
raw = str(os.environ.get('ARGENT_APPOINTMENT_MIN_DAY') or '').strip()
|
|
982
|
+
if raw.isdigit():
|
|
983
|
+
return max(1, int(raw))
|
|
984
|
+
store = str((self.task or {}).get('store') or '')
|
|
985
|
+
return 3 if '巴西' in store else 1
|
|
986
|
+
|
|
987
|
+
def _compute_targets(self, today: date) -> list[date]:
|
|
988
|
+
"""range 模式的目标日 = [max(dateFrom, 今天+N) .. dateTo] ∩ 星期过滤(N=站点最小提前量)。"""
|
|
989
|
+
if self.date_mode == 'rule':
|
|
990
|
+
if not self.rule_spec:
|
|
991
|
+
raise ValueError('rule 模式缺少规则配置')
|
|
992
|
+
allowed = compile_rule_dates(self.rule_spec, today)
|
|
993
|
+
self.rule_windows = allowed
|
|
994
|
+
lead = self._min_lead_days()
|
|
995
|
+
cutoff = today + timedelta(days=lead)
|
|
996
|
+
targets = [date.fromisoformat(k) for k in sorted(allowed) if date.fromisoformat(k) >= cutoff]
|
|
997
|
+
self.driver.log(f' 📐 时间规则:今天(墨西哥)={today.isoformat()} · 规则可约 {len(allowed)} 天 · 实际目标 {len(targets)} 天(平台最早=今天+{lead}天)')
|
|
998
|
+
return targets
|
|
999
|
+
if not self.from_date or not self.to_date:
|
|
1000
|
+
raise ValueError('range 模式需要 dateFrom/dateTo')
|
|
1001
|
+
targets: list[date] = []
|
|
1002
|
+
lead = self._min_lead_days()
|
|
1003
|
+
self.driver.log(f' 📅 最早可约日 = 今天+{lead} 天({"巴西站点规则" if lead >= 3 else "默认"})')
|
|
1004
|
+
d = max(self.from_date, today + timedelta(days=lead))
|
|
1005
|
+
while d <= self.to_date:
|
|
1006
|
+
if (not self.weekdays) or d.isoweekday() in self.weekdays:
|
|
1007
|
+
targets.append(d)
|
|
1008
|
+
d += timedelta(days=1)
|
|
1009
|
+
return targets
|
|
1010
|
+
|
|
1011
|
+
def _initial_states(self) -> dict[str, str]:
|
|
1012
|
+
if self.date_mode in ('range', 'rule'):
|
|
1013
|
+
return {d.isoformat(): 'pending' for d in self.targets}
|
|
1014
|
+
return {}
|
|
1015
|
+
|
|
1016
|
+
# ── 主循环 ─────────────────────────────────────────────────────────────
|
|
1017
|
+
async def run(self) -> dict:
|
|
1018
|
+
self.today = await self.driver.today()
|
|
1019
|
+
self.cursor = ScanCursor.at(self.today)
|
|
1020
|
+
self.driver.log(f' 🔁 值守循环启动:mode={self.date_mode}|today={self.today.isoformat()}'
|
|
1021
|
+
f'|盲扫上限={self.max_scan_months}个月|刷新抖动='
|
|
1022
|
+
f'{self.pacing.refresh_min_sec:g}–{self.pacing.refresh_max_sec:g}s'
|
|
1023
|
+
f'|循环无最大轮数(运营 stopRequestedAt 停止)')
|
|
1024
|
+
if self.date_mode in ('range', 'rule'):
|
|
1025
|
+
self.targets = self._compute_targets(self.today)
|
|
1026
|
+
if not self.targets:
|
|
1027
|
+
return self._result_failed('当前时间规则下没有可预约日期(可能已过今日窗口/全部被跳过)')
|
|
1028
|
+
self._target_set = {d.isoformat() for d in self.targets}
|
|
1029
|
+
self._max_target_idx = month_index(self.targets[-1].year, self.targets[-1].month)
|
|
1030
|
+
|
|
1031
|
+
while True:
|
|
1032
|
+
self.round_no += 1
|
|
1033
|
+
if self.date_mode == 'rule':
|
|
1034
|
+
self.today = await self.driver.today()
|
|
1035
|
+
self.targets = self._compute_targets(self.today)
|
|
1036
|
+
self._target_set = {d.isoformat() for d in self.targets}
|
|
1037
|
+
self._max_target_idx = month_index(self.targets[-1].year, self.targets[-1].month) if self.targets else None
|
|
1038
|
+
self.date_states = self._initial_states()
|
|
1039
|
+
if self.date_mode == 'rule' and not self.targets:
|
|
1040
|
+
await self._refresh_and_wait(STATE_CALENDAR_ALL_DISABLED, 'rule-no-targets')
|
|
1041
|
+
continue
|
|
1042
|
+
self.saw_selectable = False
|
|
1043
|
+
try:
|
|
1044
|
+
result = await self._run_round()
|
|
1045
|
+
if result is not None:
|
|
1046
|
+
return result
|
|
1047
|
+
self._consecutive_errors = 0
|
|
1048
|
+
except KeyboardInterrupt:
|
|
1049
|
+
raise # 运营停止(SIGTERM)⇒ 交 main 收尾
|
|
1050
|
+
except PageError as exc:
|
|
1051
|
+
# 平台/页面形态类:刷新继续等(不设上限)
|
|
1052
|
+
await self._refresh_and_wait(STATE_PAGE_ERROR, f'page-error:{str(exc)[:120]}')
|
|
1053
|
+
except Exception as exc: # noqa: BLE001 —— 未知内部异常:有限次后收手,别把 tab 焊死
|
|
1054
|
+
self._consecutive_errors += 1
|
|
1055
|
+
self.driver.log(f' ❌ 值守循环未预期异常({self._consecutive_errors}/'
|
|
1056
|
+
f'{MAX_UNEXPECTED_ERRORS}):{type(exc).__name__}: {str(exc)[:200]}')
|
|
1057
|
+
if self._consecutive_errors >= MAX_UNEXPECTED_ERRORS:
|
|
1058
|
+
return self._result_failed(
|
|
1059
|
+
f'值守循环连续 {self._consecutive_errors} 次未预期异常,已停止以免占死标签页:'
|
|
1060
|
+
f'{type(exc).__name__}: {str(exc)[:200]}')
|
|
1061
|
+
await self._refresh_and_wait(STATE_PAGE_ERROR,
|
|
1062
|
+
f'unexpected:{type(exc).__name__}')
|
|
1063
|
+
if self.max_rounds and self.round_no >= self.max_rounds:
|
|
1064
|
+
return self._result_failed(
|
|
1065
|
+
f'值守循环达到测试上限 max_rounds={self.max_rounds}(生产默认无上限)')
|
|
1066
|
+
|
|
1067
|
+
async def _run_round(self) -> Optional[dict]:
|
|
1068
|
+
"""一轮 = 准备页面 → 滚动扫描/预约,直到抢到或窗口耗尽(耗尽由本函数内刷新)。"""
|
|
1069
|
+
# ── PREPARING ──
|
|
1070
|
+
outcome = await self._prepare_page()
|
|
1071
|
+
if outcome == STATE_EXISTING:
|
|
1072
|
+
return await self._handle_existing()
|
|
1073
|
+
if outcome == STATE_NOT_APPLICABLE:
|
|
1074
|
+
return self._result_failed('该货件无需预约:平台把预约页重定向到货件详情页(可能已处理完成/非 FULL 入仓)')
|
|
1075
|
+
if outcome != 'ready':
|
|
1076
|
+
await self._refresh_and_wait(outcome, 'prepare-failed')
|
|
1077
|
+
return None
|
|
1078
|
+
await self._align_view_to_cursor()
|
|
1079
|
+
self._transition(STATE_SCANNING, 'page-ready')
|
|
1080
|
+
|
|
1081
|
+
# ── SCANNING / BOOKING ──
|
|
1082
|
+
defer_refresh = 0
|
|
1083
|
+
while True:
|
|
1084
|
+
view = await self.driver.scan_view()
|
|
1085
|
+
self._absorb_view(view)
|
|
1086
|
+
self._emit_progress()
|
|
1087
|
+
cands = self._candidates(view)
|
|
1088
|
+
if cands:
|
|
1089
|
+
self.saw_selectable = True
|
|
1090
|
+
self._transition(STATE_BOOKING, f'{len(cands)} 个候选日')
|
|
1091
|
+
result = await self._try_candidates(cands)
|
|
1092
|
+
if result is _PASS_ENDED:
|
|
1093
|
+
return None
|
|
1094
|
+
if result is not None:
|
|
1095
|
+
return result
|
|
1096
|
+
continue # 候选都失败:页面已重开并对齐游标,继续本窗口
|
|
1097
|
+
if self._window_exhausted():
|
|
1098
|
+
# 2026-11-19:页面渲染竞态——扫描瞬间可能日历还没渲染完;刷新前再等两次
|
|
1099
|
+
# (各 1.2s)重扫,出现候选直接进 booking,避免"刚出现日历就被刷新"。
|
|
1100
|
+
late = None
|
|
1101
|
+
for _delay in (1.2, 1.2):
|
|
1102
|
+
await asyncio.sleep(_delay)
|
|
1103
|
+
try:
|
|
1104
|
+
late_view = await self.driver.scan_view()
|
|
1105
|
+
except Exception:
|
|
1106
|
+
late_view = None
|
|
1107
|
+
if not late_view:
|
|
1108
|
+
continue
|
|
1109
|
+
self._absorb_view(late_view)
|
|
1110
|
+
late = self._candidates(late_view)
|
|
1111
|
+
if late:
|
|
1112
|
+
break
|
|
1113
|
+
if late:
|
|
1114
|
+
self.saw_selectable = True
|
|
1115
|
+
self._transition(STATE_BOOKING, f'{len(late)} 个候选日(窗口耗尽前复核,不刷新)')
|
|
1116
|
+
result = await self._try_candidates(late)
|
|
1117
|
+
if result is _PASS_ENDED:
|
|
1118
|
+
return None
|
|
1119
|
+
if result is not None:
|
|
1120
|
+
return result
|
|
1121
|
+
continue
|
|
1122
|
+
# B 态:整窗口没有可选日;否则=有可选日但都点/提交失败
|
|
1123
|
+
terminal = (STATE_BOOKING_FAILED if self.saw_selectable
|
|
1124
|
+
else STATE_CALENDAR_ALL_DISABLED)
|
|
1125
|
+
reloaded = await self._refresh_and_wait(terminal, 'window-exhausted')
|
|
1126
|
+
if not reloaded:
|
|
1127
|
+
defer_refresh += 1
|
|
1128
|
+
if defer_refresh >= 3:
|
|
1129
|
+
# 连续暂缓 ⇒ 结束本 round(下一 round 重新检测;⛔ 绝不在这种状态下 reload)
|
|
1130
|
+
return None
|
|
1131
|
+
await self.pacing.sleep(1.0)
|
|
1132
|
+
continue # 页面有选中/已预约:不刷新,继续扫描判断(等操作走完)
|
|
1133
|
+
return None
|
|
1134
|
+
if not await self._advance_month():
|
|
1135
|
+
await self._refresh_and_wait(STATE_PAGE_ERROR, 'flip-failed')
|
|
1136
|
+
return None
|
|
1137
|
+
await self.pacing.sleep(self.pacing.scan_pause_sec)
|
|
1138
|
+
|
|
1139
|
+
async def _prepare_page(self) -> str:
|
|
1140
|
+
"""PREPARING:返回 'ready' / STATE_EXISTING / 失败态(no_delivery_option/page_error)。"""
|
|
1141
|
+
self._transition(STATE_PREPARING, 'round-start')
|
|
1142
|
+
try:
|
|
1143
|
+
await self.driver.prepare_page()
|
|
1144
|
+
return 'ready'
|
|
1145
|
+
except PrepareError as exc:
|
|
1146
|
+
if exc.state == STATE_EXISTING:
|
|
1147
|
+
return STATE_EXISTING
|
|
1148
|
+
state = exc.state if exc.state in (STATE_NO_DELIVERY_OPTION, STATE_PAGE_ERROR) \
|
|
1149
|
+
else STATE_PAGE_ERROR
|
|
1150
|
+
self._transition(state, f'prepare-failed:{str(exc)[:120]}')
|
|
1151
|
+
return state
|
|
1152
|
+
except Exception as exc: # noqa: BLE001
|
|
1153
|
+
self._transition(STATE_PAGE_ERROR, f'prepare-error:{type(exc).__name__}')
|
|
1154
|
+
self.driver.log(f' ⚠️ 预约页准备异常:{type(exc).__name__}: {str(exc)[:160]}')
|
|
1155
|
+
return STATE_PAGE_ERROR
|
|
1156
|
+
|
|
1157
|
+
def _parse_view_month(self, view: dict) -> tuple[int, int]:
|
|
1158
|
+
got = parse_header_month((view or {}).get('header') or '')
|
|
1159
|
+
if not got:
|
|
1160
|
+
raise PageError(f'日历 header 不可解析(header={(view or {}).get("header")!r})')
|
|
1161
|
+
return got
|
|
1162
|
+
|
|
1163
|
+
async def _align_view_to_cursor(self) -> None:
|
|
1164
|
+
"""重开页面后日历可能停在平台默认月:先按实际视图前移游标,再翻到游标月。"""
|
|
1165
|
+
st = await self.driver.calendar_state()
|
|
1166
|
+
actual = parse_header_month((st or {}).get('header') or '')
|
|
1167
|
+
if actual:
|
|
1168
|
+
self.cursor.sync(month_index(*actual))
|
|
1169
|
+
y, m = self.cursor.year_month
|
|
1170
|
+
await self.driver.align_month(y, m)
|
|
1171
|
+
|
|
1172
|
+
def _absorb_view(self, view: dict) -> None:
|
|
1173
|
+
"""把当前视图的逐日状态吸收进 dateStates(并校验日历确实渲染了)。"""
|
|
1174
|
+
view_year, view_month = self._parse_view_month(view)
|
|
1175
|
+
dates = (view or {}).get('dates') or []
|
|
1176
|
+
if not dates:
|
|
1177
|
+
raise PageError('日历能打开但读不到任何 day 格(视图未渲染)')
|
|
1178
|
+
self.cursor.sync(month_index(view_year, view_month))
|
|
1179
|
+
tomorrow = (self.today + timedelta(days=1)).isoformat()
|
|
1180
|
+
if self.date_mode == 'available_days':
|
|
1181
|
+
for item in dates:
|
|
1182
|
+
iso = item.get('date')
|
|
1183
|
+
if not iso or iso < tomorrow:
|
|
1184
|
+
continue
|
|
1185
|
+
if iso in self.tried:
|
|
1186
|
+
continue # 已失败的日期保留失败口径(不被重扫的旧视图覆盖)
|
|
1187
|
+
self.date_states[iso] = 'disabled' if item.get('disabled') else 'selectable'
|
|
1188
|
+
return
|
|
1189
|
+
# range:只维护运营给定目标日(形状与旧实现一致),其余日期不进 dateStates
|
|
1190
|
+
seen: dict[str, bool] = {}
|
|
1191
|
+
for item in dates:
|
|
1192
|
+
iso = item.get('date')
|
|
1193
|
+
if iso:
|
|
1194
|
+
seen[iso] = bool(item.get('disabled'))
|
|
1195
|
+
for iso, label in list(self.date_states.items()):
|
|
1196
|
+
if label not in ('pending',):
|
|
236
1197
|
continue
|
|
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
|
-
|
|
1198
|
+
try:
|
|
1199
|
+
td = date.fromisoformat(iso)
|
|
1200
|
+
except ValueError:
|
|
1201
|
+
continue
|
|
1202
|
+
if (td.year, td.month) != (view_year, view_month):
|
|
1203
|
+
continue
|
|
1204
|
+
if iso not in seen:
|
|
1205
|
+
self.date_states[iso] = 'date_not_found'
|
|
1206
|
+
elif seen[iso]:
|
|
1207
|
+
self.date_states[iso] = 'disabled'
|
|
1208
|
+
|
|
1209
|
+
def _candidates(self, view: dict) -> list[date]:
|
|
1210
|
+
"""当前视图里可以立刻尝试预约的日期(range 只认目标日;available_days 认可选日)。"""
|
|
1211
|
+
tomorrow = (self.today + timedelta(days=1)).isoformat()
|
|
1212
|
+
out: list[date] = []
|
|
1213
|
+
for item in (view or {}).get('dates') or []:
|
|
1214
|
+
iso = item.get('date')
|
|
1215
|
+
if not iso or item.get('disabled'):
|
|
1216
|
+
continue
|
|
1217
|
+
if iso < tomorrow or iso in self.tried:
|
|
1218
|
+
continue
|
|
1219
|
+
if self.date_mode in ('range', 'rule') and iso not in self._target_set:
|
|
1220
|
+
continue
|
|
1221
|
+
try:
|
|
1222
|
+
d = date.fromisoformat(iso)
|
|
1223
|
+
except ValueError:
|
|
1224
|
+
continue
|
|
1225
|
+
if self.date_mode == 'available_days' and self.weekdays \
|
|
1226
|
+
and d.isoweekday() not in self.weekdays:
|
|
1227
|
+
continue
|
|
1228
|
+
out.append(d)
|
|
1229
|
+
out.sort()
|
|
1230
|
+
if self.date_mode == 'available_days':
|
|
1231
|
+
out = out[:self.need]
|
|
1232
|
+
return out
|
|
264
1233
|
|
|
1234
|
+
def _window_exhausted(self) -> bool:
|
|
1235
|
+
"""本窗口扫完了吗?available_days = 6 个月盲扫上限;range = 最远目标月。"""
|
|
1236
|
+
if self.date_mode == 'range':
|
|
1237
|
+
return self._max_target_idx is not None and self.cursor.idx >= self._max_target_idx
|
|
1238
|
+
return self.cursor.flips >= (self.max_scan_months - 1)
|
|
265
1239
|
|
|
1240
|
+
async def _advance_month(self) -> bool:
|
|
1241
|
+
"""向后翻一个月(滚动游标只前进);失败返回 False(调用方按 page_error 刷新)。"""
|
|
1242
|
+
y, m = self.cursor.year_month
|
|
1243
|
+
ny, nm = (y + 1, 1) if m >= 12 else (y, m + 1)
|
|
1244
|
+
try:
|
|
1245
|
+
await self.driver.align_month(ny, nm)
|
|
1246
|
+
except Exception as exc: # noqa: BLE001
|
|
1247
|
+
self.driver.log(f' ⚠️ 翻月失败(→ {ny}-{nm:02d}):{str(exc)[:160]}')
|
|
1248
|
+
return False
|
|
1249
|
+
self.cursor.advance()
|
|
1250
|
+
return True
|
|
1251
|
+
|
|
1252
|
+
async def _try_candidates(self, cands: list[date]) -> Any:
|
|
1253
|
+
"""按序尝试候选日。
|
|
1254
|
+
|
|
1255
|
+
· 成功 ⇒ 返回 booked 结果 dict;
|
|
1256
|
+
· 全部失败但页面仍就绪 ⇒ 返回 None(本轮继续扫本窗口);
|
|
1257
|
+
· 页面准备失败并已刷新(本轮不能再扫)⇒ 返回 `_PASS_ENDED`。
|
|
1258
|
+
"""
|
|
1259
|
+
exact = self.date_mode in ('range', 'rule')
|
|
1260
|
+
for day in cands:
|
|
1261
|
+
self._emit_progress()
|
|
1262
|
+
try:
|
|
1263
|
+
booked = await self.driver.book_day(day, today=self.today, exact=exact,
|
|
1264
|
+
time_from=self.time_from, time_to=self.time_to,
|
|
1265
|
+
time_ranges=self.rule_windows.get(day.isoformat()) if self.date_mode == 'rule' else None,
|
|
1266
|
+
min_lead_hours=self.rule_min_lead_hours if self.date_mode == 'rule' else 0)
|
|
1267
|
+
except BookingError as exc:
|
|
1268
|
+
kind, msg = exc.kind, str(exc)
|
|
1269
|
+
except Exception as exc: # noqa: BLE001 —— 任何失败都按 dateStates 口径归类
|
|
1270
|
+
kind, msg = classify_booking_error(str(exc)), str(exc)
|
|
1271
|
+
else:
|
|
1272
|
+
actual = str(booked.get('date') or day.isoformat())
|
|
1273
|
+
slot = str(booked.get('slot') or 'first')
|
|
1274
|
+
self.date_states[actual] = 'booked'
|
|
1275
|
+
return self._result_booked(actual, slot)
|
|
1276
|
+
|
|
1277
|
+
self.date_states[day.isoformat()] = kind
|
|
1278
|
+
self.tried.add(day.isoformat())
|
|
1279
|
+
self._transition(STATE_BOOKING_FAILED, f'{day.isoformat()}:{kind}')
|
|
1280
|
+
self.driver.log(f' ⚠️ {day.isoformat()} 预约失败({kind}):{msg[:160]}')
|
|
1281
|
+
self._emit_progress()
|
|
1282
|
+
# 预约尝试会改动页面状态 ⇒ 重开页面(旧 range 实现同样 prepared=False 重开),
|
|
1283
|
+
# 失败则本轮结束、由状态机走刷新;成功则继续本窗口剩余候选。
|
|
1284
|
+
outcome = await self._prepare_page()
|
|
1285
|
+
if outcome == STATE_EXISTING:
|
|
1286
|
+
return await self._handle_existing()
|
|
1287
|
+
if outcome != 'ready':
|
|
1288
|
+
await self._refresh_and_wait(outcome, 'prepare-after-booking-failed')
|
|
1289
|
+
return _PASS_ENDED
|
|
1290
|
+
try:
|
|
1291
|
+
await self._align_view_to_cursor()
|
|
1292
|
+
except PageError as exc:
|
|
1293
|
+
await self._refresh_and_wait(STATE_PAGE_ERROR, f'align-failed:{str(exc)[:120]}')
|
|
1294
|
+
return _PASS_ENDED
|
|
1295
|
+
self._transition(STATE_SCANNING, 'page-ready')
|
|
1296
|
+
return None
|
|
1297
|
+
|
|
1298
|
+
|
|
1299
|
+
# ══════════════════════════════════════════════════════════════════════════════
|
|
1300
|
+
# run_task:任务校验/浏览器装配/锁 —— 值守循环本体在 AppointmentLoop
|
|
1301
|
+
# ══════════════════════════════════════════════════════════════════════════════
|
|
266
1302
|
async def run_task(task: dict) -> dict:
|
|
267
1303
|
store = task.get('store') or ''
|
|
268
1304
|
if not store:
|
|
@@ -279,12 +1315,14 @@ async def run_task(task: dict) -> dict:
|
|
|
279
1315
|
if not is_mx:
|
|
280
1316
|
return {'status': 'failed', 'summary': f'抢预约当前仅支持墨西哥站(MLM);{store} 属于 {platform},暂未适配,请勿执行'}
|
|
281
1317
|
date_mode = task.get('dateMode') or 'range'
|
|
1318
|
+
rule_snapshot = task.get('ruleSnapshot') if isinstance(task.get('ruleSnapshot'), dict) else None
|
|
1319
|
+
rule_spec = (rule_snapshot or {}).get('spec') if rule_snapshot else None
|
|
1320
|
+
if rule_spec:
|
|
1321
|
+
date_mode = 'rule'
|
|
282
1322
|
weekdays = {int(x) for x in (task.get('weekdays') or []) if str(x).isdigit() and 1 <= int(x) <= 7}
|
|
283
1323
|
time_from = str(task.get('timeFrom') or '').strip()
|
|
284
1324
|
time_to = str(task.get('timeTo') or '').strip()
|
|
285
1325
|
|
|
286
|
-
def weekday_allowed(d: date) -> bool:
|
|
287
|
-
return (not weekdays) or d.isoweekday() in weekdays
|
|
288
1326
|
from_date = iso_day(task['dateFrom']) if date_mode == 'range' else None
|
|
289
1327
|
to_date = iso_day(task['dateTo']) if date_mode == 'range' else None
|
|
290
1328
|
cfg = O.load_config()
|
|
@@ -302,13 +1340,42 @@ async def run_task(task: dict) -> dict:
|
|
|
302
1340
|
orch.state.box = str(task.get('boxCount') or '')
|
|
303
1341
|
if task.get('shipmentNo'):
|
|
304
1342
|
orch.state.shipment_id = str(task['shipmentNo'])
|
|
1343
|
+
# 槽位锁:同店并行执行位(每店 N 个;N 由 worker 的 STORE_CONCURRENCY 决定)
|
|
1344
|
+
slot_no = int(task.get('slotNo') or 0)
|
|
1345
|
+
if not orch.acquire_appt_slot_lock(slot_no):
|
|
1346
|
+
return {'status': 'failed',
|
|
1347
|
+
'summary': f'同店槽位 {slot_no} 已被占用(先让位,稍后重新入队)'}
|
|
305
1348
|
try:
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
1349
|
+
# 开店权(会换端口、踢掉别人的标签页)⇒ 同店同一时刻只允许一个进程真开窗口;
|
|
1350
|
+
# 窗口新鲜时**直接复用** cdp-port-map.json 里的端口,不再重复 open。
|
|
1351
|
+
got_open_lock = orch.acquire_store_executor_lock()
|
|
1352
|
+
try:
|
|
1353
|
+
dl_dir, port = orch.read_store_window()
|
|
1354
|
+
if got_open_lock and not port:
|
|
1355
|
+
_dl, port = orch._open_store()
|
|
1356
|
+
if not port:
|
|
1357
|
+
return {'status': 'failed', 'summary': 'CDP 端口未发现(店铺窗口未就绪)'}
|
|
1358
|
+
orch.remember_store_window(port, str(_dl or ''))
|
|
1359
|
+
dl_dir = _dl
|
|
1360
|
+
if not port:
|
|
1361
|
+
# 别的进程正在开店:等它把端口写进 map(最多 60s)
|
|
1362
|
+
for _ in range(60):
|
|
1363
|
+
await asyncio.sleep(1)
|
|
1364
|
+
dl_dir, port = orch.read_store_window()
|
|
1365
|
+
if port:
|
|
1366
|
+
break
|
|
1367
|
+
if not port:
|
|
1368
|
+
return {'status': 'failed', 'summary': '店铺窗口未就绪(开店权被占用且无可用端口,已等待 60s)'}
|
|
1369
|
+
orch._log(f' 🔗 复用店铺窗口:cdp_port={port}(无需重复开店)' if not got_open_lock
|
|
1370
|
+
else f' 🔗 店铺窗口:cdp_port={port}')
|
|
1371
|
+
finally:
|
|
1372
|
+
if got_open_lock:
|
|
1373
|
+
orch.release_store_executor_lock()
|
|
311
1374
|
orch.browser.cdp_url = f'http://127.0.0.1:{port}'
|
|
1375
|
+
if slot_no > 1:
|
|
1376
|
+
stagger = random.uniform(2.5, 6.0) * (slot_no - 1)
|
|
1377
|
+
orch._log(f' ⏱️ 同店多槽位错峰启动:slot={slot_no} 先等 {stagger:.1f}s')
|
|
1378
|
+
await asyncio.sleep(stagger)
|
|
312
1379
|
await orch._connect_with_port_rediscovery()
|
|
313
1380
|
await orch._preflight_store_window(phase='appointment-grab')
|
|
314
1381
|
if not orch.state.shipment_id:
|
|
@@ -317,119 +1384,29 @@ async def run_task(task: dict) -> dict:
|
|
|
317
1384
|
await orch.step1_prepare()
|
|
318
1385
|
await orch.step2_entry()
|
|
319
1386
|
await orch.step3_select_product()
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
try:
|
|
344
|
-
await orch._book_appointment(hour_idx=0, date_offset=offset,
|
|
345
|
-
time_from=time_from, time_to=time_to)
|
|
346
|
-
finally:
|
|
347
|
-
orch._release_store_step4_lock()
|
|
348
|
-
actual = str(getattr(orch, '_last_booked_date', '') or d.isoformat())
|
|
349
|
-
states[actual] = 'booked'
|
|
350
|
-
slot = str(getattr(orch, '_last_booked_slot', '') or 'first')
|
|
351
|
-
return {'status': 'booked', 'date': actual, 'slot': slot, 'dateStates': states, 'summary': f'{actual} {slot} 预约成功', 'windowMode': 'available_days'}
|
|
352
|
-
except Exception as exc:
|
|
353
|
-
msg = str(exc)
|
|
354
|
-
if '不可选' in msg or '目标日期' in msg:
|
|
355
|
-
states[d.isoformat()] = 'disabled'
|
|
356
|
-
elif any(k in msg for k in ('可用时段不足', '未渲染出可选时段', '时间选择失败', '未写入日期时间',
|
|
357
|
-
'指定时间范围内无可预约时段')):
|
|
358
|
-
states[d.isoformat()] = 'selectable_no_slot'
|
|
359
|
-
else:
|
|
360
|
-
states[d.isoformat()] = 'selectable_booking_failed'
|
|
361
|
-
orch._log(f' ⚠️ {d} 预约失败: {msg[:160]}')
|
|
362
|
-
else:
|
|
363
|
-
targets = []
|
|
364
|
-
d = max(from_date, today + timedelta(days=1))
|
|
365
|
-
while d <= to_date:
|
|
366
|
-
if weekday_allowed(d):
|
|
367
|
-
targets.append(d)
|
|
368
|
-
d += timedelta(days=1)
|
|
369
|
-
if not targets:
|
|
370
|
-
return {'status': 'failed', 'summary': '日期范围内没有符合星期条件的可预约日期(今天及以前不算)'}
|
|
371
|
-
states = {d.isoformat(): 'pending' for d in targets}
|
|
372
|
-
# 2026-10-21:range 模式也改为**每轮只打开一次日历**。
|
|
373
|
-
# 先在同一页面上扫完本轮所有目标日期;只有日期可选时才进入预约。
|
|
374
|
-
# 旧实现每个日期都 prepare_appointment_page() 重新打开页面,导致
|
|
375
|
-
# 一轮 3 个日期产生 6~10 次页面检查(用户看到的“轮次对不上”根因)。
|
|
376
|
-
prepared = False
|
|
377
|
-
for d in targets:
|
|
378
|
-
offset = (d - today).days
|
|
379
|
-
try:
|
|
380
|
-
if not prepared:
|
|
381
|
-
await prepare_appointment_page(orch)
|
|
382
|
-
prepared = True
|
|
383
|
-
info = await find_date_cell(orch, d)
|
|
384
|
-
if not info.get('found'):
|
|
385
|
-
states[d.isoformat()] = 'date_not_found'
|
|
386
|
-
print(json.dumps({'event': 'progress', 'cycle': cycle_no, 'checks': int(getattr(orch, '_appt_page_checks', 0)), 'dateStates': states}, ensure_ascii=False), flush=True)
|
|
387
|
-
continue
|
|
388
|
-
if info.get('disabled'):
|
|
389
|
-
states[d.isoformat()] = 'disabled'
|
|
390
|
-
print(json.dumps({'event': 'progress', 'cycle': cycle_no, 'checks': int(getattr(orch, '_appt_page_checks', 0)), 'dateStates': states}, ensure_ascii=False), flush=True)
|
|
391
|
-
continue
|
|
392
|
-
except Exception as exc:
|
|
393
|
-
prepared = False
|
|
394
|
-
states[d.isoformat()] = 'page_error'
|
|
395
|
-
orch._log(f' ⚠️ {d} 分类失败: {str(exc)[:120]}')
|
|
396
|
-
print(json.dumps({'event': 'progress', 'cycle': cycle_no, 'checks': int(getattr(orch, '_appt_page_checks', 0)), 'dateStates': states}, ensure_ascii=False), flush=True)
|
|
397
|
-
continue
|
|
398
|
-
print(json.dumps({'event': 'progress', 'cycle': cycle_no, 'checks': int(getattr(orch, '_appt_page_checks', 0)), 'dateStates': states}, ensure_ascii=False), flush=True)
|
|
399
|
-
try:
|
|
400
|
-
# 与 FULL 步骤4、其他抢预约任务共用同店预约锁:只串行化“提交预约”
|
|
401
|
-
orch._acquire_store_step4_lock(force=True)
|
|
402
|
-
try:
|
|
403
|
-
# range 模式严格目标日期:只点运营给的日期,⛔ 不允许 _pick_date 跳到范围外
|
|
404
|
-
await orch._book_appointment(hour_idx=0, date_offset=offset, exact_date=d.isoformat(),
|
|
405
|
-
time_from=time_from, time_to=time_to)
|
|
406
|
-
finally:
|
|
407
|
-
orch._release_store_step4_lock()
|
|
408
|
-
actual = str(getattr(orch, '_last_booked_date', '') or d.isoformat())
|
|
409
|
-
if actual != d.isoformat():
|
|
410
|
-
raise RuntimeError(f'严格日期校验失败:目标 {d.isoformat()},实际页面选中 {actual}(不提交)')
|
|
411
|
-
states[d.isoformat()] = 'booked'
|
|
412
|
-
slot = str(getattr(orch, '_last_booked_slot', '') or 'first')
|
|
413
|
-
return {'status': 'booked', 'date': actual, 'slot': slot, 'dateStates': states, 'summary': f'{actual} {slot} 预约成功'}
|
|
414
|
-
except Exception as exc:
|
|
415
|
-
prepared = False
|
|
416
|
-
msg = str(exc)
|
|
417
|
-
if '不可选' in msg or '目标日期' in msg:
|
|
418
|
-
states[d.isoformat()] = 'disabled'
|
|
419
|
-
elif any(k in msg for k in ('可用时段不足', '未渲染出可选时段', '时间选择失败', '未写入日期时间',
|
|
420
|
-
'指定时间范围内无可预约时段')):
|
|
421
|
-
states[d.isoformat()] = 'selectable_no_slot'
|
|
422
|
-
else:
|
|
423
|
-
states[d.isoformat()] = 'selectable_booking_failed'
|
|
424
|
-
orch._log(f' ⚠️ {d} 预约失败: {msg[:160]}')
|
|
425
|
-
last_states = states
|
|
426
|
-
print(json.dumps({'event': 'cycle', 'cycle': cycle_no, 'checks': int(getattr(orch, '_appt_page_checks', 0)), 'dateStates': states}, ensure_ascii=False), flush=True)
|
|
427
|
-
if cycles and cycle_no >= cycles:
|
|
428
|
-
break
|
|
429
|
-
interval = max(30, min(600, int(task.get('pollIntervalSec') or 30)))
|
|
430
|
-
elapsed = time.monotonic() - cycle_started
|
|
431
|
-
await asyncio.sleep(max(10, interval - elapsed))
|
|
432
|
-
return {'status': 'failed', 'dateStates': last_states, 'cycles': cycle_no, 'summary': '本轮日期范围内未抢到预约'}
|
|
1387
|
+
pacing = Pacing(
|
|
1388
|
+
refresh_min_sec=_CLI_PACING['refresh_min'] if _CLI_PACING['refresh_min'] else Pacing.refresh_min_sec,
|
|
1389
|
+
refresh_max_sec=_CLI_PACING['refresh_max'] if _CLI_PACING['refresh_max'] else Pacing.refresh_max_sec,
|
|
1390
|
+
)
|
|
1391
|
+
loop = AppointmentLoop(
|
|
1392
|
+
OrchestratorDriver(orch, pacing=pacing),
|
|
1393
|
+
date_mode=date_mode,
|
|
1394
|
+
from_date=from_date,
|
|
1395
|
+
to_date=to_date,
|
|
1396
|
+
weekdays=weekdays,
|
|
1397
|
+
time_from=time_from,
|
|
1398
|
+
time_to=time_to,
|
|
1399
|
+
rule_spec=rule_spec,
|
|
1400
|
+
rule_min_lead_hours=float((rule_snapshot or {}).get('spec', {}).get('minLeadHours') or 0) if rule_snapshot else 0,
|
|
1401
|
+
available_days=int(task.get('availableDays') or 0),
|
|
1402
|
+
pacing=pacing,
|
|
1403
|
+
max_scan_months=MAX_SCAN_MONTHS,
|
|
1404
|
+
# ⛔ 不设 max_rounds:任务模型里也没有 maxCycles(实测 ERP AppointmentTask 无该字段),
|
|
1405
|
+
# 值守循环的唯一终止 = 抢到 / 运营停止(stopRequestedAt → SIGTERM)。
|
|
1406
|
+
max_rounds=None,
|
|
1407
|
+
task=task,
|
|
1408
|
+
)
|
|
1409
|
+
return await loop.run()
|
|
433
1410
|
finally:
|
|
434
1411
|
try:
|
|
435
1412
|
_APPT_CLOSE_LAST['closed'] = await _close_appointment_tab(orch)
|
|
@@ -443,6 +1420,10 @@ async def run_task(task: dict) -> dict:
|
|
|
443
1420
|
orch.release_store_executor_lock()
|
|
444
1421
|
except Exception:
|
|
445
1422
|
pass
|
|
1423
|
+
try:
|
|
1424
|
+
orch.release_appt_slot_lock()
|
|
1425
|
+
except Exception:
|
|
1426
|
+
pass
|
|
446
1427
|
|
|
447
1428
|
|
|
448
1429
|
_APPT_CLOSE_LAST = {'closed': 0}
|
|
@@ -451,6 +1432,60 @@ _APPT_CLOSE_LAST = {'closed': 0}
|
|
|
451
1432
|
_ORCH = None
|
|
452
1433
|
|
|
453
1434
|
|
|
1435
|
+
# ══════════════════════════════════════════════════════════════════════════════
|
|
1436
|
+
# 停止收尾(保持原实现:标签页必须关掉;同步 CDP 兜底)
|
|
1437
|
+
# ══════════════════════════════════════════════════════════════════════════════
|
|
1438
|
+
async def _close_appointment_tab(orch) -> int:
|
|
1439
|
+
"""停止/失败时关闭本任务用的预约标签页;若它是窗口最后 1 个标签,先开一个占位页再关。
|
|
1440
|
+
|
|
1441
|
+
2026-11-07 修复("停止后标签页仍在"):
|
|
1442
|
+
· 旧实现只看 `orch.browser.page`(当前页),stop 时当前页可能已不是预约页(或被切走)⇒ 漏关;
|
|
1443
|
+
· 改为**遍历所有 context 的所有 page**,按 URL 匹配 appointment-v2(或本任务货件号 + appointment);
|
|
1444
|
+
· 失败不再静默吞掉:返回实际关闭数,main 的停止摘要按真实结果生成(不再硬编码"已关闭")。
|
|
1445
|
+
"""
|
|
1446
|
+
closed = 0
|
|
1447
|
+
shipment_id = str(getattr(getattr(orch, 'state', None), 'shipment_id', '') or '')
|
|
1448
|
+
try:
|
|
1449
|
+
contexts = list(getattr(orch.browser, 'contexts', []) or [])
|
|
1450
|
+
for ctx in contexts:
|
|
1451
|
+
try:
|
|
1452
|
+
pages = list(ctx.pages)
|
|
1453
|
+
except Exception:
|
|
1454
|
+
continue
|
|
1455
|
+
for page in pages:
|
|
1456
|
+
try:
|
|
1457
|
+
if page.is_closed():
|
|
1458
|
+
continue
|
|
1459
|
+
url = str(getattr(page, 'url', '') or '')
|
|
1460
|
+
# 2026-11-17 并行安全:只关**本任务**(按 shipment_id 命中)的预约页;
|
|
1461
|
+
# 同店并行时其它任务的 appointment-v2 标签绝不能碰。
|
|
1462
|
+
if shipment_id:
|
|
1463
|
+
is_appt = ('appointment' in url) and (shipment_id in url)
|
|
1464
|
+
else:
|
|
1465
|
+
# 无货件号(SKU-only 起步):只认当前自己的 page
|
|
1466
|
+
is_appt = ('appointment-v2' in url) and page is getattr(orch.browser, 'page', None)
|
|
1467
|
+
if not is_appt:
|
|
1468
|
+
continue
|
|
1469
|
+
if len(ctx.pages) <= 1:
|
|
1470
|
+
try:
|
|
1471
|
+
await ctx.new_page() # 占位,保持窗口不退出
|
|
1472
|
+
except Exception:
|
|
1473
|
+
return closed
|
|
1474
|
+
await page.close()
|
|
1475
|
+
closed += 1
|
|
1476
|
+
orch._log(f' 🗂️ 已关闭抢预约任务标签页({url[:100]})')
|
|
1477
|
+
except Exception as e:
|
|
1478
|
+
try: orch._log(f' ⚠️ 关闭预约标签页失败:{str(e)[:120]}')
|
|
1479
|
+
except Exception: pass
|
|
1480
|
+
if not closed:
|
|
1481
|
+
try: orch._log(' ⚠️ 停止时未找到待关闭的预约标签页(可能已被用户关闭)')
|
|
1482
|
+
except Exception: pass
|
|
1483
|
+
except Exception as e:
|
|
1484
|
+
try: orch._log(f' ⚠️ 关闭预约标签页异常:{str(e)[:120]}')
|
|
1485
|
+
except Exception: pass
|
|
1486
|
+
return closed
|
|
1487
|
+
|
|
1488
|
+
|
|
454
1489
|
def _http_sync(url: str, method: str = 'GET', timeout: float = 2.0):
|
|
455
1490
|
req = urllib.request.Request(url, method=method)
|
|
456
1491
|
with urllib.request.urlopen(req, timeout=timeout) as r:
|
|
@@ -470,16 +1505,26 @@ def _close_appointment_tab_via_cdp(orch) -> int:
|
|
|
470
1505
|
if not endpoint:
|
|
471
1506
|
return 0
|
|
472
1507
|
targets = json.loads(_http_sync(f'{endpoint}/json/list').decode('utf-8', 'replace') or '[]')
|
|
473
|
-
|
|
1508
|
+
shipment_id_sync = str(getattr(getattr(orch, 'state', None), 'shipment_id', '') or '')
|
|
1509
|
+
appt = [t for t in targets
|
|
1510
|
+
if ('appointment' in str(t.get('url') or ''))
|
|
1511
|
+
and (not shipment_id_sync or shipment_id_sync in str(t.get('url') or ''))]
|
|
474
1512
|
if not appt:
|
|
475
1513
|
try: orch._log(' ⚠️ 同步清理:未发现 appointment-v2 标签页')
|
|
476
1514
|
except Exception: pass
|
|
477
1515
|
return 0
|
|
478
|
-
#
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
1516
|
+
# 只有预约页是窗口里最后一个页面时才开占位页;用户/店铺已有其它标签 → 直接关(不制造空页)
|
|
1517
|
+
others = [
|
|
1518
|
+
t for t in targets
|
|
1519
|
+
if t not in appt and str(t.get('type') or '') == 'page'
|
|
1520
|
+
and not str(t.get('url') or '').startswith('about:')
|
|
1521
|
+
and 'chrome-extension://' not in str(t.get('url') or '')
|
|
1522
|
+
]
|
|
1523
|
+
if not others:
|
|
1524
|
+
try: _http_sync(f'{endpoint}/json/new?about:blank', method='PUT')
|
|
1525
|
+
except Exception:
|
|
1526
|
+
try: _http_sync(f'{endpoint}/json/new?about:blank')
|
|
1527
|
+
except Exception: pass
|
|
483
1528
|
for t in appt:
|
|
484
1529
|
tid = str(t.get('id') or '')
|
|
485
1530
|
if not tid: continue
|