dsh-workbench-tasks 0.0.0-stage → 5.2.20

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.
Files changed (57) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +26 -2
  3. package/cordis.patch.yml +7 -0
  4. package/lib/client.js +11963 -0
  5. package/lib/db/db-core.js +432 -0
  6. package/lib/db/db-legacy.js +473 -0
  7. package/lib/db/db.js +97 -0
  8. package/lib/db/ownership-path.js +33 -0
  9. package/lib/db/timeline-schema.js +7 -0
  10. package/lib/db/workspace-schema.js +15 -0
  11. package/lib/index.js +232 -0
  12. package/lib/infra/backup.js +289 -0
  13. package/lib/infra/config.js +462 -0
  14. package/lib/infra/data.js +368 -0
  15. package/lib/infra/sync.js +189 -0
  16. package/lib/publisher/brief.js +76 -0
  17. package/lib/publisher/catalog.js +99 -0
  18. package/lib/publisher/command.js +81 -0
  19. package/lib/stats/activity-calendar.js +74 -0
  20. package/lib/stats/difficulty-bins.js +49 -0
  21. package/lib/stats/events.js +40 -0
  22. package/lib/stats/overview.js +99 -0
  23. package/lib/stats/stats-today.js +26 -0
  24. package/lib/stats/stats.js +589 -0
  25. package/lib/stats/timeline-stats.js +174 -0
  26. package/lib/tagging/source.js +89 -0
  27. package/lib/tagging/tag-options.js +99 -0
  28. package/lib/tagging/tagging.js +371 -0
  29. package/lib/task/model/task-difficulty.js +15 -0
  30. package/lib/task/model/task-model.js +256 -0
  31. package/lib/task/model/task-ownership-path.js +22 -0
  32. package/lib/task/model/task-priority.js +33 -0
  33. package/lib/task/read/task-discovery.js +123 -0
  34. package/lib/task/read/task-publish-filter.js +31 -0
  35. package/lib/task/read/task-query.js +351 -0
  36. package/lib/task/read/task-search-schema.js +34 -0
  37. package/lib/task/read/task-view.js +146 -0
  38. package/lib/task/write/task-bulk.js +247 -0
  39. package/lib/task/write/task-claim.js +229 -0
  40. package/lib/task/write/task-create-schema.js +34 -0
  41. package/lib/task/write/task-create.js +178 -0
  42. package/lib/task/write/task-operations.js +207 -0
  43. package/lib/task/write/task-target.js +56 -0
  44. package/lib/task/write/task-transaction.js +18 -0
  45. package/lib/task/write/task-update.js +104 -0
  46. package/lib/tasks.js +456 -0
  47. package/lib/timeline/task-timelines.js +110 -0
  48. package/lib/timeline/timeline-actions.js +69 -0
  49. package/lib/timeline/timeline-migration.js +70 -0
  50. package/lib/timeline/timeline-store.js +57 -0
  51. package/lib/timeline/timeline-sync.js +46 -0
  52. package/lib/tree/task-node-write.js +26 -0
  53. package/lib/tree/tree.js +517 -0
  54. package/lib/workspace/workspace-actions.js +217 -0
  55. package/lib/workspace/workspace-store.js +196 -0
  56. package/package.json +144 -4
  57. package/shared/tree/limits.cjs +3 -0
