@chenshu2026/qianchuan-auto 1.0.0 → 1.0.2
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/README.md +91 -14
- package/data/ruleset.json +27 -20
- package/index.js +78 -36
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -16,20 +16,86 @@
|
|
|
16
16
|
- **每日建量**:06:10 提议建 直投-放 / 主-放 / 次-放(首次确认)
|
|
17
17
|
- **账本**:`data/ops_ledger.jsonl`,记录每次加预算/调价,卡单日≤4次。
|
|
18
18
|
|
|
19
|
-
|
|
19
|
+
---
|
|
20
|
+
|
|
21
|
+
## 一、安装(5 步)
|
|
20
22
|
|
|
21
23
|
1. **拿到插件**:解压 `qianchuan-auto` 到他本地,例如 `C:\Users\他\qianchuan-auto`。
|
|
22
|
-
2. **安装**:DSH → Plugins → **Add plugin** →
|
|
23
|
-
|
|
24
|
-
-
|
|
25
|
-
- `
|
|
26
|
-
|
|
27
|
-
|
|
24
|
+
2. **安装**:DSH → Plugins → **Add plugin** →
|
|
25
|
+
- 输入包名 `@chenshu2026/qianchuan-auto`(**安装源选「npm 官方源」**,镜像可能只有占位版),或
|
|
26
|
+
- 输入插件文件夹的绝对路径(本地装),或
|
|
27
|
+
- 让 DSH 的 agent 调 `plugin_manager install_bundle`(target = 文件夹路径)。
|
|
28
|
+
装完点 **Enable now**。
|
|
29
|
+
3. **改账户**(详见下方「二、新用户上手」第 1 步)
|
|
30
|
+
4. **授权**(详见「二、新用户上手」第 2 步)
|
|
28
31
|
5. **启用自动化**:
|
|
29
32
|
- `cordis.patch.yml` 的 `config.polling.enabled: true`(每 30 分钟自动跑),或
|
|
30
33
|
- 建 DSH 定时任务,每 30 分钟调 `qianchuan_engine_run`。
|
|
31
34
|
|
|
32
|
-
|
|
35
|
+
---
|
|
36
|
+
|
|
37
|
+
## 二、新用户上手(第 3、4 步详解)
|
|
38
|
+
|
|
39
|
+
### 第 1 步:改 `data/ruleset.json`
|
|
40
|
+
|
|
41
|
+
**① 找到文件**
|
|
42
|
+
|
|
43
|
+
- 用 **npm 包装的**:
|
|
44
|
+
```
|
|
45
|
+
C:\Users\<用户名>\.dsh\profiles\desktop\node_modules\@chenshu2026\qianchuan-auto\data\ruleset.json
|
|
46
|
+
```
|
|
47
|
+
- 用 **本地文件夹装的**:
|
|
48
|
+
```
|
|
49
|
+
<插件文件夹>\data\ruleset.json
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
> 找不到就直接问 DSH 的 agent:「千川插件的 ruleset.json 在哪?」
|
|
53
|
+
|
|
54
|
+
**② 用记事本打开**(右键 → 打开方式 → 记事本,或 VS Code)
|
|
55
|
+
|
|
56
|
+
**③ 改这两行**
|
|
57
|
+
|
|
58
|
+
```json
|
|
59
|
+
"account": {
|
|
60
|
+
"advertiserId": "",
|
|
61
|
+
"planId": "",
|
|
62
|
+
"planName": ""
|
|
63
|
+
}
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
- `advertiserId`:广告主 ID(千川后台 → 账户信息里那串数字;或让 agent 调 `qianchuan_list_advertisers` 列出)
|
|
67
|
+
- `planId`:乘方计划 ID(千川后台 → 乘方计划列表 → 点开计划看 URL/详情;或让 agent 调 `qianchuan_uni_promotion` 的 list 查)
|
|
68
|
+
|
|
69
|
+
**④ 保存 → 关掉**
|
|
70
|
+
|
|
71
|
+
### 第 2 步:授权他自己的账户
|
|
72
|
+
|
|
73
|
+
`qianchuan_*` 是 DSH 插件工具,**不用自己敲命令**,在 DSH 对话框里跟 agent 说即可:
|
|
74
|
+
|
|
75
|
+
1. **保存 App ID / Secret**
|
|
76
|
+
> 帮我保存千川凭据,app_id 是 `1234567890`,secret 是 `abcdef...`
|
|
77
|
+
→ agent 调 `qianchuan_save_credentials`
|
|
78
|
+
|
|
79
|
+
2. **生成授权链接**
|
|
80
|
+
> 生成千川授权链接
|
|
81
|
+
→ agent 调 `qianchuan_get_auth_url`,给你一条链接
|
|
82
|
+
|
|
83
|
+
3. **浏览器授权**
|
|
84
|
+
打开链接 → 登录千川 → 同意授权 → 回调页会带一个 **`auth_code`** → 复制它
|
|
85
|
+
|
|
86
|
+
4. **用 auth_code 完成授权**
|
|
87
|
+
> 用 auth_code 是 `xxxxx`,完成千川授权
|
|
88
|
+
→ agent 调 `qianchuan_save_credentials`(带 `auth_code`)→ 换取 `access_token`/`refresh_token`
|
|
89
|
+
|
|
90
|
+
5. **验证**
|
|
91
|
+
> 看下千川授权状态
|
|
92
|
+
→ agent 调 `qianchuan_status`,能看到账户列表就成功
|
|
93
|
+
|
|
94
|
+
> 授权需要**自己的千川开放平台应用**(App ID / Secret),不能共用别人的。
|
|
95
|
+
|
|
96
|
+
---
|
|
97
|
+
|
|
98
|
+
## 三、配置
|
|
33
99
|
|
|
34
100
|
`cordis.patch.yml` 的 `config`:
|
|
35
101
|
|
|
@@ -43,7 +109,7 @@ config:
|
|
|
43
109
|
intervalMinutes: 30
|
|
44
110
|
```
|
|
45
111
|
|
|
46
|
-
##
|
|
112
|
+
## 四、规则参数(`data/ruleset.json` 的 `params`)
|
|
47
113
|
|
|
48
114
|
```json
|
|
49
115
|
"params": {
|
|
@@ -58,14 +124,25 @@ config:
|
|
|
58
124
|
|
|
59
125
|
新增/修改规则 = 改 `params` 或 `dailyCreate`,**不用改代码**。
|
|
60
126
|
|
|
61
|
-
##
|
|
127
|
+
## 五、注意
|
|
62
128
|
|
|
63
129
|
- **凭据不打包**:每位使用者用自己的 App ID/Secret 授权,插件目录不含任何密钥。
|
|
64
|
-
- **19 位 material_id
|
|
130
|
+
- **19 位 material_id 精度**:建任务时用精确整数(引擎已处理),不要直接用 JS 数字。
|
|
65
131
|
- **R4/R7/R8 与每日建量是「首次触发需确认」**,不会自动删任务。
|
|
66
132
|
- **接口频控**:引擎有「指标全 0 则整轮跳过」的护栏,避免误触发。
|
|
133
|
+
- **npm 镜像可能滞后**:安装时若报「没有声明 dsh.bundle」,说明镜像只有占位版 `0.0.0-stage`,请把安装源切到 npm 官方源。
|
|
134
|
+
|
|
135
|
+
## 六、分享前建议
|
|
67
136
|
|
|
68
|
-
|
|
137
|
+
- 清空 `data/rule_state.json`(`snapshots` 置空)和 `data/ops_ledger.jsonl`(清空)。
|
|
138
|
+
- 保留 `data/ruleset.json` 作为模板,把 `account.advertiserId/planId` 留成占位符。
|
|
139
|
+
|
|
140
|
+
## 七、发版(维护者)
|
|
141
|
+
|
|
142
|
+
```powershell
|
|
143
|
+
# 改 package.json 的 version(如 1.0.1)后:
|
|
144
|
+
cd <插件目录>
|
|
145
|
+
pnpm publish --access public --no-git-checks
|
|
146
|
+
```
|
|
69
147
|
|
|
70
|
-
|
|
71
|
-
- 保留 `data/ruleset.json` 作为模板,把 `account.advertiserId/planId` 留成占位符,提醒对方修改。
|
|
148
|
+
> 发布需要 npm 2FA 或「Bypass 2FA」的 granular token。新包首个版本可能先出现 `0.0.0-stage` 占位,待 npm 审核通过后 `latest` 指向真实版本。
|
package/data/ruleset.json
CHANGED
|
@@ -1,51 +1,58 @@
|
|
|
1
1
|
{
|
|
2
2
|
"rulesetName": "千川乘方自动化投放规则集(自包含)",
|
|
3
|
-
"version": "2026-12-
|
|
3
|
+
"version": "2026-12-03",
|
|
4
4
|
"account": {
|
|
5
5
|
"advertiserId": "",
|
|
6
6
|
"planId": "",
|
|
7
|
-
"planName": "
|
|
7
|
+
"planName": "填你的乘方计划名"
|
|
8
8
|
},
|
|
9
9
|
"params": {
|
|
10
10
|
"R4": { "enabled": true, "roiFactor": 0.5, "minCost": 500 },
|
|
11
|
-
"R5": { "enabled": true, "boostRatio": 9, "boostAdd": 500, "controlSpendPct": 0.8, "controlMinRoi": 10, "controlAdd": 1000, "dailyLimit":
|
|
12
|
-
"R6": { "enabled": true, "lowPct": 0.25, "highPct": 0.75, "bidUp": 1.066, "bidDown": 0.934, "bidMin": 250, "bidMax":
|
|
13
|
-
"R7": { "enabled": true, "minAgeHours": 2, "roiFactor": 0.7 },
|
|
14
|
-
"R8": { "enabled": true, "consecutiveRuns": 4 },
|
|
15
|
-
"dailyCreate": { "enabled": true, "roiFactor": 0.8, "top": 9, "from": 10, "to": 18, "budgetPerHour": 100 }
|
|
11
|
+
"R5": { "enabled": true, "boostRatio": 9, "boostAdd": 500, "controlSpendPct": 0.8, "controlMinRoi": 10, "controlAdd": 1000, "dailyLimit": 8 },
|
|
12
|
+
"R6": { "enabled": true, "lowPct": 0.25, "highPct": 0.75, "bidUp": 1.066, "bidDown": 0.934, "bidMin": 250, "bidMax": 330, "dailyLimit": 2 },
|
|
13
|
+
"R7": { "enabled": true, "minAgeHours": 2, "roiFactor": 0.7, "minCost": 400 },
|
|
14
|
+
"R8": { "enabled": true, "consecutiveRuns": 4, "roiBelowAvg": true, "minCost": 400 },
|
|
15
|
+
"dailyCreate": { "enabled": true, "roiFactor": 0.8, "top": 9, "from": 10, "to": 18, "budgetPerHour": 100 },
|
|
16
|
+
"zhitou": { "roomMaterialId": "", "materialType": "LIVE_ROOM" },
|
|
17
|
+
"material": { "lookbackDays": 4, "mode": "natural_days" }
|
|
18
|
+
},
|
|
19
|
+
"rebuild": {
|
|
20
|
+
"control": { "budget": 2000, "bid": null, "duration": "平台默认(控成本追投不支持自定义调控时长)" },
|
|
21
|
+
"boost": { "budget": "时长 × 100", "bid": null, "duration": "到次日 01:00" }
|
|
16
22
|
},
|
|
17
23
|
"dailyCreate": {
|
|
18
24
|
"openCheck": "DELIVERY_OK / DELIVERYING 才继续,否则跳过",
|
|
19
25
|
"duration": "创建时刻 → 次日 01:00 的小时数",
|
|
20
26
|
"tasks": [
|
|
21
27
|
{ "name": "直投-放", "material": "直播间画面素材", "mode": "放量" },
|
|
22
|
-
{ "name": "主-放", "material": "近
|
|
23
|
-
{ "name": "次-放", "material": "近
|
|
28
|
+
{ "name": "主-放", "material": "近4天 · 消耗降序 · ROI≥平均×80% · 前9条", "mode": "放量" },
|
|
29
|
+
{ "name": "次-放", "material": "近4天 · 消耗降序 · ROI≥平均×80% · 第10~18条", "mode": "放量" }
|
|
24
30
|
],
|
|
25
31
|
"budget": "时长 × 100",
|
|
26
32
|
"disabled": ["高ROI-放"]
|
|
27
33
|
},
|
|
28
34
|
"monitorRules": [
|
|
29
|
-
{ "id": "R4", "name": "ROI过低", "condition": "总ROI < 素材平均×50%,累计消耗≥500", "action": "
|
|
30
|
-
{ "id": "R5", "name": "加预算", "condition": "控成本:消耗>预算×80% 且 ROI≥10;放量:成交÷预算≥9", "action": "控成本 +1000;放量 +500;单日限
|
|
31
|
-
{ "id": "R6", "name": "控成本调价", "condition": "控成本:Δ<上一个小时消耗×25% → 出价×1.066;Δ>75% → 出价×0.934", "action": "
|
|
32
|
-
{ "id": "R7", "name": "控成本超2小时低ROI", "condition": "控成本:消耗时长>2h 且 总ROI<素材平均×70%", "action": "
|
|
33
|
-
{ "id": "R8", "name": "连续4次无新增成交", "condition": "所有任务:连续4次巡检成交无新增", "action": "
|
|
35
|
+
{ "id": "R4", "name": "ROI过低", "condition": "总ROI < 素材平均×50%,累计消耗≥500", "action": "删除重建(自动)" },
|
|
36
|
+
{ "id": "R5", "name": "加预算", "condition": "控成本:消耗>预算×80% 且 ROI≥10;放量:成交÷预算≥9", "action": "控成本 +1000;放量 +500;单日限8次" },
|
|
37
|
+
{ "id": "R6", "name": "控成本调价", "condition": "控成本:Δ<上一个小时消耗×25% → 出价×1.066;Δ>75% → 出价×0.934", "action": "取整;自动执行;单日≤2次" },
|
|
38
|
+
{ "id": "R7", "name": "控成本超2小时低ROI", "condition": "控成本:消耗时长>2h 且 总ROI<素材平均×70% 且 消耗>400", "action": "删除重建(自动)" },
|
|
39
|
+
{ "id": "R8", "name": "连续4次无新增成交", "condition": "所有任务:连续4次巡检成交无新增 且 总ROI<素材平均ROI 且 消耗>400(保护:高ROI不重建)", "action": "删除重建(自动)" }
|
|
34
40
|
],
|
|
35
41
|
"guards": {
|
|
36
42
|
"bidMin": 250,
|
|
37
|
-
"bidMax":
|
|
43
|
+
"bidMax": 330,
|
|
38
44
|
"maxRebuildPerTaskPerDay": 6,
|
|
39
|
-
"maxBudgetAddPerTaskPerDay":
|
|
45
|
+
"maxBudgetAddPerTaskPerDay": 8,
|
|
40
46
|
"readonlyWindow": "00:00-05:59",
|
|
47
|
+
"excludeFromRebuild": ["测"],
|
|
41
48
|
"ledgerPath": "data/ops_ledger.jsonl"
|
|
42
49
|
},
|
|
43
50
|
"execution": {
|
|
44
|
-
"R4": { "mode": "
|
|
51
|
+
"R4": { "mode": "auto" },
|
|
45
52
|
"R5": { "mode": "auto" },
|
|
46
53
|
"R6": { "mode": "auto" },
|
|
47
|
-
"R7": { "mode": "
|
|
48
|
-
"R8": { "mode": "
|
|
49
|
-
"dailyCreate": { "mode": "
|
|
54
|
+
"R7": { "mode": "auto" },
|
|
55
|
+
"R8": { "mode": "auto" },
|
|
56
|
+
"dailyCreate": { "mode": "auto" }
|
|
50
57
|
}
|
|
51
58
|
}
|
package/index.js
CHANGED
|
@@ -781,13 +781,18 @@ function metricNum(v) {
|
|
|
781
781
|
return Number(v) || 0
|
|
782
782
|
}
|
|
783
783
|
|
|
784
|
+
function materialStart() {
|
|
785
|
+
const n = new Date()
|
|
786
|
+
return new Date(n.getFullYear(), n.getMonth(), n.getDate() - 3, 0, 0, 0)
|
|
787
|
+
}
|
|
788
|
+
|
|
784
789
|
function pad2(n) { return String(n).padStart(2, '0') }
|
|
785
790
|
function fmtDay(d) { return `${d.getFullYear()}-${pad2(d.getMonth() + 1)}-${pad2(d.getDate())}` }
|
|
786
791
|
function fmtDateTime(d) { return `${fmtDay(d)} ${pad2(d.getHours())}:${pad2(d.getMinutes())}:${pad2(d.getSeconds())}` }
|
|
787
792
|
|
|
788
|
-
function countTodayAdds(ledger, taskId) {
|
|
793
|
+
function countTodayAdds(ledger, taskId, action = 'BUDGET_ADD') {
|
|
789
794
|
const today = fmtDay(new Date())
|
|
790
|
-
return ledger.filter((r) => String(r.ts || '').startsWith(today) && String(r.task_id) === String(taskId) && r.action ===
|
|
795
|
+
return ledger.filter((r) => String(r.ts || '').startsWith(today) && String(r.task_id) === String(taskId) && r.action === action).length
|
|
791
796
|
}
|
|
792
797
|
|
|
793
798
|
function snapshotMap(state) {
|
|
@@ -825,15 +830,15 @@ async function pullTasks(token, advertiserId, planId, signal) {
|
|
|
825
830
|
|
|
826
831
|
async function pullMaterialAvg(token, advertiserId, signal) {
|
|
827
832
|
const end = new Date()
|
|
828
|
-
const start =
|
|
833
|
+
const start = materialStart()
|
|
829
834
|
const resp = await apiCall('GET', 'v1.0/qianchuan/report/uni_promotion/data/get/', {
|
|
830
835
|
query: {
|
|
831
836
|
advertiser_id: advertiserId,
|
|
832
837
|
data_topic: 'OVERALL_ROI_LIVE_MATERIAL_VIDEO',
|
|
833
838
|
dimensions: ['stat_time_day'],
|
|
834
|
-
metrics: ['
|
|
839
|
+
metrics: ['stat_cost_for_roi2', 'total_prepay_and_pay_order_roi2'],
|
|
835
840
|
filters: [{ field: 'roi2_material_type_v3', operator: 7, values: ['3'] }],
|
|
836
|
-
order_by: [{ field: '
|
|
841
|
+
order_by: [{ field: 'stat_cost_for_roi2', type: 1 }],
|
|
837
842
|
start_time: fmtDateTime(start),
|
|
838
843
|
end_time: fmtDateTime(end),
|
|
839
844
|
},
|
|
@@ -844,23 +849,24 @@ async function pullMaterialAvg(token, advertiserId, signal) {
|
|
|
844
849
|
let gmv = 0
|
|
845
850
|
for (const row of (resp.data && resp.data.rows) || []) {
|
|
846
851
|
const m = (row && row.metrics) || {}
|
|
847
|
-
|
|
848
|
-
|
|
852
|
+
const c = metricNum(m.stat_cost_for_roi2)
|
|
853
|
+
cost += c
|
|
854
|
+
gmv += metricNum(m.total_prepay_and_pay_order_roi2) * c
|
|
849
855
|
}
|
|
850
856
|
return cost > 0 ? gmv / cost : 0
|
|
851
857
|
}
|
|
852
858
|
|
|
853
859
|
async function pullMaterials(token, advertiserId, signal) {
|
|
854
860
|
const end = new Date()
|
|
855
|
-
const start =
|
|
861
|
+
const start = materialStart()
|
|
856
862
|
const resp = await apiCall('GET', 'v1.0/qianchuan/report/uni_promotion/data/get/', {
|
|
857
863
|
query: {
|
|
858
864
|
advertiser_id: advertiserId,
|
|
859
865
|
data_topic: 'OVERALL_ROI_LIVE_MATERIAL_VIDEO',
|
|
860
866
|
dimensions: ['material_id'],
|
|
861
|
-
metrics: ['
|
|
867
|
+
metrics: ['stat_cost_for_roi2', 'total_prepay_and_pay_order_roi2'],
|
|
862
868
|
filters: [{ field: 'roi2_material_type_v3', operator: 7, values: ['3'] }],
|
|
863
|
-
order_by: [{ field: '
|
|
869
|
+
order_by: [{ field: 'stat_cost_for_roi2', type: 2 }],
|
|
864
870
|
page_size: 50,
|
|
865
871
|
start_time: fmtDateTime(start),
|
|
866
872
|
end_time: fmtDateTime(end),
|
|
@@ -872,9 +878,9 @@ async function pullMaterials(token, advertiserId, signal) {
|
|
|
872
878
|
return rows.map((row) => {
|
|
873
879
|
const id = row.dimensions && row.dimensions.material_id && (row.dimensions.material_id.ValueStr || row.dimensions.material_id.Value)
|
|
874
880
|
const m = row.metrics || {}
|
|
875
|
-
const cost = metricNum(m.
|
|
876
|
-
const
|
|
877
|
-
return { material_id: String(id), cost, gmv
|
|
881
|
+
const cost = metricNum(m.stat_cost_for_roi2)
|
|
882
|
+
const roi = metricNum(m.total_prepay_and_pay_order_roi2)
|
|
883
|
+
return { material_id: String(id), cost, gmv: roi * cost, roi }
|
|
878
884
|
})
|
|
879
885
|
}
|
|
880
886
|
|
|
@@ -886,19 +892,21 @@ async function updateBudget(token, advertiserId, planId, taskId, budget, signal)
|
|
|
886
892
|
})
|
|
887
893
|
}
|
|
888
894
|
|
|
889
|
-
async function updateBid(token, advertiserId, planId, task, newBid, signal) {
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
},
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
}
|
|
895
|
+
async function updateBid(token, advertiserId, planId, task, newBid, signal, materialOpt) {
|
|
896
|
+
const adv = Number(advertiserId)
|
|
897
|
+
const plan = Number(planId)
|
|
898
|
+
const tid = Number(task.id)
|
|
899
|
+
const name = JSON.stringify(task.name || '')
|
|
900
|
+
const budget = Number(task.budget)
|
|
901
|
+
const bid = Number(newBid)
|
|
902
|
+
let extra = ''
|
|
903
|
+
if (materialOpt && materialOpt.roomMaterialId) {
|
|
904
|
+
extra = `,"room_material_id":${String(materialOpt.roomMaterialId)},"material_type":"LIVE_ROOM"`
|
|
905
|
+
} else if (materialOpt && Array.isArray(materialOpt.materialIds) && materialOpt.materialIds.length) {
|
|
906
|
+
extra = `,"material_ids":[${materialOpt.materialIds.map((x) => String(x)).join(',')}]`
|
|
907
|
+
}
|
|
908
|
+
const json = `{"advertiser_id":${adv},"ad_id":${plan},"task_id":${tid},"name":${name},"budget":${budget},"bid":${bid}${extra}}`
|
|
909
|
+
return rawPost('v1.0/qianchuan/uni_promotion/ad/control_task/update/', json, token, signal)
|
|
902
910
|
}
|
|
903
911
|
|
|
904
912
|
// ---- 创建/删除(自动执行用,material_ids 手写 JSON 保精度)----
|
|
@@ -980,11 +988,12 @@ async function runEngine(ctx, config, signal) {
|
|
|
980
988
|
return { skipped: 'no-data', message: '接口返回的任务指标全为 0(可能数据未回填或频控),本轮跳过,未执行任何动作', debug: { taskCount: tasks.length, firstMetrics: tasks[0] && tasks[0].metrics } }
|
|
981
989
|
}
|
|
982
990
|
|
|
983
|
-
const roomMaterialId = String((ruleset.params && ruleset.params.zhitou && ruleset.params.zhitou.roomMaterialId) || '
|
|
991
|
+
const roomMaterialId = String((ruleset.params && ruleset.params.zhitou && ruleset.params.zhitou.roomMaterialId) || '')
|
|
984
992
|
let materialAvg = 0
|
|
985
993
|
try { materialAvg = await pullMaterialAvg(token, advertiserId, signal) } catch { materialAvg = 0 }
|
|
986
994
|
|
|
987
995
|
const now = new Date()
|
|
996
|
+
const readonly = now.getHours() < 6
|
|
988
997
|
const tsNow = fmtDateTime(now)
|
|
989
998
|
const byTs = snapshotMap(state)
|
|
990
999
|
const tsKeys = [...byTs.keys()].sort()
|
|
@@ -1012,6 +1021,21 @@ async function runEngine(ctx, config, signal) {
|
|
|
1012
1021
|
const eligible = list.filter((m) => m.roi >= threshold)
|
|
1013
1022
|
return eligible.slice(Math.max(0, from - 1), to).map((m) => m.material_id)
|
|
1014
1023
|
}
|
|
1024
|
+
async function exactMaterialOpt(task) {
|
|
1025
|
+
const list = Array.isArray(task.material_list) ? task.material_list : []
|
|
1026
|
+
if (list.length === 1 && roomMaterialId && Number(list[0] && list[0].material_id) === Number(roomMaterialId)) {
|
|
1027
|
+
return { roomMaterialId }
|
|
1028
|
+
}
|
|
1029
|
+
const mats = await getRebuildMaterials()
|
|
1030
|
+
const ids = []
|
|
1031
|
+
for (const mm of list) {
|
|
1032
|
+
const raw = Number(mm && mm.material_id)
|
|
1033
|
+
if (!Number.isFinite(raw)) continue
|
|
1034
|
+
const hit = mats.find((r) => Number(r.material_id) === raw)
|
|
1035
|
+
if (hit) ids.push(hit.material_id)
|
|
1036
|
+
}
|
|
1037
|
+
return ids.length ? { materialIds: ids } : null
|
|
1038
|
+
}
|
|
1015
1039
|
async function autoRebuild(rule, task, reason, roomMaterialId) {
|
|
1016
1040
|
const id = String(task.id)
|
|
1017
1041
|
const name = task.name || ''
|
|
@@ -1031,7 +1055,7 @@ async function runEngine(ctx, config, signal) {
|
|
|
1031
1055
|
const bidNum = Number(task.bid) || 315
|
|
1032
1056
|
created = await createControlTask(token, advertiserId, planId, { name, budget: 2000, bid: Math.max(250, Math.min(350, Math.round(bidNum))), ...matOpt }, signal)
|
|
1033
1057
|
} else {
|
|
1034
|
-
const hours = Math.max(0.5, Math.round(((new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1, 1, 0, 0) - now) / 3600000) * 2) / 2)
|
|
1058
|
+
const hours = Math.min(24, Math.max(0.5, Math.round(((new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1, 1, 0, 0) - now) / 3600000) * 2) / 2))
|
|
1035
1059
|
created = await createBoostTask(token, advertiserId, planId, { name, budget: Math.round(hours * 100), duration: hours, ...matOpt }, signal)
|
|
1036
1060
|
}
|
|
1037
1061
|
actions.push({ rule, task_id: id, name, action: 'REBUILD', new_task_id: String((created.data && created.data.id) || ''), reason })
|
|
@@ -1044,7 +1068,10 @@ async function runEngine(ctx, config, signal) {
|
|
|
1044
1068
|
const id = String(task.id)
|
|
1045
1069
|
const name = task.name || ''
|
|
1046
1070
|
const isTest = /测/.test(String(name))
|
|
1071
|
+
if (readonly) continue
|
|
1047
1072
|
const type = task.smart_bid_type
|
|
1073
|
+
const taskStatus = String(task.task_status || '')
|
|
1074
|
+
const liveOn = taskStatus !== 'OFFLINE_TIME' && taskStatus !== 'LIVE_ROOM_OFF'
|
|
1048
1075
|
const budget = Number(task.budget) || 0
|
|
1049
1076
|
const bid = task.bid === null || task.bid === undefined ? null : Number(task.bid)
|
|
1050
1077
|
const m = task.metrics || {}
|
|
@@ -1052,6 +1079,21 @@ async function runEngine(ctx, config, signal) {
|
|
|
1052
1079
|
const gmv = metricNum(m.total_pay_order_gmv_include_coupon_for_roi2_assist)
|
|
1053
1080
|
const orderCnt = metricNum(m.total_pay_order_count_for_roi2_assist)
|
|
1054
1081
|
const roi = metricNum(m.total_prepay_and_pay_order_roi2_assist)
|
|
1082
|
+
const allRuns = tsKeys.map((k) => byTs.get(k) && byTs.get(k).get(id)).filter(Boolean)
|
|
1083
|
+
const activeRuns = []
|
|
1084
|
+
let offlineHours = 0
|
|
1085
|
+
for (let i = 1; i < allRuns.length; i++) {
|
|
1086
|
+
if (Number(allRuns[i].cost) > Number(allRuns[i - 1].cost)) {
|
|
1087
|
+
activeRuns.push(allRuns[i])
|
|
1088
|
+
} else {
|
|
1089
|
+
const a = Date.parse(String(allRuns[i - 1].ts).replace(/-/g, '/'))
|
|
1090
|
+
const b = Date.parse(String(allRuns[i].ts).replace(/-/g, '/'))
|
|
1091
|
+
if (Number.isFinite(a) && Number.isFinite(b)) offlineHours += (b - a) / 3600000
|
|
1092
|
+
}
|
|
1093
|
+
}
|
|
1094
|
+
const createdAtMs = Date.parse(String(task.create_time || '').replace(/-/g, '/'))
|
|
1095
|
+
const totalHours = Number.isFinite(createdAtMs) ? (now.getTime() - createdAtMs) / 3600000 : 0
|
|
1096
|
+
const liveHours = Math.max(0, totalHours - offlineHours)
|
|
1055
1097
|
const createdAt = Date.parse(String(task.create_time || '').replace(/-/g, '/'))
|
|
1056
1098
|
const ageHours = Number.isFinite(createdAt) ? (now.getTime() - createdAt) / 3600000 : 0
|
|
1057
1099
|
|
|
@@ -1087,7 +1129,7 @@ async function runEngine(ctx, config, signal) {
|
|
|
1087
1129
|
}
|
|
1088
1130
|
|
|
1089
1131
|
// R6 控成本调价(自动)
|
|
1090
|
-
if (type === 'SMART_BID_CUSTOM' && bid !== null && (P.R6 === undefined || P.R6.enabled !== false)) {
|
|
1132
|
+
if (type === 'SMART_BID_CUSTOM' && bid !== null && (P.R6 === undefined || P.R6.enabled !== false) && countTodayAdds(ledger, id, 'BID_ADJUST') < ((P.R6 && P.R6.dailyLimit) ?? 2)) {
|
|
1091
1133
|
const r6 = P.R6 || {}
|
|
1092
1134
|
const prevCost = prevKey && byTs.get(prevKey) && byTs.get(prevKey).get(id) ? Number(byTs.get(prevKey).get(id).cost) : undefined
|
|
1093
1135
|
const oneCost = oneHourKey && byTs.get(oneHourKey) && byTs.get(oneHourKey).get(id) ? Number(byTs.get(oneHourKey).get(id).cost) : undefined
|
|
@@ -1102,7 +1144,7 @@ async function runEngine(ctx, config, signal) {
|
|
|
1102
1144
|
newBid = Math.max(r6.bidMin ?? 250, Math.min(r6.bidMax ?? 350, newBid))
|
|
1103
1145
|
if (newBid !== bid) {
|
|
1104
1146
|
try {
|
|
1105
|
-
await updateBid(token, advertiserId, planId, task, newBid, signal)
|
|
1147
|
+
await updateBid(token, advertiserId, planId, task, newBid, signal, await exactMaterialOpt(task))
|
|
1106
1148
|
const entry = { ts: tsNow, task_id: id, task_name: name, action: 'BID_ADJUST', before: bid, after: newBid, delta: newBid - bid, reason, request_id: '' }
|
|
1107
1149
|
await appendLedger(ledgerPath, entry)
|
|
1108
1150
|
ledger.push(entry)
|
|
@@ -1121,15 +1163,15 @@ async function runEngine(ctx, config, signal) {
|
|
|
1121
1163
|
await autoRebuild('R4', task, `ROI ${roi.toFixed(2)} < 素材平均${materialAvg.toFixed(2)}×${P.R4?.roiFactor ?? 0.5}`, roomMaterialId)
|
|
1122
1164
|
}
|
|
1123
1165
|
// R7:控成本 消耗时长>2h 且 ROI < 平均×70% → 删除重建(自动)
|
|
1124
|
-
if (type === 'SMART_BID_CUSTOM' && (P.R7 === undefined || P.R7.enabled !== false) &&
|
|
1125
|
-
await autoRebuild('R7', task,
|
|
1166
|
+
if (cost > (P.R7?.minCost ?? 400) && liveOn && type === 'SMART_BID_CUSTOM' && (P.R7 === undefined || P.R7.enabled !== false) && liveHours > (P.R7?.minAgeHours ?? 2) && roi < materialAvg * (P.R7?.roiFactor ?? 0.7)) {
|
|
1167
|
+
await autoRebuild('R7', task, `控成本已开播 ${liveHours.toFixed(1)}h,ROI ${roi.toFixed(2)} < 平均×${P.R7?.roiFactor ?? 0.7}`, roomMaterialId)
|
|
1126
1168
|
}
|
|
1127
1169
|
}
|
|
1128
1170
|
|
|
1129
1171
|
// R8:连续 N 次巡检累计成交无新增 → 删除重建(自动;仅当 ROI 低于素材平均时)
|
|
1130
|
-
if (!isTest && materialAvg > 0 && roi < materialAvg && (P.R8 === undefined || P.R8.enabled !== false)) {
|
|
1172
|
+
if (!isTest && cost > (P.R8?.minCost ?? 400) && liveOn && materialAvg > 0 && roi < materialAvg && (P.R8 === undefined || P.R8.enabled !== false)) {
|
|
1131
1173
|
const n = P.R8?.consecutiveRuns ?? 4
|
|
1132
|
-
const runs =
|
|
1174
|
+
const runs = activeRuns.slice(-n)
|
|
1133
1175
|
if (runs.length >= n && runs.every((s) => Number(s.gmv) === runs[0].gmv)) {
|
|
1134
1176
|
await autoRebuild('R8', task, `连续 ${n} 次巡检成交未新增(gmv=${gmv})`, roomMaterialId)
|
|
1135
1177
|
}
|
|
@@ -1142,7 +1184,7 @@ async function runEngine(ctx, config, signal) {
|
|
|
1142
1184
|
const today = fmtDay(now)
|
|
1143
1185
|
if (state.dailyCreateDate !== today) {
|
|
1144
1186
|
try {
|
|
1145
|
-
const hours = Math.max(0.5, Math.round(((new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1, 1, 0, 0) - now) / 3600000) * 2) / 2)
|
|
1187
|
+
const hours = Math.min(24, Math.max(0.5, Math.round(((new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1, 1, 0, 0) - now) / 3600000) * 2) / 2))
|
|
1146
1188
|
const budget = Math.round(hours * 100)
|
|
1147
1189
|
const top9 = await selectMaterials(daily.roiFactor ?? 0.8, 1, daily.top ?? 9)
|
|
1148
1190
|
const range = await selectMaterials(daily.roiFactor ?? 0.8, daily.from ?? 10, daily.to ?? 18)
|
|
@@ -1168,7 +1210,7 @@ async function runEngine(ctx, config, signal) {
|
|
|
1168
1210
|
}
|
|
1169
1211
|
|
|
1170
1212
|
// 写快照
|
|
1171
|
-
state.snapshots = (state.snapshots || []).filter((s) => !tsKeys.slice(0, Math.max(0, tsKeys.length -
|
|
1213
|
+
state.snapshots = (state.snapshots || []).filter((s) => !tsKeys.slice(0, Math.max(0, tsKeys.length - 12)).includes(s.ts))
|
|
1172
1214
|
if (!state.snapshots.some((s) => s.ts === tsNow)) {
|
|
1173
1215
|
for (const task of tasks) {
|
|
1174
1216
|
const m = task.metrics || {}
|