@whyshu/argent-engine 0.7.7 → 0.8.0-rc.10
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 +67 -45
- package/engine/VERSION +1 -1
- package/engine/core/contracts/argent.contracts.json +2 -2
- package/engine/core/contracts/verbs.schema.json +64 -1
- package/engine/core/lib/argent-datadir.mjs +6 -0
- package/engine/core/lib/contract.mjs +30 -0
- package/engine/core/mcp/server.mjs +171 -2
- package/engine/scripts/appointment-create.mjs +2 -2
- package/engine/scripts/argent-doctor.mjs +44 -3
- package/engine/scripts/argent-machine-setup.mjs +3 -1
- package/engine/scripts/argent-runner.mjs +4 -2
- package/engine/scripts/argent-schedule.mjs +6 -0
- package/engine/scripts/base-bootstrap.sh +0 -0
- package/engine/scripts/billing-mode-daily.sh +0 -0
- package/engine/scripts/build-doc-index.mjs +68 -0
- package/engine/scripts/build-engine-package.mjs +18 -3
- package/engine/scripts/capability-packs.lock.json +66 -65
- package/engine/scripts/check-argent-desktop.mjs +91 -0
- package/engine/scripts/check-billing-mode.sh +0 -0
- package/engine/scripts/check-docs-drift.mjs +51 -4
- package/engine/scripts/check-dsh-web-expose.sh +0 -0
- package/engine/scripts/ci-run.sh +2 -2
- package/engine/scripts/customer-readiness.sh +0 -0
- package/engine/scripts/daily-report-run.sh +68 -0
- package/engine/scripts/daily-report-status.mjs +130 -0
- package/engine/scripts/daily-report-timer-plist.sh +89 -0
- package/engine/scripts/daily-report-timers.sh +199 -0
- package/engine/scripts/daily-report.mjs +136 -7
- package/engine/scripts/daily-report.sh +0 -0
- package/engine/scripts/desktop-trial.sh +0 -0
- package/engine/scripts/dev-window.sh +0 -0
- package/engine/scripts/doc-status.mjs +212 -0
- package/engine/scripts/drill-clean-room.sh +0 -0
- package/engine/scripts/drill-handover.sh +0 -0
- package/engine/scripts/dsh-backup-scope.sh +0 -0
- package/engine/scripts/dsh-overlay-pin.sh +0 -0
- package/engine/scripts/dsh-release-watch-daily.sh +0 -0
- package/engine/scripts/dsh-remote-check.sh +0 -0
- package/engine/scripts/dsh-restart.sh +0 -0
- package/engine/scripts/dsh-restore.sh +0 -0
- package/engine/scripts/dsh-url.sh +0 -0
- package/engine/scripts/erp_invoice_shadow.py +62 -0
- package/engine/scripts/erp_invoice_writeback.py +93 -0
- package/engine/scripts/flow-requirements.json +4 -4
- package/engine/scripts/flow-session-retention.mjs +2 -1
- package/engine/scripts/flow-timers-plist.sh +0 -0
- package/engine/scripts/flow-timers.sh +11 -0
- package/engine/scripts/flow-trigger-wake.mjs +6 -3
- package/engine/scripts/flow-trigger.sh +0 -0
- package/engine/scripts/flow_config.py +16 -0
- package/engine/scripts/flow_failure.py +3 -0
- package/engine/scripts/flow_source.py +10 -1
- package/engine/scripts/flow_sources/__init__.py +1 -0
- package/engine/scripts/flow_sources/erp.py +54 -0
- package/engine/scripts/fulfillment_sites.py +46 -0
- package/engine/scripts/gen-agent-bundles.mjs +1 -1
- package/engine/scripts/init-ml.sh +0 -0
- package/engine/scripts/invoice-table.sh +0 -0
- package/engine/scripts/invoice_lip_runner.py +43 -0
- package/engine/scripts/invoice_runner.py +5 -3
- package/engine/scripts/invoice_stageb.py +21 -4
- package/engine/scripts/lib/argent-datadir.sh +0 -0
- package/engine/scripts/lib/argent_datadir.py +5 -0
- package/engine/scripts/lib/daily-report-status.mjs +227 -0
- package/engine/scripts/lib/plugin-packages.mjs +3 -0
- package/engine/scripts/lib/repo-root.sh +0 -0
- package/engine/scripts/migrate-skills.sh +0 -0
- package/engine/scripts/ml-ads.mjs +181 -0
- package/engine/scripts/ml-oauth-setup.mjs +1 -1
- package/engine/scripts/ml_hub_status.py +3 -3
- package/engine/scripts/npm-publish-argent.sh +0 -0
- package/engine/scripts/orchestrator.py +228 -31
- package/engine/scripts/orchestrator_br.py +14412 -0
- package/engine/scripts/patches/retire-check.sh +0 -0
- package/engine/scripts/poll-fulfillment.sh +0 -0
- package/engine/scripts/poll-invoice.sh +0 -0
- package/engine/scripts/provider-select.sh +0 -0
- package/engine/scripts/provider-switch.sh +0 -0
- package/engine/scripts/python-runtime.sh +0 -0
- package/engine/scripts/query_runner.py +2 -3
- package/engine/scripts/release-argent.sh +0 -0
- package/engine/scripts/release-gate-0.8.mjs +81 -0
- package/engine/scripts/run-tests.sh +0 -0
- package/engine/scripts/s1-audit.mjs +4 -1
- package/engine/scripts/session-handoff.mjs +2 -1
- package/engine/scripts/setup.sh +0 -0
- package/engine/scripts/skuflow_invoice_runner.py +164 -0
- package/engine/scripts/sync-plugins.sh +0 -0
- package/engine/scripts/sync-presets.sh +0 -0
- package/engine/scripts/sync-scripts.sh +0 -0
- package/engine/scripts/telemetry.py +6 -2
- package/engine/scripts/usage-anchor.sh +0 -0
- package/engine/scripts/vertical-lint.mjs +19 -0
- package/engine/scripts/wenyao-browser.sh +0 -0
- package/engine/scripts/wenyao-login.sh +0 -0
- package/engine/scripts/xzh-browser.sh +2 -1
- package/engine/scripts/xzh_browser.py +1 -1
- package/engine/scripts/ziniao-auth-probe.sh +67 -18
- package/engine/scripts/ziniao-keepalive.sh +0 -0
- package/engine/scripts/ziniao-post-upgrade-check.sh +0 -0
- package/engine/scripts/ziniao-windows.sh +0 -0
- package/engine/skills/ml-fulfillment-sop/SKILL.md +29 -0
- package/engine/skills/ml-fulfillment-sop/references/agentic-runtime-v3.md +39 -0
- package/engine/skills/ml-fulfillment-sop/scripts/poll-and-execute.sh +0 -0
- package/engine/skills/ml-store-daily-report/SKILL.md +68 -0
- package/engine/tools/agentic/README.md +95 -0
- package/engine/tools/agentic/mcp_server.py +212 -0
- package/engine/tools/agentic/ml_agent_tools.py +602 -0
- package/engine/version.mjs +1 -1
- package/engine/verticals/_engine-words.baseline.txt +16 -2
- package/engine/verticals/mercadolibre/brazil-full-sop.json +47 -0
- package/engine/verticals/mercadolibre/flows.json +15 -5
- package/engine/verticals/mercadolibre/prompts/full.failure.md +39 -1
- package/package.json +1 -1
|
@@ -45,6 +45,11 @@ import {
|
|
|
45
45
|
// 广告(Product Ads)只读取数/聚合/告警:与 `scripts/ml-ads.mjs` 共用同一份实现
|
|
46
46
|
// (⛔ 不在两处各写一份口径;2026-10-17 新增,默认关,客户开广告权限后再启用 `ads.summary`)
|
|
47
47
|
import { fetchAdsReport, adsCardLines } from './lib/ml-ads-core.mjs'
|
|
48
|
+
// 定时器状态(2026-10-30):日报改成 launchd 直跑确定性脚本后没有会话/台账可看 ⇒
|
|
49
|
+
// 每轮把「推了哪几家 / 下次几点 / 上次错误」落一份状态文件(桌宠 / doctor / CLI 读同一份)。
|
|
50
|
+
import {
|
|
51
|
+
computeStoreStates, mergeStatus, readStatus, summarizeStates, writeStatus,
|
|
52
|
+
} from './lib/daily-report-status.mjs'
|
|
48
53
|
|
|
49
54
|
// 逐字转出(既有调用方/单测 import 路径不变;同一绑定 ⇒ `M.aggregateOrders === core.aggregateOrders`)
|
|
50
55
|
export { aggregateOrders, localDateStr, tzOffsetMs, startOfLocalDayUTC, localHour, loadEnvFile }
|
|
@@ -745,7 +750,7 @@ export function buildTableCard(payload) {
|
|
|
745
750
|
{ k: '件数', cur: fmtNum(payload.totals?.units?.current), d1: fmtNum(payload.totals?.units?.prevDay), d7: fmtNum(payload.totals?.units?.prevWeek), d30: fmtNum(payload.totals?.units?.prevMonth) },
|
|
746
751
|
{ k: '取消', cur: fmtNum(payload.totals?.cancelled?.current), d1: fmtNum(payload.totals?.cancelled?.prevDay), d7: fmtNum(payload.totals?.cancelled?.prevWeek), d30: fmtNum(payload.totals?.cancelled?.prevMonth) },
|
|
747
752
|
]
|
|
748
|
-
const url = process.env.ML_ERP_REPORT_URL || 'https://whyshu.com/admin/argent
|
|
753
|
+
const url = process.env.ML_ERP_REPORT_URL || 'https://whyshu.com/admin/argent/?tenant=ly-0001#/reports'
|
|
749
754
|
const elements = [
|
|
750
755
|
{ tag: 'markdown', content: `**跨店总览** · 昨日 / 前一日 / 上周同期 / 上月同期对比(完整数据点下方按钮)` },
|
|
751
756
|
{ tag: 'table', page_size: 10, row_height: 'low', freeze_first_column: true, header_style: { bold: true, background_style: 'grey' }, columns: overviewColumns, rows: overviewRows },
|
|
@@ -904,6 +909,34 @@ function larkConfig() {
|
|
|
904
909
|
} catch { return {} }
|
|
905
910
|
}
|
|
906
911
|
|
|
912
|
+
/**
|
|
913
|
+
* 推送目标守卫(2026-11-02 事故后固化)——**默认拒绝**,必须显式放行。
|
|
914
|
+
*
|
|
915
|
+
* 事故:开发机上装定时器 + 手动跑一轮,把一条真实日报推进了客户群(六禾园智能体)。
|
|
916
|
+
* 根因不是权限,是"任何机器都能往任何群推"。故改成 fail-closed:
|
|
917
|
+
* 放行条件(任一):`ARGENT_ALLOW_CUSTOMER_PUSH=1` | cfg.dailyReport.role === 'production'
|
|
918
|
+
* | chatId ∈ cfg.dailyReport.allowedChatIds
|
|
919
|
+
* 其余一律拒绝,并在错误里给出放行办法(⛔ 不静默跳过,必须让人看见)。
|
|
920
|
+
*/
|
|
921
|
+
export function pushTargetAllowed({ chatId = '', cfg = {}, env = process.env } = {}) {
|
|
922
|
+
const dr = (cfg && cfg.dailyReport) || {}
|
|
923
|
+
if (String(env.ARGENT_ALLOW_CUSTOMER_PUSH || '') === '1') return { ok: true, reason: 'env-override' }
|
|
924
|
+
if (Array.isArray(dr.allowedChatIds) && dr.allowedChatIds.length) {
|
|
925
|
+
return dr.allowedChatIds.includes(String(chatId))
|
|
926
|
+
? { ok: true, reason: 'allowlist' }
|
|
927
|
+
: { ok: false, reason: 'not-in-allowlist', detail: `目标群 ${chatId} 不在 dailyReport.allowedChatIds 里` }
|
|
928
|
+
}
|
|
929
|
+
if (String(dr.role || '').toLowerCase() === 'production') return { ok: true, reason: 'production-role' }
|
|
930
|
+
const role = String(dr.role || '').trim()
|
|
931
|
+
return {
|
|
932
|
+
ok: false,
|
|
933
|
+
reason: 'no-role-and-no-allowlist',
|
|
934
|
+
detail: role
|
|
935
|
+
? `本机 dailyReport.role=${role}(不是 production),也没配 allowedChatIds ⇒ 禁止向客户群推送`
|
|
936
|
+
: '本机未声明 dailyReport.role=production,也没有 allowedChatIds ⇒ 禁止向客户群推送',
|
|
937
|
+
}
|
|
938
|
+
}
|
|
939
|
+
|
|
907
940
|
// 读取链:Web 配置中心 config.json(mlDaily*)→ daily-report.env(旧键)→ 默认
|
|
908
941
|
export function pick(cfg, env, cfgKey, envKey, def) {
|
|
909
942
|
const v = cfg[cfgKey] ?? env[envKey]
|
|
@@ -972,6 +1005,7 @@ function pushLark(md, chatId, profile) {
|
|
|
972
1005
|
if (r.status !== 0) {
|
|
973
1006
|
throw new Error(`lark-cli 推送失败: ${(r.error?.message || r.stderr || r.stdout || '').slice(0, 300)}`)
|
|
974
1007
|
}
|
|
1008
|
+
return larkMessageId(r.stdout)
|
|
975
1009
|
}
|
|
976
1010
|
|
|
977
1011
|
// 2026-08-31:lark-bot 通道改发 interactive 卡片(与 webhook 卡片同构,角色化后保持卡片式)
|
|
@@ -984,6 +1018,18 @@ function pushLarkCard(card, chatId, profile) {
|
|
|
984
1018
|
if (r.status !== 0) {
|
|
985
1019
|
throw new Error(`lark-cli 卡片推送失败: ${(r.error?.message || r.stderr || r.stdout || '').slice(0, 300)}`)
|
|
986
1020
|
}
|
|
1021
|
+
return larkMessageId(r.stdout)
|
|
1022
|
+
}
|
|
1023
|
+
|
|
1024
|
+
/**
|
|
1025
|
+
* 从 lark-cli 的 stdout 取 message_id(2026-11-02:**推完必须记得住 id**,
|
|
1026
|
+
* 否则事后要撤回却拿不到 id —— 客户机 bot 也没有 im:message:readonly 列不了消息)。
|
|
1027
|
+
*/
|
|
1028
|
+
function larkMessageId(stdout) {
|
|
1029
|
+
try {
|
|
1030
|
+
const d = JSON.parse(String(stdout || ''))
|
|
1031
|
+
return (d && ((d.data && d.data.message_id) || d.message_id)) || ''
|
|
1032
|
+
} catch { return '' }
|
|
987
1033
|
}
|
|
988
1034
|
|
|
989
1035
|
/** 上传结构化日报到 ERP(bridge secret;失败不阻断群推送,ERP 页显示上一份)。 */
|
|
@@ -1020,8 +1066,21 @@ async function pushCards(env, cards, overview) {
|
|
|
1020
1066
|
if (overview) await pushWebhook(webhook, overview)
|
|
1021
1067
|
return 'webhook'
|
|
1022
1068
|
}
|
|
1023
|
-
|
|
1024
|
-
if (
|
|
1069
|
+
const gate = pushTargetAllowed({ chatId, cfg, env })
|
|
1070
|
+
if (!gate.ok) {
|
|
1071
|
+
throw new Error(`⛔ 拒绝推送(${gate.reason}):${gate.detail || ''}`
|
|
1072
|
+
+ ' | 放行办法:本机 config.json → dailyReport.allowedChatIds 加该群,或显式 ARGENT_ALLOW_CUSTOMER_PUSH=1')
|
|
1073
|
+
}
|
|
1074
|
+
const ids = []
|
|
1075
|
+
for (const c of cards) ids.push(pushLarkCard(c.card, chatId, profile)) // 每店一张卡(用户决策 D)
|
|
1076
|
+
if (overview) ids.push(pushLarkCard(overview.card, chatId, profile))
|
|
1077
|
+
// 记住 id(撤回/审计用);失败不阻断推送
|
|
1078
|
+
try {
|
|
1079
|
+
writeFileSync(join(DATA_DIR, 'daily-report-last-push.json'), JSON.stringify({
|
|
1080
|
+
at: new Date().toISOString(), chatId, profile, messageIds: ids.filter(Boolean),
|
|
1081
|
+
}, null, 2) + '\n')
|
|
1082
|
+
} catch { /* 写不进去不影响推送 */ }
|
|
1083
|
+
if (ids.filter(Boolean).length) console.log(`[daily-report] 本次消息 id:${ids.filter(Boolean).join(', ')}`)
|
|
1025
1084
|
return 'lark-bot-card'
|
|
1026
1085
|
}
|
|
1027
1086
|
|
|
@@ -1393,6 +1452,55 @@ export function collectMock(fixture) {
|
|
|
1393
1452
|
})
|
|
1394
1453
|
}
|
|
1395
1454
|
|
|
1455
|
+
// ── 定时器状态(2026-10-30)──────────────────────────────────
|
|
1456
|
+
// 只记**事实**:本轮推了哪些店、失败原因、下次该推时点(由标记文件推算)。
|
|
1457
|
+
// 状态写入**永不影响**推送结果(try/catch 兜住);--dry-run / --json / --mock / 列表模式不写。
|
|
1458
|
+
const STATUS_ACC = { pushed: [], failed: [], summary: '' }
|
|
1459
|
+
const STATUS_CTX = { stores: [], reportTime: '' }
|
|
1460
|
+
|
|
1461
|
+
function statusEnabled() {
|
|
1462
|
+
return !FLAG_DRY && !FLAG_JSON && !MOCK_FILE && !FLAG_LIST_SECTIONS && !FLAG_LIST_STORES
|
|
1463
|
+
}
|
|
1464
|
+
|
|
1465
|
+
function finalizeStatus({ code = 0, startedAt = '', error = '' } = {}) {
|
|
1466
|
+
if (!statusEnabled()) return
|
|
1467
|
+
try {
|
|
1468
|
+
const now = new Date()
|
|
1469
|
+
const prev = readStatus(DATA_HOME)
|
|
1470
|
+
const patch = {
|
|
1471
|
+
updatedAt: now.toISOString(),
|
|
1472
|
+
lastRunAt: startedAt || prev.lastRunAt || now.toISOString(),
|
|
1473
|
+
lastFinishAt: now.toISOString(),
|
|
1474
|
+
lastExit: code,
|
|
1475
|
+
reportTime: STATUS_CTX.reportTime || prev.reportTime || '00:05',
|
|
1476
|
+
lastPushed: STATUS_ACC.pushed,
|
|
1477
|
+
failed: STATUS_ACC.failed,
|
|
1478
|
+
lastSummary: STATUS_ACC.summary || '',
|
|
1479
|
+
lastError: code === 0 ? '' : (error || STATUS_ACC.summary
|
|
1480
|
+
|| (STATUS_ACC.failed.length ? `${STATUS_ACC.failed.length} 家取数失败:${STATUS_ACC.failed[0].store}(${STATUS_ACC.failed[0].error})` : '')
|
|
1481
|
+
|| `exit ${code}`),
|
|
1482
|
+
}
|
|
1483
|
+
if (code === 0) patch.lastOkAt = now.toISOString()
|
|
1484
|
+
const pushedAt = STATUS_ACC.pushed.reduce((max, p) => (p.at > max ? p.at : max), '')
|
|
1485
|
+
if (pushedAt) patch.lastPushAt = pushedAt
|
|
1486
|
+
// 用 --store / --date 过滤的运行只记"推了什么",不重算全店派生面(否则会把其它店的状态写成空)
|
|
1487
|
+
if (STATUS_CTX.stores.length && !ARG_STORE.length) {
|
|
1488
|
+
const states = computeStoreStates({
|
|
1489
|
+
stores: STATUS_CTX.stores,
|
|
1490
|
+
cacheDir: cacheDir(),
|
|
1491
|
+
now,
|
|
1492
|
+
reportTime: patch.reportTime,
|
|
1493
|
+
})
|
|
1494
|
+
Object.assign(patch, summarizeStates(states))
|
|
1495
|
+
if (!patch.lastPushAt) patch.lastPushAt = prev.lastPushAt || ''
|
|
1496
|
+
if (!patch.pending) patch.pending = prev.pending || []
|
|
1497
|
+
}
|
|
1498
|
+
writeStatus(DATA_HOME, mergeStatus(prev, patch))
|
|
1499
|
+
} catch (e) {
|
|
1500
|
+
console.error(`⚠️ 定时器状态写入失败(不影响推送):${e.message}`)
|
|
1501
|
+
}
|
|
1502
|
+
}
|
|
1503
|
+
|
|
1396
1504
|
// ── 主流程 ─────────────────────────────────────────────────
|
|
1397
1505
|
async function main() {
|
|
1398
1506
|
// 进程 env 覆盖 env 文件(文件仍是部署基线;命令行临时覆盖用 process.env)
|
|
@@ -1417,6 +1525,7 @@ async function main() {
|
|
|
1417
1525
|
const now = ARG_ASOF ? new Date(ARG_ASOF) : new Date()
|
|
1418
1526
|
if (ARG_ASOF && Number.isNaN(now.getTime())) { console.error(`✗ --as-of 解析失败:${ARG_ASOF}`); return 1 }
|
|
1419
1527
|
const reportTime = pick(cfg, env, 'mlDailyTime', 'REPORT_TIME', '08:00')
|
|
1528
|
+
STATUS_CTX.reportTime = String(reportTime)
|
|
1420
1529
|
|
|
1421
1530
|
if (MOCK_FILE) {
|
|
1422
1531
|
const fixture = JSON.parse(readFileSync(MOCK_FILE, 'utf8'))
|
|
@@ -1437,6 +1546,8 @@ async function main() {
|
|
|
1437
1546
|
}
|
|
1438
1547
|
stores = stores.stores || []
|
|
1439
1548
|
STORE_LIST = stores // 供 token 轮换后原子写回(persistStores)
|
|
1549
|
+
// 定时器状态的派生面永远按**全量**店铺算(--store 过滤只影响本轮抓取,不影响"哪几家还没推")
|
|
1550
|
+
STATUS_CTX.stores = stores.slice()
|
|
1440
1551
|
if (FLAG_LIST_STORES) {
|
|
1441
1552
|
console.log(JSON.stringify({ stores: stores.map((x) => ({ name: x.name, site: x.site, user_id: String(x.user_id) })) }, null, 1))
|
|
1442
1553
|
return 0
|
|
@@ -1487,10 +1598,15 @@ async function main() {
|
|
|
1487
1598
|
})
|
|
1488
1599
|
}
|
|
1489
1600
|
}
|
|
1601
|
+
// 定时器状态:把本轮每店事实记下来(成功也记 —— "这轮跑了、某店取数失败"同样是状态)
|
|
1602
|
+
STATUS_ACC.failed = reports.filter((x) => !x.r.summary).map((x) => ({
|
|
1603
|
+
store: x.store.name, site: x.store.site, error: String(x.r.error || '采集失败').slice(0, 200),
|
|
1604
|
+
}))
|
|
1490
1605
|
|
|
1491
1606
|
const okReports = reports.filter((x) => x.r.summary)
|
|
1492
1607
|
if (!okReports.length) {
|
|
1493
1608
|
console.error('✗ 全部店铺采集失败,不推送')
|
|
1609
|
+
STATUS_ACC.summary = `全部店铺采集失败(${reports.length} 家)`
|
|
1494
1610
|
return 1
|
|
1495
1611
|
}
|
|
1496
1612
|
|
|
@@ -1593,10 +1709,16 @@ async function main() {
|
|
|
1593
1709
|
if (!FLAG_NO_MARK) {
|
|
1594
1710
|
for (const { store, r } of due) markPushed(r.date, store)
|
|
1595
1711
|
}
|
|
1712
|
+
const at = new Date().toISOString()
|
|
1713
|
+
STATUS_ACC.pushed = due.map(({ store, r }) => ({
|
|
1714
|
+
store: store.name, site: store.site, date: r.date, at,
|
|
1715
|
+
}))
|
|
1716
|
+
STATUS_ACC.summary = `已推送 ${due.length} 家(${channel})· ${dateLabel}`
|
|
1596
1717
|
console.log(`[daily-report] ✅ 日报已推送(${channel}):${title}(${due.length} 家店铺)${FLAG_NO_MARK ? '(--no-mark 未写幂等标记)' : ''}`)
|
|
1597
1718
|
return 0
|
|
1598
1719
|
} catch (err) {
|
|
1599
1720
|
console.error(`✗ 推送失败:${err.message}`)
|
|
1721
|
+
STATUS_ACC.summary = `推送失败:${String(err.message).slice(0, 160)}`
|
|
1600
1722
|
// KB-090:推送失败 → 飞书告警(webhook 优先/lark-bot 兜底/alert.log 落盘)
|
|
1601
1723
|
await notifyPushFailure(env, err).catch(() => {})
|
|
1602
1724
|
return 1
|
|
@@ -1606,8 +1728,15 @@ async function main() {
|
|
|
1606
1728
|
// 仅直接执行时跑主流程(import 单测时不触发)
|
|
1607
1729
|
const isMain = isDirectRun(import.meta.url)
|
|
1608
1730
|
if (isMain) {
|
|
1609
|
-
|
|
1610
|
-
|
|
1611
|
-
|
|
1612
|
-
|
|
1731
|
+
const startedAt = new Date().toISOString()
|
|
1732
|
+
main()
|
|
1733
|
+
.then((code) => {
|
|
1734
|
+
finalizeStatus({ code: code === 0 ? 0 : 1, startedAt })
|
|
1735
|
+
process.exit(code)
|
|
1736
|
+
})
|
|
1737
|
+
.catch((err) => {
|
|
1738
|
+
console.error(`✗ 异常:${err.message}`)
|
|
1739
|
+
finalizeStatus({ code: 1, startedAt, error: `未捕获异常:${err.message}` })
|
|
1740
|
+
process.exit(1)
|
|
1741
|
+
})
|
|
1613
1742
|
}
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* doc-status.mjs —— 文档状态体检(**默认 dry-run,只报告,不写任何文件**)
|
|
4
|
+
*
|
|
5
|
+
* 背景(2026-11-02):docs 下 105 篇,零 frontmatter;INDEX 里写死过版本号 ⇒ "新旧误会"。
|
|
6
|
+
* 本脚本按 INDEX 归属 + 文件名 + 已有横幅,给每篇一个**候选 status** 与依据,
|
|
7
|
+
* 供人工审阅后再落 frontmatter(见 docs/INDEX.md §文档状态约定)。
|
|
8
|
+
*
|
|
9
|
+
* 用法:
|
|
10
|
+
* node scripts/doc-status.mjs # 全部 docs/*.md,打印表格
|
|
11
|
+
* node scripts/doc-status.mjs --limit 20 # 只看前 20 行
|
|
12
|
+
* node scripts/doc-status.mjs --json # 机器可读
|
|
13
|
+
* node scripts/doc-status.mjs --dirs # 连 docs/*∕ 子目录一起扫
|
|
14
|
+
*
|
|
15
|
+
* 退出码:恒为 0(只报告)。门禁在 check-docs-drift.mjs(R5 规则族)。
|
|
16
|
+
*/
|
|
17
|
+
import { readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs'
|
|
18
|
+
import { join, basename, relative } from 'node:path'
|
|
19
|
+
|
|
20
|
+
const ROOT = new URL('..', import.meta.url).pathname
|
|
21
|
+
const DOCS = join(ROOT, 'docs')
|
|
22
|
+
const args = process.argv.slice(2)
|
|
23
|
+
const LIMIT = args.includes('--limit') ? Number(args[args.indexOf('--limit') + 1]) : 0
|
|
24
|
+
const JSON_OUT = args.includes('--json')
|
|
25
|
+
const WITH_DIRS = !args.includes('--top-only') // 默认递归(排除 archive/)
|
|
26
|
+
const APPLY = args.includes('--apply') // 显式开启才写文件(默认 dry-run)
|
|
27
|
+
|
|
28
|
+
const SUPERSEDED_BY = {
|
|
29
|
+
'docs/分层职责与判断归属.md': 'docs/Argent-宿主适配契约.md', // AGENTS.md:已并入库,只剩指针
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
// 2026-11-02 人工判定(17 篇自动分类判不出来的;改这里再跑 --apply 即可)
|
|
33
|
+
const MANUAL = {
|
|
34
|
+
// 现行:运维/接口/数据口径手册,仍被使用
|
|
35
|
+
'docs/dsh-api-protocol.md': 'current',
|
|
36
|
+
'docs/dsh-client-plugin-pitfalls.md': 'current',
|
|
37
|
+
'docs/full-lip-operational-guide.md': 'current',
|
|
38
|
+
'docs/ml-dev-failure-sop.md': 'current',
|
|
39
|
+
'docs/机器接入Skill-分发说明.md': 'current',
|
|
40
|
+
'docs/美客多日报-数据指标清单.md': 'current',
|
|
41
|
+
'docs/ml-agent-architecture.md': 'current',
|
|
42
|
+
// 历史:方案/评估/路线记录,仅作证据
|
|
43
|
+
'docs/agentic-tools-contract-v1.md': 'historical',
|
|
44
|
+
'docs/Argent-智能体平台-设计.md': 'historical',
|
|
45
|
+
'docs/Argent-陪跑式交付-实施方案.md': 'historical',
|
|
46
|
+
'docs/Argent-许可自助签发与续期-实施方案.md': 'historical',
|
|
47
|
+
'docs/branding-roadmap.md': 'historical',
|
|
48
|
+
'docs/dsh-排程插件评估与迁移设计.md': 'historical',
|
|
49
|
+
'docs/invoice-usage.md': 'historical',
|
|
50
|
+
'docs/策划案-可读性根治与按能力交付与结果计费.md': 'historical',
|
|
51
|
+
'docs/ml-invoice-automation.md': 'historical',
|
|
52
|
+
'docs/内部运维-dsh升级与旧版本清场方案(不属 Argent 产品路径).md': 'historical',
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
const VERSION = readFileSync(join(ROOT, 'VERSION'), 'utf8').trim()
|
|
56
|
+
const CURRENT_MAJOR = VERSION.split('.').slice(0, 2).join('.') // 0.8
|
|
57
|
+
|
|
58
|
+
// ── INDEX 解析 ────────────────────────────────────────────────────────
|
|
59
|
+
const indexText = readFileSync(join(DOCS, 'INDEX.md'), 'utf8')
|
|
60
|
+
const sections = {}
|
|
61
|
+
let cur = null
|
|
62
|
+
for (const line of indexText.split('\n')) {
|
|
63
|
+
const h = line.match(/^##\s+(.*)$/)
|
|
64
|
+
if (h) { cur = h[1].trim(); sections[cur] = []; continue }
|
|
65
|
+
if (cur) sections[cur].push(line)
|
|
66
|
+
}
|
|
67
|
+
const currentLines = sections['当前有效(操作/契约以此为准)'] || []
|
|
68
|
+
const historicalLines = sections['历史文档(仅作证据,不作为当前操作依据)'] || []
|
|
69
|
+
|
|
70
|
+
const currentPaths = new Set()
|
|
71
|
+
for (const line of currentLines) {
|
|
72
|
+
if (!line.startsWith('|')) continue
|
|
73
|
+
for (const m of line.matchAll(/`([^`]+)`/g)) {
|
|
74
|
+
// ⚠️ 只在「空格 + / + 空格」处切分(`docs/release.md` / `docs/xxx.md` 这种一格两项),
|
|
75
|
+
// 否则 `skills/*/SKILL.md` 会被切成 `*` ⇒ 前缀匹配命中一切(2026-11-02 实测踩到)。
|
|
76
|
+
for (const p of m[1].split(/\s+\/\s+/)) currentPaths.add(p.replace(/^\.\//, ''))
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
const historicalPatterns = []
|
|
80
|
+
for (const line of historicalLines) {
|
|
81
|
+
if (!line.startsWith('- ')) continue
|
|
82
|
+
for (const m of line.matchAll(/`([^`]+)`/g)) {
|
|
83
|
+
for (const p of m[1].split(/\s+[·、]\s+/)) {
|
|
84
|
+
const t = p.trim()
|
|
85
|
+
if (t) historicalPatterns.push(t)
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function matches(p, token) {
|
|
91
|
+
if (!token || token === '*' || token.endsWith('/*')) return false
|
|
92
|
+
if (token.endsWith('*')) return basename(p).startsWith(token.slice(0, -1))
|
|
93
|
+
if (token.includes('/')) return p === token || p.endsWith('/' + token)
|
|
94
|
+
return basename(p) === token || basename(p) === token + '.md'
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
// ── 文件扫描 ──────────────────────────────────────────────────────────
|
|
98
|
+
function walk(dir) {
|
|
99
|
+
const out = []
|
|
100
|
+
for (const e of readdirSync(dir)) {
|
|
101
|
+
const p = join(dir, e)
|
|
102
|
+
const st = statSync(p)
|
|
103
|
+
if (st.isDirectory()) { if (WITH_DIRS && e !== 'archive') out.push(...walk(p)); continue }
|
|
104
|
+
if (e.endsWith('.md')) out.push(p)
|
|
105
|
+
}
|
|
106
|
+
return out
|
|
107
|
+
}
|
|
108
|
+
const files = walk(DOCS).filter((f) => basename(f) !== 'INDEX.md')
|
|
109
|
+
|
|
110
|
+
function frontmatter(text) {
|
|
111
|
+
const lines = text.split('\n')
|
|
112
|
+
if (lines[0]?.trim() !== '---') return null
|
|
113
|
+
const end = lines.indexOf('---', 1)
|
|
114
|
+
if (end < 0) return null
|
|
115
|
+
const fm = {}
|
|
116
|
+
for (const l of lines.slice(1, end)) {
|
|
117
|
+
const m = l.match(/^([A-Za-z]+):\s*(.*)$/)
|
|
118
|
+
if (m) fm[m[1]] = m[2].trim()
|
|
119
|
+
}
|
|
120
|
+
return fm
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
// 现行引用面:INDEX 的"当前有效"文档正文 + 新会话真正读的入口(AGENTS/WORKSPACE)
|
|
124
|
+
const corpus = [
|
|
125
|
+
...[...currentPaths]
|
|
126
|
+
.filter((x) => x.startsWith('docs/') && x.endsWith('.md'))
|
|
127
|
+
.map((x) => join(ROOT, x)),
|
|
128
|
+
join(process.env.HOME || '', '.dsh', 'AGENTS.md'),
|
|
129
|
+
join(ROOT, '..', 'WORKSPACE.md'),
|
|
130
|
+
]
|
|
131
|
+
.map((f) => { try { return readFileSync(f, 'utf8') } catch { return '' } })
|
|
132
|
+
.join('\n')
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
const rows = []
|
|
136
|
+
for (const f of files) {
|
|
137
|
+
const rel = relative(ROOT, f).split('\\').join('/')
|
|
138
|
+
const text = readFileSync(f, 'utf8')
|
|
139
|
+
const fm = frontmatter(text)
|
|
140
|
+
const head = text.split('\n').slice(0, 6).join('\n')
|
|
141
|
+
const hasBanner = /历史文档|已归档|⛔\s*\*\*本文|superseded/i.test(head)
|
|
142
|
+
const name = basename(f)
|
|
143
|
+
const verMatch = name.match(/-(0\.\d)(?:\.\d)?-/)
|
|
144
|
+
const hasDate = /20\d{2}-\d{2}-\d{2}/.test(name)
|
|
145
|
+
const inCurrent = [...currentPaths].some((p) => matches(rel, p))
|
|
146
|
+
const inHistorical = historicalPatterns.some((p) => matches(rel, p))
|
|
147
|
+
|
|
148
|
+
let status, why, risk = ''
|
|
149
|
+
if (fm?.status) { status = fm.status; why = '已有 frontmatter' }
|
|
150
|
+
else if (inCurrent) { status = 'current'; why = 'INDEX「当前有效」' }
|
|
151
|
+
else if (hasBanner) { status = 'historical'; why = '已有历史横幅' }
|
|
152
|
+
else if (inHistorical) { status = 'historical'; why = 'INDEX「历史文档」' }
|
|
153
|
+
else if (/^release-/.test(name)) { status = 'historical'; why = '发布记录(事件)'; risk = '不取代任何文档' }
|
|
154
|
+
else if (MANUAL[rel]) { status = MANUAL[rel]; why = '人工判定(2026-11-02)' }
|
|
155
|
+
else if (rel.startsWith('docs/ops/')) { status = 'historical'; why = '运维事件记录(证据)' }
|
|
156
|
+
else if (rel.startsWith('docs/releases/')) { status = 'current'; why = '版本索引页' }
|
|
157
|
+
else if (rel.startsWith('docs/samples/')) { status = 'current'; why = '对外样例(脱敏)' }
|
|
158
|
+
else if (SUPERSEDED_BY[rel]) { status = 'superseded'; why = '已并入其他文档(人工确认)' }
|
|
159
|
+
else if (verMatch && verMatch[1] !== CURRENT_MAJOR) { status = 'historical'; why = `旧版本线 ${verMatch[1]}`; risk = '建议人工确认是否 superseded' }
|
|
160
|
+
else if (hasDate) { status = 'historical'; why = '时间型记录'; risk = '建议人工确认' }
|
|
161
|
+
else if (corpus.includes(name)) { status = 'current'; why = '被现行文档引用'; risk = '建议人工确认' }
|
|
162
|
+
else { status = 'needs-review'; why = '未命中任何规则,也无人引用'; risk = '需人工判定' }
|
|
163
|
+
|
|
164
|
+
rows.push({
|
|
165
|
+
file: rel, status, why, risk,
|
|
166
|
+
frontmatter: fm ? 'yes' : 'no',
|
|
167
|
+
hasAppliesTo: Boolean(fm?.appliesTo),
|
|
168
|
+
})
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
// ── apply(仅 --apply)──────────────────────────────────────────────
|
|
172
|
+
if (APPLY) {
|
|
173
|
+
let written = 0
|
|
174
|
+
for (const r of rows) {
|
|
175
|
+
if (r.frontmatter === 'yes') continue
|
|
176
|
+
// ⛔ 不替人做决定:needs-review 不写(留给人工判定,门禁会点名)
|
|
177
|
+
if (r.status === 'needs-review') continue
|
|
178
|
+
const abs = join(ROOT, r.file)
|
|
179
|
+
const text = readFileSync(abs, 'utf8')
|
|
180
|
+
const ver = r.file.match(/-(0\.\d)(?:\.\d)?-/)
|
|
181
|
+
const fm = [
|
|
182
|
+
'---',
|
|
183
|
+
`status: ${r.status === 'needs-review' ? 'draft' : r.status}`,
|
|
184
|
+
`appliesTo: ${ver ? `argent ${ver[1]}.x` : '—'}`,
|
|
185
|
+
...(r.status === 'superseded' ? [`supersededBy: ${SUPERSEDED_BY[r.file]}`] : []),
|
|
186
|
+
'updated: 2026-11-02',
|
|
187
|
+
'---',
|
|
188
|
+
'',
|
|
189
|
+
].join('\n')
|
|
190
|
+
writeFileSync(abs, fm + text)
|
|
191
|
+
written++
|
|
192
|
+
}
|
|
193
|
+
console.log(`已写入 frontmatter:${written} 篇(其余已有,跳过)`)
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
// ── 输出 ──────────────────────────────────────────────────────────────
|
|
197
|
+
const order = { current: 0, 'needs-review': 1, superseded: 2, historical: 3, draft: 4 }
|
|
198
|
+
rows.sort((a, b) => (order[a.status] ?? 9) - (order[b.status] ?? 9) || a.file.localeCompare(b.file))
|
|
199
|
+
const counts = rows.reduce((m, r) => ((m[r.status] = (m[r.status] || 0) + 1), m), {})
|
|
200
|
+
|
|
201
|
+
if (JSON_OUT) {
|
|
202
|
+
console.log(JSON.stringify({ version: VERSION, counts, rows }, null, 2))
|
|
203
|
+
} else {
|
|
204
|
+
console.log(`doc-status —— 文档状态体检(dry-run,不写文件)`)
|
|
205
|
+
console.log(` 当前 VERSION: ${VERSION} 扫描: ${rows.length} 篇 frontmatter 覆盖: ${rows.filter((r) => r.frontmatter === 'yes').length}/${rows.length}`)
|
|
206
|
+
console.log(` 候选分布: ${Object.entries(counts).map(([k, v]) => `${k}=${v}`).join(' ')}`)
|
|
207
|
+
console.log('')
|
|
208
|
+
console.log(['STATUS', 'FILE', 'WHY', 'RISK'].join('\t'))
|
|
209
|
+
const show = LIMIT > 0 ? rows.slice(0, LIMIT) : rows
|
|
210
|
+
for (const r of show) console.log([r.status, r.file, r.why, r.risk].join('\t'))
|
|
211
|
+
if (LIMIT > 0 && rows.length > LIMIT) console.log(`... 还有 ${rows.length - LIMIT} 篇(用 --limit 0 看全部)`)
|
|
212
|
+
}
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
"""发票写回 shadow:把「准备写到 lip 的字段/附件」映射成 ERP 契约并落 JSONL。
|
|
2
|
+
|
|
3
|
+
⛔ 本模块**不调用 ERP 写接口**、**不改客户状态**;只供 invoice_lip_runner 在
|
|
4
|
+
ARGENT_WRITEBACK=shadow 时记录“如果切 ERP 会写什么”,用于和 lip 结果比对。
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import json
|
|
9
|
+
import os
|
|
10
|
+
import time
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
FIELD_MAP = {
|
|
14
|
+
'发票状态': 'invoiceStatus',
|
|
15
|
+
'发票错误信息': 'invoiceError',
|
|
16
|
+
'发票就绪': 'invoiceReady',
|
|
17
|
+
}
|
|
18
|
+
ATTACHMENT_MAP = {
|
|
19
|
+
'发票文件': 'invoiceFile',
|
|
20
|
+
'大货标签': 'bulkLabel',
|
|
21
|
+
'产品图': 'productImage',
|
|
22
|
+
'FULL标签文件': 'fullLabelFile',
|
|
23
|
+
'FULL箱唛文件': 'fullCartonFile',
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def to_erp_fields(patch: dict) -> tuple[dict, list]:
|
|
28
|
+
"""lip 中文 patch → ERP 字段;返回 (erp_fields, skipped)。"""
|
|
29
|
+
fields: dict = {}
|
|
30
|
+
skipped: list = []
|
|
31
|
+
for key, value in (patch or {}).items():
|
|
32
|
+
target = FIELD_MAP.get(key)
|
|
33
|
+
if target:
|
|
34
|
+
fields[target] = value
|
|
35
|
+
else:
|
|
36
|
+
skipped.append(key)
|
|
37
|
+
return fields, skipped
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def shadow_record(rids, patch=None, source: str = 'lip_update', attachments=None) -> dict:
|
|
41
|
+
fields, skipped = to_erp_fields(patch or {})
|
|
42
|
+
return {
|
|
43
|
+
'ts': time.strftime('%Y-%m-%dT%H:%M:%S'),
|
|
44
|
+
'mode': 'shadow',
|
|
45
|
+
'source': source,
|
|
46
|
+
'records': [str(x) for x in (rids or [])],
|
|
47
|
+
'erpFields': fields,
|
|
48
|
+
'skippedFields': skipped,
|
|
49
|
+
'attachments': [
|
|
50
|
+
{'field': ATTACHMENT_MAP.get(a.get('field'), a.get('field')), 'filename': a.get('filename', '')}
|
|
51
|
+
for a in (attachments or [])
|
|
52
|
+
],
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def append_shadow(record: dict, data_dir=None) -> Path:
|
|
57
|
+
base = Path(data_dir) if data_dir else Path(os.environ.get('ARGENT_DATA_DIR') or (Path.home() / '.dsh' / 'argent'))
|
|
58
|
+
path = base / 'invoice-lip-writes' / 'erp-shadow.jsonl'
|
|
59
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
60
|
+
with path.open('a', encoding='utf-8') as fh:
|
|
61
|
+
fh.write(json.dumps(record, ensure_ascii=False) + '\n')
|
|
62
|
+
return path
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
"""发票写回 ERP(ARGENT_WRITEBACK=erp):字段 + 附件引用。
|
|
2
|
+
|
|
3
|
+
⛔ 不打印 token;附件走 machine 上传端点(≤2MB),再把 attachment `_id` 同时作为
|
|
4
|
+
fileToken/attachmentId 传给 /agent-tasks/invoice-finalize(attachInvoiceFile 幂等)。
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import base64
|
|
9
|
+
import json
|
|
10
|
+
import mimetypes
|
|
11
|
+
import os
|
|
12
|
+
import urllib.error
|
|
13
|
+
import urllib.request
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
|
|
16
|
+
from erp_invoice_shadow import ATTACHMENT_MAP, to_erp_fields
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _config() -> dict:
|
|
20
|
+
env = os.environ
|
|
21
|
+
candidates = []
|
|
22
|
+
if env.get('ARGENT_AGENT_REPORT'):
|
|
23
|
+
candidates.append(Path(env['ARGENT_AGENT_REPORT']))
|
|
24
|
+
data_dir = Path(env.get('ARGENT_DATA_DIR') or (Path.home() / '.dsh' / 'argent'))
|
|
25
|
+
candidates += [data_dir / 'agent-report.json', Path.home() / '.dsh-argent' / 'argent' / 'agent-report.json']
|
|
26
|
+
for f in candidates:
|
|
27
|
+
try:
|
|
28
|
+
d = json.loads(f.read_text())
|
|
29
|
+
if d.get('serverUrl') and d.get('tenantAppId') and d.get('machineId') and d.get('machineToken'):
|
|
30
|
+
return d
|
|
31
|
+
except Exception:
|
|
32
|
+
continue
|
|
33
|
+
raise RuntimeError('ERP 写回:找不到 agent-report.json(serverUrl/tenantAppId/machineId/machineToken)')
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _post(path: str, body: dict) -> tuple[int, dict]:
|
|
37
|
+
cfg = _config()
|
|
38
|
+
url = f"{str(cfg['serverUrl']).rstrip('/')}{path}"
|
|
39
|
+
req = urllib.request.Request(url, data=json.dumps(body, ensure_ascii=False).encode('utf-8'), method='POST',
|
|
40
|
+
headers={'content-type': 'application/json', 'authorization': f"Bearer {cfg['machineToken']}"})
|
|
41
|
+
try:
|
|
42
|
+
with urllib.request.urlopen(req, timeout=60) as resp:
|
|
43
|
+
raw = resp.read().decode('utf-8', errors='replace')
|
|
44
|
+
return resp.status, (json.loads(raw) if raw else {})
|
|
45
|
+
except urllib.error.HTTPError as e:
|
|
46
|
+
raw = e.read().decode('utf-8', errors='replace')
|
|
47
|
+
try:
|
|
48
|
+
return e.code, json.loads(raw)
|
|
49
|
+
except Exception:
|
|
50
|
+
return e.code, {'ok': False, 'error': {'code': 'http_error', 'message': raw[:500]}}
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def upload_attachment(path) -> dict:
|
|
54
|
+
p = Path(path)
|
|
55
|
+
data = base64.b64encode(p.read_bytes()).decode('ascii')
|
|
56
|
+
mime = mimetypes.guess_type(p.name)[0] or 'application/octet-stream'
|
|
57
|
+
cfg = _config()
|
|
58
|
+
status, doc = _post(f"/api/argent/v1/tenants/{cfg['tenantAppId']}/machines/{cfg['machineId']}/attachments", {
|
|
59
|
+
'filename': p.name, 'mime': mime, 'dataBase64': data, 'kind': 'invoice-file',
|
|
60
|
+
})
|
|
61
|
+
att = (doc.get('data') or {}).get('attachment') or {}
|
|
62
|
+
if not doc.get('ok') or not att.get('_id'):
|
|
63
|
+
raise RuntimeError(f"ERP 附件上传失败(HTTP {status}):{(doc.get('error') or {}).get('message') or doc}")
|
|
64
|
+
return {
|
|
65
|
+
'attachmentId': str(att['_id']), 'fileToken': str(att['_id']),
|
|
66
|
+
'filename': att.get('filename') or p.name, 'mime': att.get('mime') or mime,
|
|
67
|
+
'size': att.get('size') if isinstance(att.get('size'), int) else p.stat().st_size,
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def finalize(record_id: str, fields: dict, attachments: list) -> bool:
|
|
72
|
+
cfg = _config()
|
|
73
|
+
body = {'sourceRecordId': str(record_id), 'fields': fields or {}, 'attachments': attachments or []}
|
|
74
|
+
status, doc = _post(f"/api/argent/v1/tenants/{cfg['tenantAppId']}/machines/{cfg['machineId']}/agent-tasks/invoice-finalize", body)
|
|
75
|
+
return bool(doc.get('ok')), status, doc
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def write_fields(rids, patch) -> bool:
|
|
79
|
+
fields, _skipped = to_erp_fields(patch or {})
|
|
80
|
+
if not fields:
|
|
81
|
+
return True
|
|
82
|
+
for rid in rids or []:
|
|
83
|
+
ok, _status, _doc = finalize(rid, fields, [])
|
|
84
|
+
if not ok:
|
|
85
|
+
return False
|
|
86
|
+
return True
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def upload_and_finalize(rid, field, path) -> bool:
|
|
90
|
+
att = upload_attachment(path)
|
|
91
|
+
erp_field = ATTACHMENT_MAP.get(field, field)
|
|
92
|
+
ok, _status, _doc = finalize(rid, {}, [{**att, 'field': erp_field}])
|
|
93
|
+
return ok
|