@@ -0,0 +1,174 @@
1
+ /**
2
+ * 时间线维度的只读统计:当前存量(总数、空线、归属、规模、Top 排行、逾期)
3
+ * 与可选的范围内事件分开返回,避免把「范围内没有任务」误读成「空线」。
4
+ * 口径与 tasks.timelines 列表一致:排除软删除任务/时间线/关联与已重启任务。
5
+ */
6
+ import { todayStr } from "../db/db.js";
7
+
8
+ const LIVE_TASK = "t.deleted_at IS NULL AND t.status!='3'";
9
+ const LIVE_ENT = "e.deleted_at IS NULL";
10
+ const MEMBERS = "task_timeline_link l JOIN task t ON t.id=l.task_id JOIN task_timeline e ON e.id=l.timeline_id";
11
+
12
+ export const TIMELINE_STATS_SCOPE = {
13
+ includeRestarted: false,
14
+ exclusion: "排除软删除任务、时间线与关联;已重启任务(status=3)不计入有效任务,因此与含已重启的任务总览数量不同",
15
+ membership: "归属以 task_timeline_link 有效关联判定,不看 task.timeline_key 兼容列",
16
+ activity: "lastActivityDate 取发布/完成/关闭日与创建/修改本地日的最大日期,计划 targetDate 不算活动",
17
+ overdue: "overdueCount = status=0 且 targetDate 早于今天",
18
+ empty: "空线指存活且有效任务数为 0 的时间线(含尚未添加任务、成员被移出/删除/重启)",
19
+ trend: "趋势按日期范围统计范围内事件;存量指标不随范围变化,范围内没有任务不等于空线",
20
+ };
21
+
22
+ const DISTRIBUTION = [
23
+ { key: "0", label: "0(空线)", min: 0, max: 0 },
24
+ { key: "1", label: "1", min: 1, max: 1 },
25
+ { key: "2-5", label: "2–5", min: 2, max: 5 },
26
+ { key: "6-10", label: "6–10", min: 6, max: 10 },
27
+ { key: "11-50", label: "11–50", min: 11, max: 50 },
28
+ { key: "51+", label: "51 及以上", min: 51, max: Infinity },
29
+ ];
30
+
31
+ function intArg(value, fallback, min, max, name) {
32
+ if (value === undefined || value === null) return fallback;
33
+ const n = Number(value);
34
+ if (!Number.isInteger(n) || n < min || n > max) throw new Error(name + " 必须是 " + min + ".." + max + " 的整数");
35
+ return n;
36
+ }
37
+
38
+ const DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
39
+ function dateArg(value, name) {
40
+ if (value === undefined || value === null || value === "") return null;
41
+ const text = String(value);
42
+ if (!DATE_RE.test(text)) throw new Error(name + " 必须是 YYYY-MM-DD");
43
+ const parsed = new Date(text + "T00:00:00");
44
+ if (Number.isNaN(parsed.getTime())) throw new Error(name + " 不是有效日期");
45
+ return text;
46
+ }
47
+
48
+ function rangeArgs(args) {
49
+ const from = dateArg(args.from, "from");
50
+ const to = dateArg(args.to, "to");
51
+ if ((from && !to) || (!from && to)) throw new Error("from 与 to 必须同时提供");
52
+ if (!from) return null;
53
+ const swapped = from > to;
54
+ return { from: swapped ? to : from, to: swapped ? from : to, swapped };
55
+ }
56
+
57
+ function ratio(part, whole) {
58
+ return whole > 0 ? Math.round((part / whole) * 1000) / 10 : null;
59
+ }
60
+
61
+ function distributionOf(lines) {
62
+ const counts = new Map(DISTRIBUTION.map((bin) => [bin.key, 0]));
63
+ for (const line of lines) {
64
+ const bin = DISTRIBUTION.find((item) => line.taskCount >= item.min && line.taskCount <= item.max);
65
+ counts.set(bin.key, counts.get(bin.key) + 1);
66
+ }
67
+ return DISTRIBUTION.map((bin) => ({ key: bin.key, label: bin.label, count: counts.get(bin.key) }));
68
+ }
69
+
70
+ function trendOf(db, range) {
71
+ const inRange = "substr(?,1,10) BETWEEN ? AND ?";
72
+ const newTimelines = Number(db.prepare(
73
+ "SELECT COUNT(*) AS n FROM task_timeline WHERE deleted_at IS NULL AND date(created_at/1000.0,'unixepoch','localtime') BETWEEN ? AND ?",
74
+ ).get(range.from, range.to).n);
75
+ const newTasks = Number(db.prepare(
76
+ "SELECT COUNT(*) AS n FROM task t WHERE " + LIVE_TASK + " AND substr(COALESCE(publish_date,''),1,10) BETWEEN ? AND ?",
77
+ ).get(range.from, range.to).n);
78
+ const doneTasks = Number(db.prepare(
79
+ "SELECT COUNT(*) AS n FROM task t WHERE " + LIVE_TASK + " AND t.status='2' AND substr(COALESCE(done_date,''),1,10) BETWEEN ? AND ?",
80
+ ).get(range.from, range.to).n);
81
+ void inRange;
82
+ return { from: range.from, to: range.to, swapped: range.swapped === true, newTimelines, newTasks, doneTasks };
83
+ }
84
+
85
+ export function timelineStats(db, args = {}) {
86
+ const topLimit = intArg(args.topLimit, 100, 1, 100, "topLimit");
87
+ const range = rangeArgs(args);
88
+ const today = todayStr();
89
+ const totalsRow = db.prepare(
90
+ "SELECT (SELECT COUNT(*) FROM task_timeline WHERE deleted_at IS NULL) AS timelines, " +
91
+ "(SELECT COUNT(*) FROM task t WHERE " + LIVE_TASK + ") AS tasks, " +
92
+ "(SELECT COUNT(*) FROM " + MEMBERS + " WHERE l.deleted_at IS NULL AND " + LIVE_ENT + " AND " + LIVE_TASK + ") AS assignedTasks, " +
93
+ "(SELECT COUNT(DISTINCT l.timeline_id) FROM " + MEMBERS + " WHERE l.deleted_at IS NULL AND " + LIVE_ENT + " AND " + LIVE_TASK + ") AS linesWithTasks",
94
+ ).get();
95
+ const lines = db.prepare(
96
+ "WITH eligible AS (SELECT l.timeline_id AS tid,t.status AS status,t.target_date AS target_date,t.publish_date AS publish_date,t.done_date AS done_date,t.shutdown_date AS shutdown_date,t.created_at AS created_at,t.updated_at AS updated_at FROM " + MEMBERS + " WHERE l.deleted_at IS NULL AND " + LIVE_ENT + " AND " + LIVE_TASK + "), " +
97
+ "counts AS (SELECT tid,COUNT(*) AS taskCount,SUM(CASE WHEN status='0' THEN 1 ELSE 0 END) AS openCount,SUM(CASE WHEN status='2' THEN 1 ELSE 0 END) AS doneCount,SUM(CASE WHEN status='1' THEN 1 ELSE 0 END) AS shutdownCount,SUM(CASE WHEN status='0' AND target_date IS NOT NULL AND target_date<>'' AND substr(target_date,1,10)<? THEN 1 ELSE 0 END) AS overdueCount,MAX(MAX(COALESCE(substr(publish_date,1,10),''),COALESCE(substr(done_date,1,10),''),COALESCE(substr(shutdown_date,1,10),''),COALESCE(date(created_at/1000.0,'unixepoch','localtime'),''),COALESCE(date(updated_at/1000.0,'unixepoch','localtime'),''))) AS lastActivityDate FROM eligible GROUP BY tid) " +
98
+ "SELECT e.id AS id,e.title AS title,COALESCE(c.taskCount,0) AS taskCount,COALESCE(c.openCount,0) AS openCount,COALESCE(c.doneCount,0) AS doneCount,COALESCE(c.shutdownCount,0) AS shutdownCount,COALESCE(c.overdueCount,0) AS overdueCount,c.lastActivityDate AS lastActivityDate " +
99
+ "FROM task_timeline e LEFT JOIN counts c ON c.tid=e.id WHERE " + LIVE_ENT + " ORDER BY taskCount DESC,e.id ASC",
100
+ ).all(today);
101
+ const rows = lines.map((line) => ({
102
+ id: String(line.id),
103
+ title: String(line.title || ""),
104
+ taskCount: Number(line.taskCount),
105
+ openCount: Number(line.openCount),
106
+ doneCount: Number(line.doneCount),
107
+ shutdownCount: Number(line.shutdownCount),
108
+ overdueCount: Number(line.overdueCount),
109
+ doneRate: line.taskCount > 0 ? Math.round((Number(line.doneCount) / Number(line.taskCount)) * 1000) / 10 : null,
110
+ lastActivityDate: line.lastActivityDate || null,
111
+ }));
112
+ const withTasks = rows.filter((line) => line.taskCount > 0);
113
+ const top = withTasks.slice(0, topLimit);
114
+ const totals = {
115
+ timelines: Number(totalsRow.timelines),
116
+ timelinesWithTasks: Number(totalsRow.linesWithTasks),
117
+ emptyTimelines: Number(totalsRow.timelines) - Number(totalsRow.linesWithTasks),
118
+ emptyRatio: ratio(Number(totalsRow.timelines) - Number(totalsRow.linesWithTasks), Number(totalsRow.timelines)),
119
+ tasks: Number(totalsRow.tasks),
120
+ assignedTasks: Number(totalsRow.assignedTasks),
121
+ unassignedTasks: Number(totalsRow.tasks) - Number(totalsRow.assignedTasks),
122
+ coverage: ratio(Number(totalsRow.assignedTasks), Number(totalsRow.tasks)),
123
+ };
124
+ return {
125
+ generatedAt: new Date().toISOString(),
126
+ scope: TIMELINE_STATS_SCOPE,
127
+ totals,
128
+ invariants: {
129
+ assignedPlusUnassigned: totals.assignedTasks + totals.unassignedTasks === totals.tasks,
130
+ linesPlusEmpty: totals.timelinesWithTasks + totals.emptyTimelines === totals.timelines,
131
+ },
132
+ top: { limit: topLimit, returned: top.length, truncated: withTasks.length > top.length, records: top },
133
+ distribution: distributionOf(rows),
134
+ overdue: {
135
+ lines: rows.filter((line) => line.overdueCount > 0).slice(0, topLimit),
136
+ lineCount: rows.filter((line) => line.overdueCount > 0).length,
137
+ taskCount: rows.reduce((sum, line) => sum + line.overdueCount, 0),
138
+ },
139
+ ...(range ? { trend: trendOf(db, range) } : {}),
140
+ };
141
+ }
142
+
143
+ export function renderTimelineStats(result) {
144
+ const t = result.totals;
145
+ const pieces = [
146
+ "时间线 " + t.timelines + " 条(有任务 " + t.timelinesWithTasks + "、空线 " + t.emptyTimelines + (t.emptyRatio === null ? "" : "," + t.emptyRatio + "%") + ")",
147
+ "有效任务 " + t.tasks + ":" + t.assignedTasks + " 已归属 / " + t.unassignedTasks + " 未归属" + (t.coverage === null ? "" : "(覆盖率 " + t.coverage + "%)"),
148
+ ];
149
+ const lines = ["时间线统计:" + pieces.join(";")];
150
+ if (result.top.records.length) {
151
+ lines.push("Top" + result.top.returned + (result.top.truncated ? "/" + t.timelinesWithTasks + "(已截断)" : "") + ":"
152
+ + result.top.records.map((line) => line.title + "=" + line.taskCount + "(已开启 " + line.openCount + "/完成 " + line.doneCount + "/关闭 " + line.shutdownCount + ")").join(","));
153
+ }
154
+ if (result.overdue.taskCount) lines.push("逾期任务 " + result.overdue.taskCount + " 个,分布在 " + result.overdue.lineCount + " 条时间线");
155
+ if (result.trend) lines.push("趋势 " + result.trend.from + "~" + result.trend.to + ":新增时间线 " + result.trend.newTimelines + "、新增任务 " + result.trend.newTasks + "、完成 " + result.trend.doneTasks);
156
+ return lines.join("\n");
157
+ }
158
+
159
+ export function registerTimelineStatsAction(api) {
160
+ api.action("tasks.timelineStats", {
161
+ description: "只读时间线统计:当前存量 + 可选范围内趋势。" + TIMELINE_STATS_SCOPE.exclusion + "。" + TIMELINE_STATS_SCOPE.membership + "。返回 totals(时间线总数/有任务线/空线/空线占比/有效任务/已归属/未归属/覆盖率)、top(全量聚合后按任务数降序取前 topLimit,同数按 id 升序,含状态构成与完成率)、distribution(0/1/2–5/6–10/11–50/51+)、overdue(逾期行与合计)与 invariants(已归属+未归属=有效任务;有任务线+空线=时间线总数)。传 from/to(YYYY-MM-DD,同时提供、反序自动交换)时另返回 trend(范围内新增时间线、新增任务、完成任务)。" + TIMELINE_STATS_SCOPE.activity + "。",
162
+ input: {
163
+ type: "object",
164
+ properties: {
165
+ topLimit: { type: "integer", minimum: 1, maximum: 100, description: "排行条数,默认 100;只影响 top.records,不影响 totals 与 distribution" },
166
+ from: { type: "string", description: "趋势起始日 YYYY-MM-DD,与 to 同时提供" },
167
+ to: { type: "string", description: "趋势结束日 YYYY-MM-DD,与 from 同时提供" },
168
+ },
169
+ },
170
+ examples: [{}, { from: "2026-10-01", to: "2026-10-31", topLimit: 20 }],
171
+ execute: (args) => timelineStats(api.db, args || {}),
172
+ render: renderTimelineStats,
173
+ });
174
+ }
@@ -0,0 +1,89 @@
1
+ /**
2
+ * 标签来源(`tag_mapping.item_type`)的业务侧适配。
3
+ *
4
+ * 契约见 `docs/specs/25-标签域解耦审计与改造.md`「6. 来源注册与映射写入门禁」:
5
+ * - 标签域(`wb-addon-tags` ≥ 1.7.1)用 `tag_source` 登记「哪个插件在用哪个 item_type」,
6
+ * 并在 `tag_mapping` 上装触发器:来源未注册(0 条)或重复(≥2 条)时拒绝一切写入;
7
+ * - 业务域负责启动时幂等登记自己的来源,写入前先判、写入异常时翻成统一可读文案。
8
+ *
9
+ * 标签域未安装或版本过低(没有 `tag_source` 表)时整块跳过,保持既有降级行为。
10
+ */
11
+ import { now, newId, tableExists } from "../db/db.js";
12
+
13
+ export const TAG_SOURCE = "task";
14
+ export const TAG_SOURCE_OWNER = "wb-addon-tasks";
15
+ export const TAG_SOURCE_TITLE = "任务";
16
+
17
+ function coded(code, message) {
18
+ return Object.assign(new Error(message), { code: code });
19
+ }
20
+
21
+ /** 该来源的活跃注册行;没有 `tag_source` 表时返回空数组。 */
22
+ export function tagSourceRows(db, source) {
23
+ if (!tableExists(db, "tag_source")) return [];
24
+ return db
25
+ .prepare("SELECT * FROM tag_source WHERE source=? AND deleted_at IS NULL ORDER BY created_at ASC, id ASC")
26
+ .all(String(source));
27
+ }
28
+
29
+ /** 恰好 1 条活跃注册才算 ready;`missing` 表示标签域还没建 `tag_source`(老版本),此时不做门禁。 */
30
+ export function tagSourceReady(db, source) {
31
+ if (!tableExists(db, "tag_source")) return { ok: false, missing: true, count: 0, owners: [] };
32
+ const rows = tagSourceRows(db, source);
33
+ return {
34
+ ok: rows.length === 1,
35
+ missing: false,
36
+ count: rows.length,
37
+ owners: rows.map(function (r) { return String(r.owner); }),
38
+ };
39
+ }
40
+
41
+ /** 幂等登记本域来源;`tag_source` 不存在时跳过(老标签插件不认识来源注册)。 */
42
+ export function ensureTagSource(db, source, owner, title) {
43
+ if (!tableExists(db, "tag_source")) return { ok: false, missing: true, created: false };
44
+ const src = String(source === undefined || source === null ? "" : source).trim();
45
+ const own = String(owner === undefined || owner === null ? "" : owner).trim();
46
+ if (!src || !own) return { ok: false, created: false };
47
+ const hit = db.prepare("SELECT id FROM tag_source WHERE source=? AND owner=? AND deleted_at IS NULL").get(src, own);
48
+ if (hit) return { ok: true, created: false, id: String(hit.id) };
49
+ const ts = now();
50
+ const id = newId();
51
+ db.prepare(
52
+ "INSERT INTO tag_source(id,source,owner,title,created_at,updated_at,deleted_at,rev) VALUES(?,?,?,?,?,?,NULL,1)",
53
+ ).run(id, src, own, String(title || ""), ts, ts);
54
+ return { ok: true, created: true, id: id };
55
+ }
56
+
57
+ /** 按当前注册状态给出统一错误:0 条 = 未注册,≥2 条 = 标识重复。 */
58
+ export function tagSourceError(db, source) {
59
+ const state = tagSourceReady(db, source);
60
+ if (state.count === 0) {
61
+ return coded(
62
+ "TAG_SOURCE_UNREGISTERED",
63
+ "标签来源未注册,无法操作(来源:" + source + ");先调用 tags.registerSource 注册该来源",
64
+ );
65
+ }
66
+ return coded(
67
+ "TAG_SOURCE_DUPLICATED",
68
+ "标签来源标识重复,无法操作(来源:" + source + ";归属:" + state.owners.join("、") +
69
+ ");请先清理 tag_source 中的重复注册",
70
+ );
71
+ }
72
+
73
+ /**
74
+ * 写入 `tag_mapping` 的统一入口:先判门禁,执行中触发器的原始错误翻成统一文案。
75
+ * `source` 省略时用本域默认来源。注册由启动时的 `ensureXxxTagSource` 负责,这里不补登记——
76
+ * 否则「被人工注销」会被静默覆盖,门禁也就失效了。
77
+ */
78
+ export function withTagSource(db, source, fn) {
79
+ const src = String(source || TAG_SOURCE);
80
+ // 先判后写:注册由启动时 ensureXxxTagSource 负责,这里只判定,不替调用方补登记。
81
+ if (!tagSourceReady(db, src).ok && !tagSourceReady(db, src).missing) throw tagSourceError(db, src);
82
+ try {
83
+ return fn();
84
+ } catch (e) {
85
+ const msg = String((e && e.message) || "");
86
+ if (msg.indexOf("标签来源") >= 0) throw tagSourceError(db, src);
87
+ throw e;
88
+ }
89
+ }
@@ -0,0 +1,99 @@
1
+ // 标签下拉的按需分页查询:从 tagging.js 拆出,避免单文件持续膨胀。
2
+ import { STATUS_FIELDS, countsOf, tagsAvailable } from "./tagging.js";
3
+
4
+ /** 标签下拉的分页上限;客户端每次只多拉一页。 */
5
+ export const TAG_OPTIONS_MAX = 100;
6
+
7
+ export function escapeLike(text) {
8
+ return String(text).replace(/[\\%_]/g, function (m) { return "\\" + m; });
9
+ }
10
+
11
+ export function untaggedCounts(db) {
12
+ const row = db.prepare(
13
+ "SELECT " + STATUS_FIELDS.map(function (p) {
14
+ return p[1] === null
15
+ ? "COUNT(*) AS total"
16
+ : "SUM(CASE WHEN status='" + p[1] + "' THEN 1 ELSE 0 END) AS " + p[0];
17
+ }).join(", ") + " FROM task " +
18
+ "WHERE deleted_at IS NULL AND NOT EXISTS (" +
19
+ "SELECT 1 FROM tag_mapping m WHERE m.item_type='task' AND m.item_id=task.id AND m.deleted_at IS NULL)",
20
+ ).get();
21
+ return countsOf(row);
22
+ }
23
+
24
+ const TAG_COUNT_SELECT =
25
+ "SELECT g.id AS id, g.name AS name, " +
26
+ STATUS_FIELDS.map(function (p) {
27
+ return p[1] === null
28
+ ? "COUNT(t.id) AS total"
29
+ : "SUM(CASE WHEN t.status='" + p[1] + "' THEN 1 ELSE 0 END) AS " + p[0];
30
+ }).join(", ") + " " +
31
+ "FROM tag g " +
32
+ "LEFT JOIN tag_mapping m ON m.tag_id=g.id AND m.item_type='task' AND m.deleted_at IS NULL " +
33
+ "LEFT JOIN task t ON t.id=m.item_id AND t.deleted_at IS NULL ";
34
+
35
+ /**
36
+ * 标签下拉的按需分页:text 模糊匹配名称(% _ \ 转义),按 total DESC, name ASC, id ASC 稳定排序。
37
+ * 与 tagNavStats 的区别:不一次性返回全量,供「搜索 + 滚动加载」的下拉使用。
38
+ */
39
+ export function tagOptions(db, api, args) {
40
+ const opt = args || {};
41
+ const pageSize = Math.max(1, Math.min(TAG_OPTIONS_MAX, Math.floor(Number(opt.pageSize) || 20)));
42
+ const pageNumber = Math.max(1, Math.floor(Number(opt.pageNumber) || 1));
43
+ const text = String(opt.text == null ? "" : opt.text).trim();
44
+ if (!tagsAvailable(db, api)) {
45
+ return { available: false, text: text, tags: [], pageNumber: pageNumber, pageSize: pageSize, total: 0, hasMore: false, untagged: { total: 0, open: 0, shutdown: 0, done: 0, restarted: 0 } };
46
+ }
47
+ const like = text ? "%" + escapeLike(text) + "%" : null;
48
+ const where = "g.deleted_at IS NULL" + (like ? " AND g.name LIKE ? ESCAPE '\\'" : "");
49
+ const countArgs = like ? [like] : [];
50
+ const total = Number(db.prepare("SELECT COUNT(*) AS n FROM tag g WHERE " + where).get(...countArgs).n || 0);
51
+ const offset = (pageNumber - 1) * pageSize;
52
+ const rows = db
53
+ .prepare(TAG_COUNT_SELECT + " WHERE " + where + " GROUP BY g.id, g.name ORDER BY total DESC, g.name ASC, g.id ASC LIMIT ? OFFSET ?")
54
+ .all(...countArgs, pageSize, offset);
55
+ const tags = rows.map(function (row) {
56
+ return Object.assign({ id: String(row.id), name: String(row.name || "") }, countsOf(row));
57
+ });
58
+ return {
59
+ available: true,
60
+ text: text,
61
+ tags: tags,
62
+ pageNumber: pageNumber,
63
+ pageSize: pageSize,
64
+ total: total,
65
+ hasMore: offset + tags.length < total,
66
+ untagged: untaggedCounts(db),
67
+ };
68
+ }
69
+
70
+
71
+ /** 把 tasks.tagOptions 的 action 注册从 tasks.js 里拆出来,控制单文件规模。 */
72
+ export function registerTagOptionsAction(action, db, api, migrateLegacyTypes) {
73
+ action("tasks.tagOptions", {
74
+ description:
75
+ "标签下拉的按需分页:按名称模糊匹配(中文子串、ASCII 大小写不敏感,% _ \\ 按字面匹配)," +
76
+ "排序 total DESC, name ASC, id ASC;返回 total / hasMore 供滚动加载。标签域未安装时 available=false",
77
+ input: {
78
+ type: "object",
79
+ properties: {
80
+ text: { type: "string", description: "名称关键词;trim 后为空表示不筛选" },
81
+ pageNumber: { type: "number", description: "默认 1" },
82
+ pageSize: { type: "number", description: "默认 20,上限 100" },
83
+ },
84
+ },
85
+ examples: [{ text: "工作", pageSize: 20 }, { pageNumber: 2, pageSize: 20 }],
86
+ execute: function (args) {
87
+ try {
88
+ migrateLegacyTypes(db, api, "migrate");
89
+ } catch (e) {
90
+ /* ignore */
91
+ }
92
+ return tagOptions(db, api, args || {});
93
+ },
94
+ render: function (r) {
95
+ if (!r.available) return "标签域未安装";
96
+ return "标签 " + r.tags.length + " 个(共 " + r.total + ",第 " + r.pageNumber + " 页)" + (r.hasMore ? ",还有更多" : "");
97
+ },
98
+ });
99
+ }