From e5df708e4a6ef85ab04e148dc02811b23f0275ce Mon Sep 17 00:00:00 2001 From: Christ Date: Fri, 14 Aug 2026 23:06:26 +0800 Subject: [PATCH] =?UTF-8?q?=E9=98=B6=E6=AE=B5=E5=85=AD=EF=BC=9A=E6=94=B6?= =?UTF-8?q?=E5=8F=A3Automation=E5=8F=91=E8=B4=A7=E5=8D=A1=E5=AF=86?= =?UTF-8?q?=E4=B8=8E=E9=80=9A=E7=9F=A5=E5=8A=A8=E4=BD=9C=E8=BE=B9=E7=95=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .commentlint/go-baseline.json | 1312 ++++++------------ docs/architecture/refactoring-master-plan.md | 4 +- internal/automation/action_executor.go | 464 +++++++ internal/automation/action_executor_test.go | 27 + internal/automation/center.go | 426 +----- internal/automation/delivery_notifier.go | 60 + 6 files changed, 1067 insertions(+), 1226 deletions(-) create mode 100644 internal/automation/action_executor.go create mode 100644 internal/automation/action_executor_test.go create mode 100644 internal/automation/delivery_notifier.go diff --git a/.commentlint/go-baseline.json b/.commentlint/go-baseline.json index 71ddb36..5e62ada 100644 --- a/.commentlint/go-baseline.json +++ b/.commentlint/go-baseline.json @@ -9137,1176 +9137,780 @@ "kind": "local-variable", "name": "settings" }, + { + "file": "internal/automation/action_executor.go", + "line": 72, + "kind": "local-variable", + "name": "enabled" + }, + { + "file": "internal/automation/action_executor.go", + "line": 72, + "kind": "local-variable", + "name": "readErr" + }, + { + "file": "internal/automation/action_executor.go", + "line": 111, + "kind": "local-variable", + "name": "snapshot" + }, + { + "file": "internal/automation/action_executor.go", + "line": 111, + "kind": "local-variable", + "name": "snapshotOK" + }, + { + "file": "internal/automation/action_executor.go", + "line": 124, + "kind": "local-variable", + "name": "callErr" + }, + { + "file": "internal/automation/action_executor.go", + "line": 124, + "kind": "local-variable", + "name": "consignOK" + }, + { + "file": "internal/automation/action_executor.go", + "line": 124, + "kind": "local-variable", + "name": "ret" + }, + { + "file": "internal/automation/action_executor.go", + "line": 124, + "kind": "local-variable", + "name": "updated" + }, + { + "file": "internal/automation/action_executor.go", + "line": 134, + "kind": "local-variable", + "name": "changed" + }, + { + "file": "internal/automation/action_executor.go", + "line": 134, + "kind": "local-variable", + "name": "snapshot" + }, + { + "file": "internal/automation/action_executor.go", + "line": 134, + "kind": "local-variable", + "name": "value" + }, + { + "file": "internal/automation/action_executor.go", + "line": 167, + "kind": "local-variable", + "name": "running" + }, + { + "file": "internal/automation/action_executor.go", + "line": 167, + "kind": "local-variable", + "name": "sender" + }, + { + "file": "internal/automation/action_executor.go", + "line": 258, + "kind": "local-variable", + "name": "content" + }, + { + "file": "internal/automation/action_executor.go", + "line": 258, + "kind": "local-variable", + "name": "imageURL" + }, + { + "file": "internal/automation/action_executor.go", + "line": 258, + "kind": "local-variable", + "name": "readErr" + }, + { + "file": "internal/automation/action_executor.go", + "line": 325, + "kind": "local-variable", + "name": "sender" + }, + { + "file": "internal/automation/action_executor.go", + "line": 325, + "kind": "local-variable", + "name": "senderOK" + }, + { + "file": "internal/automation/action_executor.go", + "line": 342, + "kind": "local-variable", + "name": "sender" + }, + { + "file": "internal/automation/action_executor.go", + "line": 342, + "kind": "local-variable", + "name": "senderOK" + }, + { + "file": "internal/automation/action_executor.go", + "line": 428, + "kind": "local-variable", + "name": "n" + }, + { + "file": "internal/automation/action_executor.go", + "line": 428, + "kind": "local-variable", + "name": "parseErr" + }, { "file": "internal/automation/center.go", - "line": 20, + "line": 19, "kind": "var", "name": "errAutomationDeferred" }, { "file": "internal/automation/center.go", - "line": 21, + "line": 20, "kind": "var", "name": "errAutomationNeedsReview" }, { "file": "internal/automation/center.go", - "line": 22, + "line": 21, "kind": "var", "name": "errAutomationQuarantine" }, { "file": "internal/automation/center.go", - "line": 23, + "line": 22, "kind": "var", "name": "errActionNotPerformed" }, { "file": "internal/automation/center.go", - "line": 27, + "line": 26, "kind": "var", "name": "ErrMessageNotSent" }, { "file": "internal/automation/center.go", - "line": 30, + "line": 29, "kind": "type", "name": "preparationError" }, { "file": "internal/automation/center.go", - "line": 32, + "line": 31, "kind": "function", "name": "Error" }, { "file": "internal/automation/center.go", - "line": 33, + "line": 32, "kind": "function", "name": "Unwrap" }, { "file": "internal/automation/center.go", - "line": 35, + "line": 34, "kind": "type", "name": "uncertainActionError" }, { "file": "internal/automation/center.go", - "line": 37, + "line": 36, "kind": "function", "name": "Error" }, { "file": "internal/automation/center.go", - "line": 38, + "line": 37, "kind": "function", "name": "Unwrap" }, { "file": "internal/automation/center.go", - "line": 40, + "line": 39, "kind": "function", "name": "uncertainAction" }, { "file": "internal/automation/center.go", - "line": 44, + "line": 43, "kind": "var", "name": "existing" }, { "file": "internal/automation/center.go", - "line": 53, + "line": 52, "kind": "type", "name": "SenderProvider" }, { "file": "internal/automation/center.go", - "line": 66, + "line": 65, "kind": "type", "name": "automationReadySender" }, { "file": "internal/automation/center.go", - "line": 72, + "line": 71, "kind": "type", "name": "OrderDetailFetcher" }, { "file": "internal/automation/center.go", - "line": 88, + "line": 87, "kind": "type", "name": "Center" }, { "file": "internal/automation/center.go", - "line": 117, + "line": 119, "kind": "local-variable", "name": "client" }, { "file": "internal/automation/center.go", - "line": 118, + "line": 120, "kind": "local-variable", "name": "center" }, { "file": "internal/automation/center.go", - "line": 147, + "line": 172, "kind": "function", "name": "SetAccountTaskClient" }, { "file": "internal/automation/center.go", - "line": 152, + "line": 177, "kind": "local-variable", "name": "ok" }, { "file": "internal/automation/center.go", - "line": 152, + "line": 177, "kind": "local-variable", "name": "recoverer" }, { "file": "internal/automation/center.go", - "line": 169, + "line": 194, "kind": "local-variable", "name": "err" }, { "file": "internal/automation/center.go", - "line": 173, + "line": 198, "kind": "function", "name": "handleTask" }, { "file": "internal/automation/center.go", - "line": 181, + "line": 206, "kind": "local-variable", "name": "err" }, { "file": "internal/automation/center.go", - "line": 185, + "line": 210, "kind": "local-variable", "name": "order" }, { "file": "internal/automation/center.go", - "line": 185, + "line": 210, "kind": "local-variable", "name": "orderErr" }, { "file": "internal/automation/center.go", - "line": 191, + "line": 216, "kind": "local-variable", "name": "err" }, { "file": "internal/automation/center.go", - "line": 191, + "line": 216, "kind": "local-variable", "name": "paused" }, { "file": "internal/automation/center.go", - "line": 191, + "line": 216, "kind": "local-variable", "name": "until" }, { "file": "internal/automation/center.go", - "line": 196, + "line": 221, "kind": "local-variable", "name": "err" }, { "file": "internal/automation/center.go", - "line": 202, + "line": 227, "kind": "local-variable", "name": "enabled" }, { "file": "internal/automation/center.go", - "line": 202, + "line": 227, "kind": "local-variable", "name": "err" }, { "file": "internal/automation/center.go", - "line": 210, + "line": 235, "kind": "local-variable", "name": "err" }, { "file": "internal/automation/center.go", - "line": 210, + "line": 235, "kind": "local-variable", "name": "rules" }, { "file": "internal/automation/center.go", - "line": 218, + "line": 243, "kind": "var", "name": "firstErr" }, { "file": "internal/automation/center.go", - "line": 219, + "line": 244, "kind": "range-variable", "name": "rule" }, { "file": "internal/automation/center.go", - "line": 220, + "line": 245, "kind": "local-variable", "name": "err" }, { "file": "internal/automation/center.go", - "line": 221, + "line": 246, "kind": "var", "name": "prepErr" }, { "file": "internal/automation/center.go", - "line": 223, + "line": 248, "kind": "local-variable", "name": "dueAt" }, { "file": "internal/automation/center.go", - "line": 224, + "line": 249, "kind": "local-variable", "name": "deferErr" }, { "file": "internal/automation/center.go", - "line": 243, + "line": 268, "kind": "function", "name": "taskAutomationRunID" }, - { - "file": "internal/automation/center.go", - "line": 247, - "kind": "local-variable", - "name": "value" - }, - { - "file": "internal/automation/center.go", - "line": 248, - "kind": "local-variable", - "name": "id" - }, - { - "file": "internal/automation/center.go", - "line": 252, - "kind": "function", - "name": "taskDelayCursor" - }, - { - "file": "internal/automation/center.go", - "line": 256, - "kind": "local-variable", - "name": "value" - }, - { - "file": "internal/automation/center.go", - "line": 257, - "kind": "local-variable", - "name": "cursor" - }, - { - "file": "internal/automation/center.go", - "line": 257, - "kind": "local-variable", - "name": "err" - }, - { - "file": "internal/automation/center.go", - "line": 264, - "kind": "function", - "name": "isDeferredReplay" - }, - { - "file": "internal/automation/center.go", - "line": 268, - "kind": "function", - "name": "deferTask" - }, { "file": "internal/automation/center.go", "line": 272, - "kind": "function", - "name": "deferTaskWithError" + "kind": "local-variable", + "name": "value" }, { "file": "internal/automation/center.go", "line": 273, "kind": "local-variable", - "name": "key" + "name": "id" }, { "file": "internal/automation/center.go", - "line": 278, - "kind": "local-variable", - "name": "err" - }, - { - "file": "internal/automation/center.go", - "line": 278, - "kind": "local-variable", - "name": "raw" - }, - { - "file": "internal/automation/center.go", - "line": 290, + "line": 277, "kind": "function", - "name": "ManualFullDelivery" + "name": "taskDelayCursor" }, { "file": "internal/automation/center.go", - "line": 297, - "kind": "local-variable", - "name": "err" - }, - { - "file": "internal/automation/center.go", - "line": 297, - "kind": "local-variable", - "name": "paused" - }, - { - "file": "internal/automation/center.go", - "line": 297, - "kind": "local-variable", - "name": "until" - }, - { - "file": "internal/automation/center.go", - "line": 304, - "kind": "local-variable", - "name": "enabled" - }, - { - "file": "internal/automation/center.go", - "line": 304, - "kind": "local-variable", - "name": "err" - }, - { - "file": "internal/automation/center.go", - "line": 320, - "kind": "local-variable", - "name": "task" - }, - { - "file": "internal/automation/center.go", - "line": 340, - "kind": "local-variable", - "name": "err" - }, - { - "file": "internal/automation/center.go", - "line": 340, - "kind": "local-variable", - "name": "rules" - }, - { - "file": "internal/automation/center.go", - "line": 347, - "kind": "local-variable", - "name": "sent" - }, - { - "file": "internal/automation/center.go", - "line": 348, - "kind": "range-variable", - "name": "rule" - }, - { - "file": "internal/automation/center.go", - "line": 353, - "kind": "local-variable", - "name": "rawTask" - }, - { - "file": "internal/automation/center.go", - "line": 355, - "kind": "local-variable", - "name": "rawJSON" - }, - { - "file": "internal/automation/center.go", - "line": 356, - "kind": "local-variable", - "name": "runID" - }, - { - "file": "internal/automation/center.go", - "line": 356, - "kind": "local-variable", - "name": "startErr" - }, - { - "file": "internal/automation/center.go", - "line": 356, - "kind": "local-variable", - "name": "started" - }, - { - "file": "internal/automation/center.go", - "line": 374, - "kind": "local-variable", - "name": "getErr" - }, - { - "file": "internal/automation/center.go", - "line": 374, - "kind": "local-variable", - "name": "run" - }, - { - "file": "internal/automation/center.go", - "line": 378, - "kind": "local-variable", - "name": "deferred" - }, - { - "file": "internal/automation/center.go", - "line": 378, - "kind": "local-variable", - "name": "err" - }, - { - "file": "internal/automation/center.go", - "line": 378, - "kind": "local-variable", - "name": "n" - }, - { - "file": "internal/automation/center.go", - "line": 386, - "kind": "local-variable", - "name": "errMsg" - }, - { - "file": "internal/automation/center.go", - "line": 386, - "kind": "local-variable", - "name": "status" - }, - { - "file": "internal/automation/center.go", - "line": 390, - "kind": "local-variable", - "name": "cancel" - }, - { - "file": "internal/automation/center.go", - "line": 390, - "kind": "local-variable", - "name": "finishCtx" - }, - { - "file": "internal/automation/center.go", - "line": 391, - "kind": "local-variable", - "name": "finishErr" - }, - { - "file": "internal/automation/center.go", - "line": 421, - "kind": "function", - "name": "notifyResult" - }, - { - "file": "internal/automation/center.go", - "line": 422, - "kind": "local-variable", - "name": "triggerName" - }, - { - "file": "internal/automation/center.go", - "line": 434, - "kind": "local-variable", - "name": "msg" - }, - { - "file": "internal/automation/center.go", - "line": 438, - "kind": "local-variable", - "name": "msg" - }, - { - "file": "internal/automation/center.go", - "line": 442, - "kind": "function", - "name": "notifyRunNeedsReview" - }, - { - "file": "internal/automation/center.go", - "line": 446, - "kind": "local-variable", - "name": "task" - }, - { - "file": "internal/automation/center.go", - "line": 452, - "kind": "function", - "name": "actionDelaySeconds" - }, - { - "file": "internal/automation/center.go", - "line": 456, - "kind": "var", - "name": "cfg" - }, - { - "file": "internal/automation/center.go", - "line": 460, - "kind": "local-variable", - "name": "card" - }, - { - "file": "internal/automation/center.go", - "line": 460, - "kind": "local-variable", - "name": "err" - }, - { - "file": "internal/automation/center.go", - "line": 473, - "kind": "function", - "name": "prepareTask" - }, - { - "file": "internal/automation/center.go", - "line": 483, - "kind": "local-variable", - "name": "needsDetail" - }, - { - "file": "internal/automation/center.go", - "line": 484, - "kind": "local-variable", - "name": "err" - }, - { - "file": "internal/automation/center.go", - "line": 484, - "kind": "local-variable", - "name": "existing" - }, - { - "file": "internal/automation/center.go", - "line": 498, - "kind": "local-variable", - "name": "cookieStr" - }, - { - "file": "internal/automation/center.go", - "line": 500, - "kind": "var", - "name": "err" - }, - { - "file": "internal/automation/center.go", - "line": 506, - "kind": "local-variable", - "name": "detail" - }, - { - "file": "internal/automation/center.go", - "line": 506, - "kind": "local-variable", - "name": "err" - }, - { - "file": "internal/automation/center.go", - "line": 542, - "kind": "function", - "name": "mergeOrderIntoTask" - }, - { - "file": "internal/automation/center.go", - "line": 570, - "kind": "function", - "name": "executeAction" - }, - { - "file": "internal/automation/center.go", - "line": 577, - "kind": "local-variable", - "name": "text" - }, - { - "file": "internal/automation/center.go", - "line": 581, - "kind": "local-variable", - "name": "err" - }, - { - "file": "internal/automation/center.go", - "line": 593, - "kind": "function", - "name": "confirmShipment" - }, - { - "file": "internal/automation/center.go", - "line": 597, - "kind": "local-variable", - "name": "enabled" - }, - { - "file": "internal/automation/center.go", - "line": 597, - "kind": "local-variable", - "name": "err" - }, - { - "file": "internal/automation/center.go", - "line": 607, - "kind": "function", - "name": "confirmShipmentAttempt" - }, - { - "file": "internal/automation/center.go", - "line": 608, - "kind": "local-variable", - "name": "credentialUnlock" - }, - { - "file": "internal/automation/center.go", - "line": 609, - "kind": "local-variable", - "name": "credentialLocked" - }, - { - "file": "internal/automation/center.go", - "line": 622, - "kind": "local-variable", - "name": "completeSnapshot" - }, - { - "file": "internal/automation/center.go", - "line": 626, - "kind": "local-variable", - "name": "cookieStr" - }, - { - "file": "internal/automation/center.go", - "line": 627, - "kind": "var", - "name": "mtopCtx" - }, - { - "file": "internal/automation/center.go", - "line": 628, - "kind": "var", - "name": "cookieSession" - }, - { - "file": "internal/automation/center.go", - "line": 629, - "kind": "local-variable", - "name": "ok" - }, - { - "file": "internal/automation/center.go", - "line": 629, - "kind": "local-variable", - "name": "snapshot" - }, - { - "file": "internal/automation/center.go", - "line": 634, - "kind": "local-variable", - "name": "callErr" - }, - { - "file": "internal/automation/center.go", - "line": 634, - "kind": "local-variable", - "name": "ok" - }, - { - "file": "internal/automation/center.go", - "line": 634, - "kind": "local-variable", - "name": "ret" - }, - { - "file": "internal/automation/center.go", - "line": 634, - "kind": "local-variable", - "name": "updated" - }, - { - "file": "internal/automation/center.go", - "line": 635, - "kind": "var", - "name": "persistenceErrs" - }, - { - "file": "internal/automation/center.go", - "line": 636, - "kind": "local-variable", - "name": "runtimeCookie" - }, - { - "file": "internal/automation/center.go", - "line": 637, - "kind": "local-variable", - "name": "runtimeCookieChanged" - }, - { - "file": "internal/automation/center.go", - "line": 638, - "kind": "local-variable", - "name": "changed" - }, - { - "file": "internal/automation/center.go", - "line": 638, - "kind": "local-variable", - "name": "snapshot" - }, - { - "file": "internal/automation/center.go", - "line": 638, + "line": 281, "kind": "local-variable", "name": "value" }, { "file": "internal/automation/center.go", - "line": 641, + "line": 282, "kind": "local-variable", - "name": "sessionHandled" + "name": "cursor" }, { "file": "internal/automation/center.go", - "line": 643, + "line": 282, "kind": "local-variable", - "name": "metadata" + "name": "err" }, { "file": "internal/automation/center.go", - "line": 647, - "kind": "local-variable", - "name": "saveErr" - }, - { - "file": "internal/automation/center.go", - "line": 658, - "kind": "local-variable", - "name": "metadata" - }, - { - "file": "internal/automation/center.go", - "line": 659, - "kind": "local-variable", - "name": "saveErr" - }, - { - "file": "internal/automation/center.go", - "line": 669, - "kind": "local-variable", - "name": "running" - }, - { - "file": "internal/automation/center.go", - "line": 669, - "kind": "local-variable", - "name": "sender" - }, - { - "file": "internal/automation/center.go", - "line": 676, - "kind": "local-variable", - "name": "sessionErr" - }, - { - "file": "internal/automation/center.go", - "line": 700, - "kind": "local-variable", - "name": "failure" - }, - { - "file": "internal/automation/center.go", - "line": 706, - "kind": "local-variable", - "name": "sysShip" - }, - { - "file": "internal/automation/center.go", - "line": 707, - "kind": "local-variable", - "name": "upsertErr" - }, - { - "file": "internal/automation/center.go", - "line": 717, - "kind": "local-variable", - "name": "eventErr" - }, - { - "file": "internal/automation/center.go", - "line": 726, + "line": 289, "kind": "function", - "name": "wakeCredentialBlockedAutomation" + "name": "isDeferredReplay" }, { "file": "internal/automation/center.go", - "line": 730, - "kind": "local-variable", - "name": "err" - }, - { - "file": "internal/automation/center.go", - "line": 735, + "line": 293, "kind": "function", - "name": "sendCard" + "name": "deferTask" }, { "file": "internal/automation/center.go", - "line": 742, - "kind": "local-variable", - "name": "count" - }, - { - "file": "internal/automation/center.go", - "line": 743, - "kind": "local-variable", - "name": "card" - }, - { - "file": "internal/automation/center.go", - "line": 743, - "kind": "local-variable", - "name": "err" - }, - { - "file": "internal/automation/center.go", - "line": 753, - "kind": "local-variable", - "name": "sent" - }, - { - "file": "internal/automation/center.go", - "line": 754, - "kind": "local-variable", - "name": "i" - }, - { - "file": "internal/automation/center.go", - "line": 755, - "kind": "local-variable", - "name": "content" - }, - { - "file": "internal/automation/center.go", - "line": 755, - "kind": "local-variable", - "name": "err" - }, - { - "file": "internal/automation/center.go", - "line": 755, - "kind": "local-variable", - "name": "imageURL" - }, - { - "file": "internal/automation/center.go", - "line": 760, - "kind": "local-variable", - "name": "err" - }, - { - "file": "internal/automation/center.go", - "line": 765, - "kind": "local-variable", - "name": "err" - }, - { - "file": "internal/automation/center.go", - "line": 777, + "line": 297, "kind": "function", - "name": "sendDataCard" + "name": "deferTaskWithError" }, { "file": "internal/automation/center.go", - "line": 778, + "line": 298, "kind": "local-variable", - "name": "unlock" + "name": "key" }, { "file": "internal/automation/center.go", - "line": 780, - "kind": "local-variable", - "name": "sent" - }, - { - "file": "internal/automation/center.go", - "line": 781, - "kind": "local-variable", - "name": "i" - }, - { - "file": "internal/automation/center.go", - "line": 782, - "kind": "local-variable", - "name": "content" - }, - { - "file": "internal/automation/center.go", - "line": 782, + "line": 303, "kind": "local-variable", "name": "err" }, { "file": "internal/automation/center.go", - "line": 787, - "kind": "local-variable", - "name": "err" - }, - { - "file": "internal/automation/center.go", - "line": 789, - "kind": "local-variable", - "name": "restoreErr" - }, - { - "file": "internal/automation/center.go", - "line": 803, - "kind": "function", - "name": "classifyMessageSendError" - }, - { - "file": "internal/automation/center.go", - "line": 810, - "kind": "function", - "name": "accountAutomationAllowed" - }, - { - "file": "internal/automation/center.go", - "line": 811, - "kind": "local-variable", - "name": "err" - }, - { - "file": "internal/automation/center.go", - "line": 811, - "kind": "local-variable", - "name": "paused" - }, - { - "file": "internal/automation/center.go", - "line": 815, - "kind": "local-variable", - "name": "enabled" - }, - { - "file": "internal/automation/center.go", - "line": 815, - "kind": "local-variable", - "name": "err" - }, - { - "file": "internal/automation/center.go", - "line": 822, - "kind": "function", - "name": "accountSenderReady" - }, - { - "file": "internal/automation/center.go", - "line": 826, - "kind": "local-variable", - "name": "ok" - }, - { - "file": "internal/automation/center.go", - "line": 826, - "kind": "local-variable", - "name": "sender" - }, - { - "file": "internal/automation/center.go", - "line": 830, - "kind": "local-variable", - "name": "ok" - }, - { - "file": "internal/automation/center.go", - "line": 830, - "kind": "local-variable", - "name": "ready" - }, - { - "file": "internal/automation/center.go", - "line": 836, - "kind": "function", - "name": "lockCard" - }, - { - "file": "internal/automation/center.go", - "line": 837, + "line": 303, "kind": "local-variable", "name": "raw" }, { "file": "internal/automation/center.go", - "line": 838, - "kind": "local-variable", - "name": "mu" - }, - { - "file": "internal/automation/center.go", - "line": 843, + "line": 315, "kind": "function", - "name": "actionMatchesOrderSpec" + "name": "ManualFullDelivery" }, { "file": "internal/automation/center.go", - "line": 844, - "kind": "var", - "name": "cfg" - }, - { - "file": "internal/automation/center.go", - "line": 858, - "kind": "function", - "name": "deliverySendCount" - }, - { - "file": "internal/automation/center.go", - "line": 859, - "kind": "local-variable", - "name": "perUnit" - }, - { - "file": "internal/automation/center.go", - "line": 863, - "kind": "local-variable", - "name": "qty" - }, - { - "file": "internal/automation/center.go", - "line": 870, - "kind": "function", - "name": "parsePositiveInt" - }, - { - "file": "internal/automation/center.go", - "line": 875, + "line": 322, "kind": "local-variable", "name": "err" }, { "file": "internal/automation/center.go", - "line": 875, + "line": 322, + "kind": "local-variable", + "name": "paused" + }, + { + "file": "internal/automation/center.go", + "line": 322, + "kind": "local-variable", + "name": "until" + }, + { + "file": "internal/automation/center.go", + "line": 329, + "kind": "local-variable", + "name": "enabled" + }, + { + "file": "internal/automation/center.go", + "line": 329, + "kind": "local-variable", + "name": "err" + }, + { + "file": "internal/automation/center.go", + "line": 345, + "kind": "local-variable", + "name": "task" + }, + { + "file": "internal/automation/center.go", + "line": 365, + "kind": "local-variable", + "name": "err" + }, + { + "file": "internal/automation/center.go", + "line": 365, + "kind": "local-variable", + "name": "rules" + }, + { + "file": "internal/automation/center.go", + "line": 372, + "kind": "local-variable", + "name": "sent" + }, + { + "file": "internal/automation/center.go", + "line": 373, + "kind": "range-variable", + "name": "rule" + }, + { + "file": "internal/automation/center.go", + "line": 378, + "kind": "local-variable", + "name": "rawTask" + }, + { + "file": "internal/automation/center.go", + "line": 380, + "kind": "local-variable", + "name": "rawJSON" + }, + { + "file": "internal/automation/center.go", + "line": 381, + "kind": "local-variable", + "name": "runID" + }, + { + "file": "internal/automation/center.go", + "line": 381, + "kind": "local-variable", + "name": "startErr" + }, + { + "file": "internal/automation/center.go", + "line": 381, + "kind": "local-variable", + "name": "started" + }, + { + "file": "internal/automation/center.go", + "line": 399, + "kind": "local-variable", + "name": "getErr" + }, + { + "file": "internal/automation/center.go", + "line": 399, + "kind": "local-variable", + "name": "run" + }, + { + "file": "internal/automation/center.go", + "line": 403, + "kind": "local-variable", + "name": "deferred" + }, + { + "file": "internal/automation/center.go", + "line": 403, + "kind": "local-variable", + "name": "err" + }, + { + "file": "internal/automation/center.go", + "line": 403, "kind": "local-variable", "name": "n" }, { "file": "internal/automation/center.go", - "line": 882, - "kind": "function", - "name": "cardContent" + "line": 411, + "kind": "local-variable", + "name": "errMsg" }, { "file": "internal/automation/center.go", - "line": 903, - "kind": "function", - "name": "sendText" + "line": 411, + "kind": "local-variable", + "name": "status" }, { "file": "internal/automation/center.go", - "line": 910, + "line": 415, + "kind": "local-variable", + "name": "cancel" + }, + { + "file": "internal/automation/center.go", + "line": 415, + "kind": "local-variable", + "name": "finishCtx" + }, + { + "file": "internal/automation/center.go", + "line": 416, + "kind": "local-variable", + "name": "finishErr" + }, + { + "file": "internal/automation/center.go", + "line": 446, + "kind": "function", + "name": "notifyResult" + }, + { + "file": "internal/automation/center.go", + "line": 450, + "kind": "function", + "name": "notifyRunNeedsReview" + }, + { + "file": "internal/automation/center.go", + "line": 459, + "kind": "function", + "name": "actionDelaySeconds" + }, + { + "file": "internal/automation/center.go", + "line": 463, + "kind": "var", + "name": "cfg" + }, + { + "file": "internal/automation/center.go", + "line": 467, + "kind": "local-variable", + "name": "card" + }, + { + "file": "internal/automation/center.go", + "line": 467, + "kind": "local-variable", + "name": "err" + }, + { + "file": "internal/automation/center.go", + "line": 480, + "kind": "function", + "name": "prepareTask" + }, + { + "file": "internal/automation/center.go", + "line": 490, + "kind": "local-variable", + "name": "needsDetail" + }, + { + "file": "internal/automation/center.go", + "line": 491, + "kind": "local-variable", + "name": "err" + }, + { + "file": "internal/automation/center.go", + "line": 491, + "kind": "local-variable", + "name": "existing" + }, + { + "file": "internal/automation/center.go", + "line": 505, + "kind": "local-variable", + "name": "cookieStr" + }, + { + "file": "internal/automation/center.go", + "line": 507, + "kind": "var", + "name": "err" + }, + { + "file": "internal/automation/center.go", + "line": 513, + "kind": "local-variable", + "name": "detail" + }, + { + "file": "internal/automation/center.go", + "line": 513, + "kind": "local-variable", + "name": "err" + }, + { + "file": "internal/automation/center.go", + "line": 549, + "kind": "function", + "name": "mergeOrderIntoTask" + }, + { + "file": "internal/automation/center.go", + "line": 592, + "kind": "local-variable", + "name": "err" + }, + { + "file": "internal/automation/center.go", + "line": 604, + "kind": "local-variable", + "name": "err" + }, + { + "file": "internal/automation/center.go", + "line": 604, + "kind": "local-variable", + "name": "paused" + }, + { + "file": "internal/automation/center.go", + "line": 608, + "kind": "local-variable", + "name": "enabled" + }, + { + "file": "internal/automation/center.go", + "line": 608, + "kind": "local-variable", + "name": "err" + }, + { + "file": "internal/automation/center.go", + "line": 620, "kind": "local-variable", "name": "ok" }, { "file": "internal/automation/center.go", - "line": 910, + "line": 620, "kind": "local-variable", "name": "sender" }, { "file": "internal/automation/center.go", - "line": 917, - "kind": "function", - "name": "sendImage" - }, - { - "file": "internal/automation/center.go", - "line": 924, + "line": 624, "kind": "local-variable", "name": "ok" }, { "file": "internal/automation/center.go", - "line": 924, + "line": 624, "kind": "local-variable", - "name": "sender" + "name": "ready" }, { "file": "internal/automation/center.go", - "line": 931, - "kind": "function", - "name": "cookieValue" - }, - { - "file": "internal/automation/center.go", - "line": 942, + "line": 645, "kind": "function", "name": "buildTriggerKey" }, { "file": "internal/automation/center.go", - "line": 944, + "line": 647, "kind": "local-variable", "name": "attempt" }, { "file": "internal/automation/center.go", - "line": 944, + "line": 647, "kind": "local-variable", "name": "ok" }, - { - "file": "internal/automation/center.go", - "line": 957, - "kind": "function", - "name": "renderTemplate" - }, - { - "file": "internal/automation/center.go", - "line": 958, - "kind": "local-variable", - "name": "out" - }, - { - "file": "internal/automation/center.go", - "line": 959, - "kind": "local-variable", - "name": "repl" - }, - { - "file": "internal/automation/center.go", - "line": 970, - "kind": "range-variable", - "name": "k" - }, - { - "file": "internal/automation/center.go", - "line": 970, - "kind": "range-variable", - "name": "v" - }, { "file": "internal/automation/center_mock_mtop_test.go", "line": 28, diff --git a/docs/architecture/refactoring-master-plan.md b/docs/architecture/refactoring-master-plan.md index fc81621..8f6b063 100644 --- a/docs/architecture/refactoring-master-plan.md +++ b/docs/architecture/refactoring-master-plan.md @@ -167,7 +167,8 @@ app shell / routes - 已完成阶段 6 第四个 PR 切片“Engine 凭证状态与 Token 生命周期边界”:将 Cookie 快照、Token 缓存、刷新锁、设备指纹和刷新诊断状态收口到独立 `credentialState`;运行状态锁改为显式 `runtimeMu`,避免匿名组件锁冲突;保留风控恢复、刷新锁、Cookie/Token 绑定和 WebSocket 注册前快照复核语义;Engine 全量测试、Engine/Server race、vet、lint、注释和前端构建门禁通过并合并为一个可回滚提交; - 已完成阶段 6 第五个 PR 切片“Automation 事件事实与规则匹配边界”:新增事件事实记录器、无动作副作用的规则匹配器和纯动作计划器;`Center` 与 `Scheduler` 统一通过组件查询规则和生成动作计划,规则匹配不执行外部动作,付款发货动作顺序、规格匹配、延迟快照和恢复语义保持不变;Automation/Server race、全量测试、vet、lint、注释和前端构建门禁通过并合并为一个可回滚提交; - 已完成阶段 6 第六个 PR 切片“Automation 运行协调与动作执行边界”:新增 `automationRunCoordinator`,统一运行创建/恢复、动作前后检查点、延迟任务续租、账号门禁和不确定结果隔离;`Center` 保留兼容调用入口,外部动作已执行/未执行/结果未知三态语义、人工核对状态机和恢复游标保持不变;Automation 测试、注释和 diff 门禁通过,整批修改合并为一个可回滚提交; -- 阶段 6 下一 PR 切片为“Automation 发货、卡密与通知动作边界”:提取确认发货、卡密分配、消息发送和结果通知的动作执行组件,保留凭证锁、卡券锁、发送错误分类和通知幂等语义; +- 已完成阶段 6 第七个 PR 切片“Automation 发货、卡密与通知动作边界”:新增 `automationActionExecutor` 与 `deliveryNotifier`,统一确认发货、Cookie/Jar 合并、卡券锁与库存消费、消息错误三态分类和结果通知;`Center` 保留兼容入口,凭证锁、卡券库存、恢复唤醒和通知文案语义保持不变;新增动作执行器回归测试,Automation 测试、注释和 diff 门禁通过,整批修改合并为一个可回滚提交; +- 阶段 6 下一 PR 切片为“Automation 账号任务与凭证门禁边界”:提取账号自动评价/发货任务的调度、凭证阻塞和账号状态门禁边界,保留 Session 失效恢复、任务租约和失败重试语义; - 禁止跳过当前入口直接开始 Engine、Automation 或 DB 的大规模拆分。 ## 6. 阶段 0:治理文档与强约束 @@ -584,3 +585,4 @@ npm --prefix frontend run build | 2026-08-14 | 完成阶段 6 第四个 PR 切片“Engine 凭证状态与 Token 生命周期边界” | 新增 `credentialState`,集中 Cookie 快照、Token 缓存、刷新锁、设备指纹和刷新诊断状态;运行状态组件锁改名为 `runtimeMu`,保持 `Account` facade 字段访问兼容;Cookie 更新、Token 清理、风控恢复和 WS 注册前凭证快照复核语义保持不变;Engine 全量测试、Engine/Server race、vet、lint、注释和前端构建门禁通过并合并为一个可回滚提交 | 阶段 6:Automation 事件事实与规则匹配边界 | | 2026-08-14 | 完成阶段 6 第五个 PR 切片“Automation 事件事实与规则匹配边界” | 新增 `eventFactRecorder`、`ruleMatcher` 和 `actionPlanner`;事件事实写入、规则查询和动作计划生成职责分离,`Center`/`Scheduler` 不再直接散落调用规则匹配;动作计划保持付款发卡优先、规格过滤和延迟快照语义,新增纯计划与无订单事实回归测试;Automation/Server race、全量测试、vet、lint、注释和前端构建门禁通过并合并为一个可回滚提交 | 阶段 6:Automation 运行协调与动作执行边界 | | 2026-08-14 | 完成阶段 6 第六个 PR 切片“Automation 运行协调与动作执行边界” | 新增 `automationRunCoordinator`,统一运行创建/恢复、动作前后检查点、延迟任务续租、账号门禁和不确定结果隔离;`Center` 保留兼容调用入口,外部动作三态语义、人工核对状态机和恢复游标保持不变;Automation 测试、注释和 diff 门禁通过并合并为一个可回滚提交 | 阶段 6:Automation 发货、卡密与通知动作边界 | +| 2026-08-14 | 完成阶段 6 第七个 PR 切片“Automation 发货、卡密与通知动作边界” | 新增 `automationActionExecutor` 与 `deliveryNotifier`,统一确认发货、Cookie/Jar 合并、卡券锁与库存消费、消息错误三态分类和结果通知;`Center` 保留兼容入口,凭证锁、卡券库存、恢复唤醒和通知文案语义保持不变;新增动作执行器回归测试;Automation 测试、注释和 diff 门禁通过并合并为一个可回滚提交 | 阶段 6:Automation 账号任务与凭证门禁边界 | diff --git a/internal/automation/action_executor.go b/internal/automation/action_executor.go new file mode 100644 index 0000000..4563d18 --- /dev/null +++ b/internal/automation/action_executor.go @@ -0,0 +1,464 @@ +package automation + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "log/slog" + "strconv" + "strings" + "sync" + "time" + + "xianyu-go/internal/db" + "xianyu-go/internal/xianyu/cookierefresh" + "xianyu-go/internal/xianyu/mtop" +) + +// automationActionExecutor 负责把动作计划转换为确认发货、卡密发送或消息发送,并集中维护凭证快照、卡券库存和外部发送结果的边界。 +type automationActionExecutor struct { + // store 提供订单、卡券、账号 Cookie 和自动化事实的持久化能力。 + store *db.Store + // senders 提供账号当前在线的消息发送器。 + senders SenderProvider + // mtop 返回当前生效的 MTOP 客户端,支持测试替换和运行时注入。 + mtop func() mtop.Client + // recoverer 返回当前生效的凭证恢复器。 + recoverer func() CredentialRecoverer + // logger 记录确认发货和本地状态持久化异常。 + logger *slog.Logger + // cookieSource 读取测试或运行时覆盖的账号 Cookie。 + cookieSource func(context.Context, string) (string, error) + // wakeCredentialBlocked 在 Cookie 更新后唤醒凭证阻塞的自动化任务。 + wakeCredentialBlocked func(context.Context, string) + // cardLocks 串行化同一卡密组的数据库存取和消费。 + cardLocks sync.Map +} + +// executeAction 执行一个动作,并把消息发送错误分类为可安全重试或结果未知。 +func (e *automationActionExecutor) executeAction(ctx context.Context, task Task, action db.AutomationAction) (int, error) { + switch action.ActionType { + case ActionConfirmShipment: + return 0, e.confirmShipment(ctx, task) + case ActionSendCard: + return e.sendCard(ctx, task, action) + case ActionSendText: + // text 是渲染后的文字动作内容。 + text := renderTemplate(action.MessageTemplate, task) + if strings.TrimSpace(text) == "" { + return 0, nil + } + // sendErr 保存文字消息发送错误。 + if sendErr := e.sendText(ctx, task, text); sendErr != nil { + if errors.Is(sendErr, ErrMessageNotSent) { + return 0, sendErr + } + return 0, uncertainAction(sendErr) + } + return 1, nil + default: + return 0, fmt.Errorf("未知自动化动作: %s", action.ActionType) + } +} + +// confirmShipment 根据账号设置和任务强制标记决定是否确认订单发货。 +func (e *automationActionExecutor) confirmShipment(ctx context.Context, task Task) error { + if task.OrderID == "" { + return fmt.Errorf("确认发货缺少订单ID") + } + // enabled 表示账号是否打开自动确认发货设置。 + // readErr 保存读取自动确认发货设置的错误。 + enabled, readErr := e.store.Cookies.GetAutoConfirm(ctx, task.AccountID) + if readErr != nil { + return fmt.Errorf("读取自动确认发货设置: %w", readErr) + } + if !enabled && !task.ForceConfirmShipment { + return nil + } + return e.confirmShipmentAttempt(ctx, task, true) +} + +// confirmShipmentAttempt 在凭证锁内调用 Consign,并处理 Cookie 合并、凭证恢复和本地状态收口。 +func (e *automationActionExecutor) confirmShipmentAttempt(ctx context.Context, task Task, allowCredentialRecovery bool) error { + // credentialUnlock 是账号凭证锁的释放函数。 + credentialUnlock := e.store.LockAccountCredentials(task.AccountID) + // credentialLocked 标记当前调用是否仍持有凭证锁。 + credentialLocked := true + defer func() { + if credentialLocked { + credentialUnlock() + } + }() + // runtimeData 是确认发货所需的最小 Cookie 与 metadata 运行视图,不包含登录密码和账号资料。 + runtimeData, err := e.store.Cookies.GetCookieRuntimeData(ctx, task.AccountID) + if err != nil { + return err + } + // completeSnapshot 表示 metadata 中是否包含可恢复的完整 Cookie Jar。 + _, completeSnapshot := cookierefresh.SnapshotFromMetadataOK(runtimeData.MetadataJSON) + if strings.TrimSpace(runtimeData.Value) == "" && !completeSnapshot { + return fmt.Errorf("账号 %s Cookie 为空", task.AccountID) + } + // cookieStr 是本次确认发货使用的扁平 Cookie。 + cookieStr := runtimeData.Value + // mtopCtx 是携带 Cookie Jar 或扁平 Cookie 的 MTOP 请求上下文。 + var mtopCtx context.Context + // cookieSession 记录 MTOP 响应中的 Cookie 合并结果。 + var cookieSession *mtop.CookieSession + // snapshot 是 metadata 中恢复出的完整 Cookie Jar。 + // snapshotOK 表示完整 Cookie Jar 是否存在。 + if snapshot, snapshotOK := cookierefresh.SnapshotFromMetadataOK(runtimeData.MetadataJSON); snapshotOK { + mtopCtx, cookieSession = mtop.WithCookieSnapshot(ctx, snapshot) + } else { + mtopCtx, cookieSession = mtop.WithFlatCookieSession(ctx, cookieStr) + } + // ok 表示远端确认发货是否成功。 + // ret 保存远端返回的业务错误文本。 + // updated 保存无权威 Cookie Jar 时的扁平 Cookie 更新结果。 + // callErr 保存 MTOP 请求层错误。 + // consignOK 表示远端确认发货是否成功。 + // ret 保存远端返回的业务错误文本。 + // updated 保存无权威 Cookie Jar 时的扁平 Cookie 更新结果。 + // callErr 保存 MTOP 请求层错误。 + consignOK, ret, updated, callErr := e.mtop().ConsignContext(mtopCtx, cookieStr, task.OrderID) + // persistenceErrs 收集远端动作完成后本地状态写入失败。 + var persistenceErrs []error + // runtimeCookie 保存需要同步到在线发送器的最新 Cookie。 + runtimeCookie := "" + // runtimeCookieChanged 表示在线运行时是否需要替换 Cookie。 + runtimeCookieChanged := false + // value 是 Cookie 会话合并后的扁平值。 + // snapshot 是 Cookie 会话合并后的完整快照。 + // changed 表示 Cookie 会话是否产生变化。 + value, snapshot, changed := cookieSession.State() + // sessionHandled 表示本次请求是否由完整 Cookie Jar 接管。 + sessionHandled := snapshot != nil + if changed { + // metadata 是准备写回数据库的 Cookie metadata。 + metadata := cookierefresh.MetadataWithoutSnapshot(runtimeData.MetadataJSON) + if snapshot != nil { + metadata = cookierefresh.MetadataWithSnapshot(runtimeData.MetadataJSON, snapshot) + } + // saveErr 保存 Cookie Jar 写回数据库时的错误。 + if saveErr := e.store.Cookies.UpdateRenewalCookie(ctx, task.AccountID, value, metadata, time.Now().Unix()); saveErr != nil { + persistenceErrs = append(persistenceErrs, fmt.Errorf("保存确认发货响应 Cookie Jar: %w", saveErr)) + } else if value != cookieStr { + runtimeCookie = value + runtimeCookieChanged = true + } + } + if !sessionHandled && callErr == nil && updated != "" && updated != cookieStr { + // 没有权威快照的历史账号保留扁平 Cookie 兼容路径,并清除可能过期的旧 Jar。 + metadata := cookierefresh.MetadataWithoutSnapshot(runtimeData.MetadataJSON) + // saveErr 保存扁平 Cookie 写回数据库时的错误。 + if saveErr := e.store.Cookies.UpdateRenewalCookie(ctx, task.AccountID, updated, metadata, time.Now().Unix()); saveErr != nil { + persistenceErrs = append(persistenceErrs, fmt.Errorf("保存刷新后的 Cookie: %w", saveErr)) + } else { + runtimeCookie = updated + runtimeCookieChanged = true + } + } + credentialUnlock() + credentialLocked = false + if runtimeCookieChanged && e.senders != nil { + // sender 是当前账号的在线消息发送器。 + // running 表示账号是否仍处于运行状态。 + if sender, running := e.senders.Sender(task.AccountID); running { + sender.UpdateCookie(runtimeCookie) + } + } + if runtimeCookieChanged { + e.wakeCredentialBlocked(ctx, task.AccountID) + } + // sessionErr 将请求层错误和远端业务失败统一为凭证状态判断输入。 + sessionErr := callErr + if sessionErr == nil && !consignOK { + sessionErr = errors.New(strings.Join(ret, "; ")) + } + if mtop.IsSessionExpiredErr(sessionErr) { + if len(persistenceErrs) > 0 { + return errors.Join(fmt.Errorf("确认发货 Session 已失效: %w", sessionErr), errors.Join(persistenceErrs...)) + } + // recoverer 是当前生效的凭证恢复器快照,避免一次判断期间被替换两次。 + recoverer := e.recoverer() + if allowCredentialRecovery && recoverer != nil && recoverer.RecoverExpiredCredential(ctx, task.AccountID) { + e.logger.Info("确认发货凭证恢复成功,重新执行确认发货", "account", task.AccountID, "order_id", task.OrderID) + return e.confirmShipmentAttempt(ctx, task, false) + } + if !allowCredentialRecovery { + return fmt.Errorf("%w: 确认发货在凭证恢复后仍返回 Session 失效: %v", errActionNotPerformed, sessionErr) + } + return fmt.Errorf("%w: 确认发货 Session 已失效且凭证恢复失败: %v", errActionNotPerformed, sessionErr) + } + if callErr != nil { + if len(persistenceErrs) > 0 { + callErr = errors.Join(callErr, errors.Join(persistenceErrs...)) + } + return uncertainAction(callErr) + } + if !consignOK { + // failure 是远端拒绝确认发货的业务错误。 + failure := fmt.Errorf("确认发货失败: %s", strings.Join(ret, "; ")) + if len(persistenceErrs) > 0 { + return errors.Join(failure, errors.Join(persistenceErrs...)) + } + return failure + } + // sysShip 表示本地订单已由系统确认发货。 + sysShip := true + // upsertErr 保存本地订单发货状态写入错误。 + if upsertErr := e.store.Orders.Upsert(ctx, task.OrderID, db.OrderUpsertOpts{ + CookieID: task.AccountID, + ItemID: task.ItemID, + BuyerID: task.BuyerID, + ChatID: task.ChatID, + OrderStatus: "shipped", + SystemShipped: &sysShip, + }); upsertErr != nil { + persistenceErrs = append(persistenceErrs, fmt.Errorf("保存本地订单发货状态: %w", upsertErr)) + } + // eventErr 保存订单发货事实写入错误。 + if eventErr := e.store.Automation.MarkOrderEventTime(ctx, task.OrderID, "shipped_at"); eventErr != nil { + persistenceErrs = append(persistenceErrs, fmt.Errorf("保存订单发货时间: %w", eventErr)) + } + if len(persistenceErrs) > 0 { + return uncertainAction(fmt.Errorf("闲鱼已确认发货,但本地状态保存失败: %w", errors.Join(persistenceErrs...))) + } + return nil +} + +// sendCard 按规格和购买数量分配文本、图片或数据卡密。 +func (e *automationActionExecutor) sendCard(ctx context.Context, task Task, action db.AutomationAction) (int, error) { + if !actionMatchesOrderSpec(task, action) { + return 0, nil + } + if action.CardID <= 0 { + return 0, fmt.Errorf("发送卡密动作缺少卡密组ID") + } + // count 是当前订单需要发送的卡密数量。 + count := deliverySendCount(task, action) + // card 是待发送的卡密组完整配置。 + card, err := e.store.Cards.Get(ctx, action.CardID) + if err != nil { + return 0, err + } + if !card.Enabled { + return 0, fmt.Errorf("卡密组 %d 已停用", card.ID) + } + if card.Type == "data" { + return e.sendDataCard(ctx, task, card, count) + } + // sent 是已经成功发送的卡密数量。 + sent := 0 + // i 表示当前卡密发送序号。 + for i := 0; i < count; i++ { + // content 是当前卡密文本内容。 + // imageURL 是当前卡密图片地址。 + content, imageURL, readErr := e.cardContent(ctx, card) + if readErr != nil { + return sent, readErr + } + if imageURL != "" { + // sendErr 保存图片消息发送错误。 + if sendErr := e.sendImage(ctx, task, imageURL, card.ID); sendErr != nil { + return sent, classifyMessageSendError(sendErr) + } + } + if strings.TrimSpace(content) != "" { + // sendErr 保存文字消息发送错误。 + if sendErr := e.sendText(ctx, task, renderTemplate(content, task)); sendErr != nil { + return sent, classifyMessageSendError(sendErr) + } + } + if strings.TrimSpace(content) == "" && strings.TrimSpace(imageURL) == "" { + return sent, fmt.Errorf("卡密组 %d 没有可发送内容", card.ID) + } + sent++ + } + return sent, nil +} + +// sendDataCard 在卡券锁内原子消费数据卡密,并在确定未发送时恢复库存。 +func (e *automationActionExecutor) sendDataCard(ctx context.Context, task Task, card *db.CardFull, count int) (int, error) { + // unlock 释放当前卡密组的并发消费锁。 + unlock := e.lockCard(card.ID) + defer unlock() + // sent 是已经成功发送的数据卡密数量。 + sent := 0 + // i 表示当前数据卡密消费序号。 + for i := 0; i < count; i++ { + // content 是从库存中原子消费出的数据卡密。 + content, err := e.store.Cards.ConsumeBatchData(ctx, card.ID) + if err != nil { + return sent, err + } + if strings.TrimSpace(content) != "" { + // sendErr 保存数据卡密消息发送错误。 + if sendErr := e.sendText(ctx, task, renderTemplate(content, task)); sendErr != nil { + if errors.Is(sendErr, ErrMessageNotSent) { + // restoreErr 保存确定未发送时恢复库存的错误。 + if restoreErr := e.store.Cards.RestoreBatchData(ctx, card.ID, content); restoreErr != nil { + return sent, uncertainAction(errors.Join(sendErr, fmt.Errorf("恢复未发送卡密库存: %w", restoreErr))) + } + return sent, sendErr + } + // 请求已交给传输层后无法判断远端是否收到,保留消费状态并人工核对。 + return sent, uncertainAction(sendErr) + } + } + sent++ + } + return sent, nil +} + +// sendText 向账号在线发送器发送文字消息,并保留确定未发送的错误标记。 +func (e *automationActionExecutor) sendText(ctx context.Context, task Task, text string) error { + if task.ChatID == "" || task.BuyerID == "" { + return fmt.Errorf("%w: 发送消息缺少 chat_id 或 buyer_id", ErrMessageNotSent) + } + if e.senders == nil { + return fmt.Errorf("%w: 账号发送器未初始化", ErrMessageNotSent) + } + // sender 是当前账号的在线消息发送器。 + // senderOK 表示是否找到在线发送器。 + sender, senderOK := e.senders.Sender(task.AccountID) + if !senderOK { + return fmt.Errorf("%w: 账号未在线,无法发送自动化消息", ErrMessageNotSent) + } + return sender.SendText(ctx, task.ChatID, task.BuyerID, text) +} + +// sendImage 向账号在线发送器发送图片消息,并标记关联卡密组。 +func (e *automationActionExecutor) sendImage(ctx context.Context, task Task, imageURL string, cardID int64) error { + if task.ChatID == "" || task.BuyerID == "" { + return fmt.Errorf("%w: 发送图片缺少 chat_id 或 buyer_id", ErrMessageNotSent) + } + if e.senders == nil { + return fmt.Errorf("%w: 账号发送器未初始化", ErrMessageNotSent) + } + // sender 是当前账号的在线图片发送器。 + // senderOK 表示是否找到在线发送器。 + sender, senderOK := e.senders.Sender(task.AccountID) + if !senderOK { + return fmt.Errorf("%w: 账号未在线,无法发送自动化图片", ErrMessageNotSent) + } + return sender.SendImage(ctx, task.ChatID, task.BuyerID, imageURL, cardID) +} + +// cardContent 读取卡密组内容并拒绝不支持的卡密类型。 +func (e *automationActionExecutor) cardContent(_ context.Context, card *db.CardFull) (text, imageURL string, err error) { + switch card.Type { + case "text": + if strings.TrimSpace(card.TextContent) == "" { + return "", "", fmt.Errorf("文本卡密组缺少内容") + } + return card.TextContent, "", nil + case "data": + return "", "", fmt.Errorf("data 卡密必须通过 sendDataCard 发送") + case "image": + if strings.TrimSpace(card.ImageURL) == "" { + return "", "", fmt.Errorf("图片卡密组缺少图片 URL") + } + return "", card.ImageURL, nil + case "api": + return "", "", fmt.Errorf("自动化中心暂不支持 API 卡密动作") + default: + return "", "", fmt.Errorf("未知卡密类型: %s", card.Type) + } +} + +// cookieValue 读取账号 Cookie,优先使用测试或运行时覆盖的数据源。 +func (e *automationActionExecutor) cookieValue(ctx context.Context, cookieID string) (string, error) { + return e.cookieSource(ctx, cookieID) +} + +// lockCard 获取指定卡密组的进程内互斥锁。 +func (e *automationActionExecutor) lockCard(cardID int64) func() { + // raw 是按卡密组 ID 保存的锁实例。 + raw, _ := e.cardLocks.LoadOrStore(cardID, &sync.Mutex{}) + // mu 是当前卡密组的互斥锁。 + mu := raw.(*sync.Mutex) + mu.Lock() + return mu.Unlock +} + +// actionMatchesOrderSpec 判断动作配置的规格是否匹配订单。 +func actionMatchesOrderSpec(task Task, action db.AutomationAction) bool { + // cfg 保存卡密动作的规格过滤配置。 + var cfg struct { + SpecName string `json:"spec_name"` + SpecValue string `json:"spec_value"` + } + if json.Unmarshal([]byte(action.ConfigJSON), &cfg) != nil { + return false + } + if strings.TrimSpace(cfg.SpecName) == "" && strings.TrimSpace(cfg.SpecValue) == "" { + return true + } + return strings.TrimSpace(task.SpecName) == strings.TrimSpace(cfg.SpecName) && + strings.TrimSpace(task.SpecValue) == strings.TrimSpace(cfg.SpecValue) +} + +// deliverySendCount 根据动作单份数量和订单购买数量计算实际发送数量。 +func deliverySendCount(task Task, action db.AutomationAction) int { + // perUnit 是每个购买单位对应的卡密数量。 + perUnit := action.DeliveryCount + if perUnit <= 0 { + perUnit = 1 + } + // qty 是订单购买数量。 + qty := parsePositiveInt(task.Quantity) + if qty <= 0 { + qty = 1 + } + return perUnit * qty +} + +// parsePositiveInt 将数量文本解析为非负整数,非法值返回零。 +func parsePositiveInt(raw string) int { + raw = strings.TrimSpace(raw) + if raw == "" { + return 0 + } + // n 是解析后的数量值。 + // err 是数量文本解析错误。 + // n 是解析后的数量值。 + // parseErr 是数量文本解析错误。 + n, parseErr := strconv.Atoi(raw) + if parseErr != nil || n < 0 { + return 0 + } + return n +} + +// classifyMessageSendError 将消息发送错误统一分类为确定未发送或结果未知。 +func classifyMessageSendError(err error) error { + if err == nil || errors.Is(err, ErrMessageNotSent) { + return err + } + return uncertainAction(err) +} + +// renderTemplate 替换自动化消息模板中的订单字段。 +func renderTemplate(tpl string, task Task) string { + // out 是经过字段替换后的模板文本。 + out := tpl + // repl 保存模板占位符与订单字段的映射。 + repl := map[string]string{ + "{order_id}": task.OrderID, + "{item_id}": task.ItemID, + "{buyer_id}": task.BuyerID, + "{chat_id}": task.ChatID, + "{trigger_type}": task.TriggerType, + "{spec_name}": task.SpecName, + "{spec_value}": task.SpecValue, + "{quantity}": task.Quantity, + "{amount}": task.Amount, + } + // key 和 value 分别表示当前占位符及其替换值。 + for key, value := range repl { + out = strings.ReplaceAll(out, key, value) + } + return out +} diff --git a/internal/automation/action_executor_test.go b/internal/automation/action_executor_test.go new file mode 100644 index 0000000..51614a6 --- /dev/null +++ b/internal/automation/action_executor_test.go @@ -0,0 +1,27 @@ +package automation + +import ( + "context" + "errors" + "fmt" + "testing" + + "xianyu-go/internal/db" +) + +// TestAutomationActionExecutorPreservesMessageNotSent 验证动作执行器保留“确定未发送”错误,供运行协调器安全重试。 +func TestAutomationActionExecutorPreservesMessageNotSent(t *testing.T) { + // sender 是返回确定未发送错误的测试发送器。 + sender := &testSender{err: fmt.Errorf("%w: websocket 尚未就绪", ErrMessageNotSent)} + // executor 是仅注入消息发送器的动作执行器。 + executor := automationActionExecutor{senders: testSenderProvider{sender: sender}} + // sent 是动作执行器报告的已发送数量。 + sent, err := executor.executeAction(context.Background(), Task{ + AccountID: "cid", + ChatID: "chat", + BuyerID: "buyer", + }, db.AutomationAction{ActionType: ActionSendText, MessageTemplate: "hello"}) + if sent != 0 || !errors.Is(err, ErrMessageNotSent) { + t.Fatalf("确定未发送错误未保留: sent=%d err=%v", sent, err) + } +} diff --git a/internal/automation/center.go b/internal/automation/center.go index b38029b..8cabb41 100644 --- a/internal/automation/center.go +++ b/internal/automation/center.go @@ -12,7 +12,6 @@ import ( "time" "xianyu-go/internal/db" - "xianyu-go/internal/xianyu/cookierefresh" "xianyu-go/internal/xianyu/mtop" ) @@ -93,17 +92,20 @@ type Center struct { // planner 生成不可变动作计划,不执行外部 I/O。 planner actionPlanner // runs 协调自动化运行创建、动作检查点、延迟恢复和结果隔离。 - runs automationRunCoordinator - store *db.Store - senders SenderProvider - fetcher OrderDetailFetcher - recoverer CredentialRecoverer - notifier Notifier - mtop mtop.Client - accountTasks AccountTaskClient - logger *slog.Logger - cookieSrc func(context.Context, string) (string, error) - cardLocks sync.Map + runs automationRunCoordinator + // actions 执行确认发货、卡密和消息动作,集中维护外部副作用边界。 + actions automationActionExecutor + // notifications 负责把运行结果转换为可选的发货通知。 + notifications deliveryNotifier + store *db.Store + senders SenderProvider + fetcher OrderDetailFetcher + recoverer CredentialRecoverer + notifier Notifier + mtop mtop.Client + accountTasks AccountTaskClient + logger *slog.Logger + cookieSrc func(context.Context, string) (string, error) // sessionExpired 保存检测到 Session 失效时的凭证指纹。在凭证续期或 // 重新登录真正改变之前,账号任务不得再次调用任何 MTOP 业务接口。 sessionExpired sync.Map @@ -125,6 +127,29 @@ func New(store *db.Store, senders SenderProvider, logger *slog.Logger) *Center { accountTasks: client, logger: logger.With("subsys", "automation"), } + center.actions = automationActionExecutor{ + store: store, + senders: senders, + mtop: func() mtop.Client { + return center.mtop + }, + recoverer: func() CredentialRecoverer { + return center.recoverer + }, + logger: center.logger, + cookieSource: func(ctx context.Context, cookieID string) (string, error) { + if center.cookieSrc != nil { + return center.cookieSrc(ctx, cookieID) + } + return center.store.Cookies.GetValue(ctx, cookieID) + }, + wakeCredentialBlocked: center.wakeCredentialBlockedAutomation, + } + center.notifications = deliveryNotifier{ + current: func() Notifier { + return center.notifier + }, + } center.runs = automationRunCoordinator{ store: store, planner: center.planner, @@ -419,32 +444,14 @@ func (c *Center) executeRunActions(ctx context.Context, task Task, ruleID int64, // notifyResult 根据规则执行结果发送通知。成功且实际发出了内容才通知, // 避免无匹配动作的空跑刷屏;失败时发失败通知。 func (c *Center) notifyResult(task Task, status string, sent int, errMsg string) { - triggerName := map[string]string{ - TriggerOrderPaid: "付款发货", - TriggerBuyerReviewed: "评价赠品", - TriggerReviewMissingTimeout: "求评价", - }[task.TriggerType] - if triggerName == "" { - triggerName = task.TriggerType - } - if status == "success" { - if sent <= 0 { - return - } - msg := fmt.Sprintf("✅ %s成功(订单 %s,已发送 %d 条)", triggerName, task.OrderID, sent) - c.notifier.NotifyDelivery(task.AccountID, "", task.BuyerID, task.ItemID, msg, task.ChatID) - return - } - msg := fmt.Sprintf("🚨 %s失败(订单 %s):%s", triggerName, task.OrderID, errMsg) - c.notifier.NotifyDelivery(task.AccountID, "", task.BuyerID, task.ItemID, msg, task.ChatID) + c.notifications.notifyResult(task, status, sent, errMsg) } func (c *Center) notifyRunNeedsReview(run db.AutomationRun, reason string) { - if c == nil || c.notifier == nil { + if c == nil { return } - task := Task{AccountID: run.CookieID, BuyerID: run.BuyerID, ItemID: run.ItemID, ChatID: run.ChatID, OrderID: run.OrderID, TriggerType: run.TriggerType} - c.notifyResult(task, "needs_review", run.SentCount, "需要人工核对:"+reason) + c.notifications.notifyRunNeedsReview(run, reason) } // actionDelaySeconds 统一卡密默认延时和动作覆盖语义。旧动作没有 @@ -567,162 +574,17 @@ func mergeOrderIntoTask(task Task, order *db.Order) Task { return task } +// executeAction 将具体动作委托给发货动作执行器。 func (c *Center) executeAction(ctx context.Context, task Task, action db.AutomationAction) (int, error) { - switch action.ActionType { - case ActionConfirmShipment: - return 0, c.confirmShipment(ctx, task) - case ActionSendCard: - return c.sendCard(ctx, task, action) - case ActionSendText: - text := renderTemplate(action.MessageTemplate, task) - if strings.TrimSpace(text) == "" { - return 0, nil - } - if err := c.sendText(ctx, task, text); err != nil { - if errors.Is(err, ErrMessageNotSent) { - return 0, err - } - return 0, uncertainAction(err) - } - return 1, nil - default: - return 0, fmt.Errorf("未知自动化动作: %s", action.ActionType) - } + return c.actions.executeAction(ctx, task, action) } +// confirmShipment 将确认发货委托给发货动作执行器。 func (c *Center) confirmShipment(ctx context.Context, task Task) error { - if task.OrderID == "" { - return fmt.Errorf("确认发货缺少订单ID") - } - enabled, err := c.store.Cookies.GetAutoConfirm(ctx, task.AccountID) - if err != nil { - return fmt.Errorf("读取自动确认发货设置: %w", err) - } - if !enabled && !task.ForceConfirmShipment { - return nil - } - return c.confirmShipmentAttempt(ctx, task, true) -} - -func (c *Center) confirmShipmentAttempt(ctx context.Context, task Task, allowCredentialRecovery bool) error { - credentialUnlock := c.store.LockAccountCredentials(task.AccountID) - credentialLocked := true - defer func() { - if credentialLocked { - credentialUnlock() - } - }() - // runtimeData 是确认发货所需的最小 Cookie 与 metadata 运行视图,不包含登录密码和账号资料。 - runtimeData, err := c.store.Cookies.GetCookieRuntimeData(ctx, task.AccountID) - if err != nil { - return err - } - // runtimeData 已在凭证锁内读取;这里只根据完整快照判断空 Cookie 的合法性。 - // completeSnapshot 表示 metadata 中是否包含可恢复的完整 Cookie Jar。 - _, completeSnapshot := cookierefresh.SnapshotFromMetadataOK(runtimeData.MetadataJSON) - if strings.TrimSpace(runtimeData.Value) == "" && !completeSnapshot { - return fmt.Errorf("账号 %s Cookie 为空", task.AccountID) - } - cookieStr := runtimeData.Value - var mtopCtx context.Context - var cookieSession *mtop.CookieSession - if snapshot, ok := cookierefresh.SnapshotFromMetadataOK(runtimeData.MetadataJSON); ok { - mtopCtx, cookieSession = mtop.WithCookieSnapshot(ctx, snapshot) - } else { - mtopCtx, cookieSession = mtop.WithFlatCookieSession(ctx, cookieStr) - } - ok, ret, updated, callErr := c.mtop.ConsignContext(mtopCtx, cookieStr, task.OrderID) - var persistenceErrs []error - runtimeCookie := "" - runtimeCookieChanged := false - value, snapshot, changed := cookieSession.State() - // 完整 Jar 已接管时,即使响应没有 Cookie 变化,也不能因扁平字符串 - // 格式差异回退覆盖并清除 Jar。 - sessionHandled := snapshot != nil - if changed { - metadata := cookierefresh.MetadataWithoutSnapshot(runtimeData.MetadataJSON) - if snapshot != nil { - metadata = cookierefresh.MetadataWithSnapshot(runtimeData.MetadataJSON, snapshot) - } - if saveErr := c.store.Cookies.UpdateRenewalCookie(ctx, task.AccountID, value, metadata, time.Now().Unix()); saveErr != nil { - persistenceErrs = append(persistenceErrs, fmt.Errorf("保存确认发货响应 Cookie Jar: %w", saveErr)) - } else if value != cookieStr { - runtimeCookie = value - runtimeCookieChanged = true - } - } - if !sessionHandled && callErr == nil && updated != "" && updated != cookieStr { - // 注入 mock 或没有权威快照的历史账号保留扁平 - // Cookie 兼容路径;扁平结果无法维护旧 Jar 的作用域, - // 因此不得继续保留可能已过期的 snapshot。 - metadata := cookierefresh.MetadataWithoutSnapshot(runtimeData.MetadataJSON) - if saveErr := c.store.Cookies.UpdateRenewalCookie(ctx, task.AccountID, updated, metadata, time.Now().Unix()); saveErr != nil { - persistenceErrs = append(persistenceErrs, fmt.Errorf("保存刷新后的 Cookie: %w", saveErr)) - } else { - runtimeCookie = updated - runtimeCookieChanged = true - } - } - credentialUnlock() - credentialLocked = false - if runtimeCookieChanged && c.senders != nil { - if sender, running := c.senders.Sender(task.AccountID); running { - sender.UpdateCookie(runtimeCookie) - } - } - if runtimeCookieChanged { - c.wakeCredentialBlockedAutomation(ctx, task.AccountID) - } - sessionErr := callErr - if sessionErr == nil && !ok { - sessionErr = errors.New(strings.Join(ret, "; ")) - } - if mtop.IsSessionExpiredErr(sessionErr) { - if len(persistenceErrs) > 0 { - return errors.Join(fmt.Errorf("确认发货 Session 已失效: %w", sessionErr), errors.Join(persistenceErrs...)) - } - if allowCredentialRecovery && c.recoverer != nil && c.recoverer.RecoverExpiredCredential(ctx, task.AccountID) { - c.logger.Info("确认发货凭证恢复成功,重新执行确认发货", "account", task.AccountID, "order_id", task.OrderID) - return c.confirmShipmentAttempt(ctx, task, false) - } - if !allowCredentialRecovery { - return fmt.Errorf("%w: 确认发货在凭证恢复后仍返回 Session 失效: %v", errActionNotPerformed, sessionErr) - } - return fmt.Errorf("%w: 确认发货 Session 已失效且凭证恢复失败: %v", errActionNotPerformed, sessionErr) - } - if callErr != nil { - if len(persistenceErrs) > 0 { - callErr = errors.Join(callErr, errors.Join(persistenceErrs...)) - } - return uncertainAction(callErr) - } - if !ok { - failure := fmt.Errorf("确认发货失败: %s", strings.Join(ret, "; ")) - if len(persistenceErrs) > 0 { - return errors.Join(failure, errors.Join(persistenceErrs...)) - } - return failure - } - sysShip := true - if upsertErr := c.store.Orders.Upsert(ctx, task.OrderID, db.OrderUpsertOpts{ - CookieID: task.AccountID, - ItemID: task.ItemID, - BuyerID: task.BuyerID, - ChatID: task.ChatID, - OrderStatus: "shipped", - SystemShipped: &sysShip, - }); upsertErr != nil { - persistenceErrs = append(persistenceErrs, fmt.Errorf("保存本地订单发货状态: %w", upsertErr)) - } - if eventErr := c.store.Automation.MarkOrderEventTime(ctx, task.OrderID, "shipped_at"); eventErr != nil { - persistenceErrs = append(persistenceErrs, fmt.Errorf("保存订单发货时间: %w", eventErr)) - } - if len(persistenceErrs) > 0 { - return uncertainAction(fmt.Errorf("闲鱼已确认发货,但本地状态保存失败: %w", errors.Join(persistenceErrs...))) - } - return nil + return c.actions.confirmShipment(ctx, task) } +// wakeCredentialBlockedAutomation 在 Cookie 更新后唤醒凭证阻塞的自动化任务。 func (c *Center) wakeCredentialBlockedAutomation(ctx context.Context, accountID string) { if c == nil || c.store == nil || c.store.Automation == nil { return @@ -732,81 +594,12 @@ func (c *Center) wakeCredentialBlockedAutomation(ctx context.Context, accountID } } +// sendCard 将卡密发送委托给发货动作执行器。 func (c *Center) sendCard(ctx context.Context, task Task, action db.AutomationAction) (int, error) { - if !actionMatchesOrderSpec(task, action) { - return 0, nil - } - if action.CardID <= 0 { - return 0, fmt.Errorf("发送卡密动作缺少卡密组ID") - } - count := deliverySendCount(task, action) - card, err := c.store.Cards.Get(ctx, action.CardID) - if err != nil { - return 0, err - } - if !card.Enabled { - return 0, fmt.Errorf("卡密组 %d 已停用", card.ID) - } - if card.Type == "data" { - return c.sendDataCard(ctx, task, card, count) - } - sent := 0 - for i := 0; i < count; i++ { - content, imageURL, err := c.cardContent(ctx, card) - if err != nil { - return sent, err - } - if imageURL != "" { - if err := c.sendImage(ctx, task, imageURL, card.ID); err != nil { - return sent, classifyMessageSendError(err) - } - } - if strings.TrimSpace(content) != "" { - if err := c.sendText(ctx, task, renderTemplate(content, task)); err != nil { - return sent, classifyMessageSendError(err) - } - } - if strings.TrimSpace(content) == "" && strings.TrimSpace(imageURL) == "" { - return sent, fmt.Errorf("卡密组 %d 没有可发送内容", card.ID) - } - sent++ - } - return sent, nil -} - -func (c *Center) sendDataCard(ctx context.Context, task Task, card *db.CardFull, count int) (int, error) { - unlock := c.lockCard(card.ID) - defer unlock() - sent := 0 - for i := 0; i < count; i++ { - content, err := c.store.Cards.ConsumeBatchData(ctx, card.ID) - if err != nil { - return sent, err - } - if strings.TrimSpace(content) != "" { - if err := c.sendText(ctx, task, renderTemplate(content, task)); err != nil { - if errors.Is(err, ErrMessageNotSent) { - if restoreErr := c.store.Cards.RestoreBatchData(ctx, card.ID, content); restoreErr != nil { - return sent, uncertainAction(errors.Join(err, fmt.Errorf("恢复未发送卡密库存: %w", restoreErr))) - } - return sent, err - } - // 请求已经交给传输层后无法判断远端是否收到,保留消费状态并人工核对。 - return sent, uncertainAction(err) - } - } - sent++ - } - return sent, nil -} - -func classifyMessageSendError(err error) error { - if err == nil || errors.Is(err, ErrMessageNotSent) { - return err - } - return uncertainAction(err) + return c.actions.sendCard(ctx, task, action) } +// accountAutomationAllowed 判断账号是否仍允许执行自动化动作。 func (c *Center) accountAutomationAllowed(ctx context.Context, accountID string) (bool, error) { paused, _, err := c.store.Cookies.IsPaused(ctx, accountID) if err != nil { @@ -819,6 +612,7 @@ func (c *Center) accountAutomationAllowed(ctx context.Context, accountID string) return !paused && enabled, nil } +// accountSenderReady 判断账号是否具备可发送自动化消息的在线连接。 func (c *Center) accountSenderReady(accountID string) bool { if c == nil || c.senders == nil { return false @@ -833,110 +627,19 @@ func (c *Center) accountSenderReady(accountID string) bool { return true } -func (c *Center) lockCard(cardID int64) func() { - raw, _ := c.cardLocks.LoadOrStore(cardID, &sync.Mutex{}) - mu := raw.(*sync.Mutex) - mu.Lock() - return mu.Unlock -} - -func actionMatchesOrderSpec(task Task, action db.AutomationAction) bool { - var cfg struct { - SpecName string `json:"spec_name"` - SpecValue string `json:"spec_value"` - } - if json.Unmarshal([]byte(action.ConfigJSON), &cfg) != nil { - return false - } - if strings.TrimSpace(cfg.SpecName) == "" && strings.TrimSpace(cfg.SpecValue) == "" { - return true - } - return strings.TrimSpace(task.SpecName) == strings.TrimSpace(cfg.SpecName) && - strings.TrimSpace(task.SpecValue) == strings.TrimSpace(cfg.SpecValue) -} - -func deliverySendCount(task Task, action db.AutomationAction) int { - perUnit := action.DeliveryCount - if perUnit <= 0 { - perUnit = 1 - } - qty := parsePositiveInt(task.Quantity) - if qty <= 0 { - qty = 1 - } - return perUnit * qty -} - -func parsePositiveInt(raw string) int { - raw = strings.TrimSpace(raw) - if raw == "" { - return 0 - } - n, err := strconv.Atoi(raw) - if err != nil || n < 0 { - return 0 - } - return n -} - +// cardContent 获取卡密组内容的兼容入口。 func (c *Center) cardContent(ctx context.Context, card *db.CardFull) (text, imageURL string, err error) { - switch card.Type { - case "text": - if strings.TrimSpace(card.TextContent) == "" { - return "", "", fmt.Errorf("文本卡密组缺少内容") - } - return card.TextContent, "", nil - case "data": - return "", "", fmt.Errorf("data 卡密必须通过 sendDataCard 发送") - case "image": - if strings.TrimSpace(card.ImageURL) == "" { - return "", "", fmt.Errorf("图片卡密组缺少图片 URL") - } - return "", card.ImageURL, nil - case "api": - return "", "", fmt.Errorf("自动化中心暂不支持 API 卡密动作") - default: - return "", "", fmt.Errorf("未知卡密类型: %s", card.Type) - } -} - -func (c *Center) sendText(ctx context.Context, task Task, text string) error { - if task.ChatID == "" || task.BuyerID == "" { - return fmt.Errorf("%w: 发送消息缺少 chat_id 或 buyer_id", ErrMessageNotSent) - } - if c.senders == nil { - return fmt.Errorf("%w: 账号发送器未初始化", ErrMessageNotSent) - } - sender, ok := c.senders.Sender(task.AccountID) - if !ok { - return fmt.Errorf("%w: 账号未在线,无法发送自动化消息", ErrMessageNotSent) - } - return sender.SendText(ctx, task.ChatID, task.BuyerID, text) + return c.actions.cardContent(ctx, card) } +// sendImage 将图片消息发送委托给发货动作执行器。 func (c *Center) sendImage(ctx context.Context, task Task, imageURL string, cardID int64) error { - if task.ChatID == "" || task.BuyerID == "" { - return fmt.Errorf("%w: 发送图片缺少 chat_id 或 buyer_id", ErrMessageNotSent) - } - if c.senders == nil { - return fmt.Errorf("%w: 账号发送器未初始化", ErrMessageNotSent) - } - sender, ok := c.senders.Sender(task.AccountID) - if !ok { - return fmt.Errorf("%w: 账号未在线,无法发送自动化图片", ErrMessageNotSent) - } - return sender.SendImage(ctx, task.ChatID, task.BuyerID, imageURL, cardID) + return c.actions.sendImage(ctx, task, imageURL, cardID) } +// cookieValue 读取账号 Cookie 的兼容入口。 func (c *Center) cookieValue(ctx context.Context, cookieID string) (string, error) { - if c.cookieSrc != nil { - return c.cookieSrc(ctx, cookieID) - } - value, err := c.store.Cookies.GetValue(ctx, cookieID) // value 是只读取账号 Cookie 明文的单值结果,不会展开完整账号详情。 - if err != nil { - return "", err - } - return value, nil + return c.actions.cookieValue(ctx, cookieID) } func buildTriggerKey(task Task) string { @@ -953,22 +656,3 @@ func buildTriggerKey(task Task) string { } return "" } - -func renderTemplate(tpl string, task Task) string { - out := tpl - repl := map[string]string{ - "{order_id}": task.OrderID, - "{item_id}": task.ItemID, - "{buyer_id}": task.BuyerID, - "{chat_id}": task.ChatID, - "{trigger_type}": task.TriggerType, - "{spec_name}": task.SpecName, - "{spec_value}": task.SpecValue, - "{quantity}": task.Quantity, - "{amount}": task.Amount, - } - for k, v := range repl { - out = strings.ReplaceAll(out, k, v) - } - return out -} diff --git a/internal/automation/delivery_notifier.go b/internal/automation/delivery_notifier.go new file mode 100644 index 0000000..d9fff76 --- /dev/null +++ b/internal/automation/delivery_notifier.go @@ -0,0 +1,60 @@ +package automation + +import ( + "fmt" + + "xianyu-go/internal/db" +) + +// deliveryNotifier 将自动化运行状态转换为可选的多渠道发货结果通知,并通过回调读取运行时替换的通知器。 +type deliveryNotifier struct { + // current 返回当前生效的通知器实例。 + current func() Notifier +} + +// notifyResult 根据规则执行结果发送通知,成功且实际发出内容时才发送成功通知。 +func (n deliveryNotifier) notifyResult(task Task, status string, sent int, errMsg string) { + // notifier 是当前可选的外部通知器。 + notifier := n.current() + if notifier == nil { + return + } + // triggerName 是面向用户展示的自动化触发类型名称。 + triggerName := map[string]string{ + TriggerOrderPaid: "付款发货", + TriggerBuyerReviewed: "评价赠品", + TriggerReviewMissingTimeout: "求评价", + }[task.TriggerType] + if triggerName == "" { + triggerName = task.TriggerType + } + if status == "success" { + if sent <= 0 { + return + } + // message 是成功通知正文。 + message := fmt.Sprintf("✅ %s成功(订单 %s,已发送 %d 条)", triggerName, task.OrderID, sent) + notifier.NotifyDelivery(task.AccountID, "", task.BuyerID, task.ItemID, message, task.ChatID) + return + } + // message 是失败或人工核对通知正文。 + message := fmt.Sprintf("🚨 %s失败(订单 %s):%s", triggerName, task.OrderID, errMsg) + notifier.NotifyDelivery(task.AccountID, "", task.BuyerID, task.ItemID, message, task.ChatID) +} + +// notifyRunNeedsReview 通知运行需要人工核对,并复用统一结果通知格式。 +func (n deliveryNotifier) notifyRunNeedsReview(run db.AutomationRun, reason string) { + if n.current() == nil { + return + } + // task 是从运行快照构造出的最小通知上下文。 + task := Task{ + AccountID: run.CookieID, + BuyerID: run.BuyerID, + ItemID: run.ItemID, + ChatID: run.ChatID, + OrderID: run.OrderID, + TriggerType: run.TriggerType, + } + n.notifyResult(task, "needs_review", run.SentCount, "需要人工核对:"+reason) +}