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.
- package/LICENSE +21 -0
- package/README.md +26 -2
- package/cordis.patch.yml +7 -0
- package/lib/client.js +11963 -0
- package/lib/db/db-core.js +432 -0
- package/lib/db/db-legacy.js +473 -0
- package/lib/db/db.js +97 -0
- package/lib/db/ownership-path.js +33 -0
- package/lib/db/timeline-schema.js +7 -0
- package/lib/db/workspace-schema.js +15 -0
- package/lib/index.js +232 -0
- package/lib/infra/backup.js +289 -0
- package/lib/infra/config.js +462 -0
- package/lib/infra/data.js +368 -0
- package/lib/infra/sync.js +189 -0
- package/lib/publisher/brief.js +76 -0
- package/lib/publisher/catalog.js +99 -0
- package/lib/publisher/command.js +81 -0
- package/lib/stats/activity-calendar.js +74 -0
- package/lib/stats/difficulty-bins.js +49 -0
- package/lib/stats/events.js +40 -0
- package/lib/stats/overview.js +99 -0
- package/lib/stats/stats-today.js +26 -0
- package/lib/stats/stats.js +589 -0
- package/lib/stats/timeline-stats.js +174 -0
- package/lib/tagging/source.js +89 -0
- package/lib/tagging/tag-options.js +99 -0
- package/lib/tagging/tagging.js +371 -0
- package/lib/task/model/task-difficulty.js +15 -0
- package/lib/task/model/task-model.js +256 -0
- package/lib/task/model/task-ownership-path.js +22 -0
- package/lib/task/model/task-priority.js +33 -0
- package/lib/task/read/task-discovery.js +123 -0
- package/lib/task/read/task-publish-filter.js +31 -0
- package/lib/task/read/task-query.js +351 -0
- package/lib/task/read/task-search-schema.js +34 -0
- package/lib/task/read/task-view.js +146 -0
- package/lib/task/write/task-bulk.js +247 -0
- package/lib/task/write/task-claim.js +229 -0
- package/lib/task/write/task-create-schema.js +34 -0
- package/lib/task/write/task-create.js +178 -0
- package/lib/task/write/task-operations.js +207 -0
- package/lib/task/write/task-target.js +56 -0
- package/lib/task/write/task-transaction.js +18 -0
- package/lib/task/write/task-update.js +104 -0
- package/lib/tasks.js +456 -0
- package/lib/timeline/task-timelines.js +110 -0
- package/lib/timeline/timeline-actions.js +69 -0
- package/lib/timeline/timeline-migration.js +70 -0
- package/lib/timeline/timeline-store.js +57 -0
- package/lib/timeline/timeline-sync.js +46 -0
- package/lib/tree/task-node-write.js +26 -0
- package/lib/tree/tree.js +517 -0
- package/lib/workspace/workspace-actions.js +217 -0
- package/lib/workspace/workspace-store.js +196 -0
- package/package.json +144 -4
- package/shared/tree/limits.cjs +3 -0
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
import { timelineIdArg, requireTimeline, activeTimeline, timelineError, setMembership } from "../../timeline/timeline-store.js";
|
|
2
|
+
import { difficultyMissingNotices, cleanDifficultyReceipt } from "../model/task-difficulty.js";
|
|
3
|
+
// 与 task-bulk 的循环引用只在调用期取值,顶层不求值。
|
|
4
|
+
import {
|
|
5
|
+
now,
|
|
6
|
+
newId,
|
|
7
|
+
idOf,
|
|
8
|
+
todayStr,
|
|
9
|
+
} from "../../db/db.js";
|
|
10
|
+
// task-query 循环依赖仅在调用期读取 tasks 的函数/常量。
|
|
11
|
+
import { priorityForCreate } from "../model/task-priority.js";
|
|
12
|
+
import {
|
|
13
|
+
tagsAvailable,
|
|
14
|
+
normalizeTagIds,
|
|
15
|
+
normalizeTagNames,
|
|
16
|
+
requireTagRows,
|
|
17
|
+
ensureTagsByNames,
|
|
18
|
+
replaceTaskTags,
|
|
19
|
+
attachTags,
|
|
20
|
+
} from "../../tagging/tagging.js";
|
|
21
|
+
import { requireKnownTagNames, tagMissingNotices, withNotices, STATUSES, STATUS_NAMES, asCode, sourceCode, clampDifficulty, dateArg, getTask, insertTaskRow, saveTaskRow, outOne, writeChange, checkRequiredDates } from "../model/task-model.js";
|
|
22
|
+
import { taskTransaction } from './task-transaction.js';
|
|
23
|
+
import { setTaskWorkspaces, attachWorkspaces } from '../../workspace/workspace-store.js';
|
|
24
|
+
import { validateTargetArgs, resolveTarget, requireOwnedTable } from './task-target.js';
|
|
25
|
+
import { ownershipError, ownershipFields } from '../model/task-ownership-path.js';
|
|
26
|
+
// 标题不做唯一性校验:允许与其它任务同名,调用方用 id 区分(与标签名唯一是两条规则)。
|
|
27
|
+
export function createTask(db, args, origin, api, opts) {
|
|
28
|
+
if (!opts?.skipTx) return taskTransaction(db, api, buffered => createTask(db, args, origin, buffered, {skipTx:true}));
|
|
29
|
+
const validated = validateTargetArgs(db, args, api);
|
|
30
|
+
const title = String(args.title === undefined || args.title === null ? "" : args.title).trim();
|
|
31
|
+
if (!title) throw new Error("title 不能为空");
|
|
32
|
+
const dedupeKey = String(args.dedupeKey === undefined || args.dedupeKey === null ? "" : args.dedupeKey).trim() || null;
|
|
33
|
+
if (dedupeKey) {
|
|
34
|
+
const matches = db.prepare("SELECT * FROM task WHERE dedupe_key=? AND deleted_at IS NULL ORDER BY created_at ASC").all(dedupeKey);
|
|
35
|
+
if (matches.length > 1) throw ownershipError('DEDUPE_AMBIGUOUS', '幂等键对应多个存活任务:' + dedupeKey);
|
|
36
|
+
const existing = matches[0];
|
|
37
|
+
if (existing) {
|
|
38
|
+
requireOwnedTable(db, existing.table_id);
|
|
39
|
+
const task = outOne(db, existing);
|
|
40
|
+
attachTags(db, api, task);
|
|
41
|
+
const same = validated.hasId ? String(args.tableId) === task.tableId : JSON.stringify(validated.parts) === JSON.stringify(task.pathSegments.slice(1).map(n=>n.name));
|
|
42
|
+
const notices = [...tagMissingNotices(args, tagsAvailable(db, api)), ...difficultyMissingNotices(args, task.difficulty)];
|
|
43
|
+
cleanDifficultyReceipt(task);
|
|
44
|
+
if (!same) notices.push({code:'DEDUPE_TARGET_MISMATCH',message:'返回已有任务实际归属,未移动任务或创建请求路径节点;纠正请调用 tasks.update(' + JSON.stringify({id:task.id,tableId:'目标表id'}) + ')'});
|
|
45
|
+
return withNotices({ id: String(existing.id), task, ...ownershipFields(task), deduped: true, existing: true, createdNodes: [] }, notices);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
const source = sourceCode(args.source);
|
|
49
|
+
let status = asCode(args.status, STATUS_NAMES, STATUSES, "status");
|
|
50
|
+
if (status === null) status = "0";
|
|
51
|
+
if (status === "3") throw new Error("创建任务时不能直接使用 RESTARTED 状态");
|
|
52
|
+
if (source === "2") status = "0";
|
|
53
|
+
|
|
54
|
+
const publishDate = dateArg(args.publishDate, "publishDate") || todayStr();
|
|
55
|
+
const targetDate = dateArg(args.targetDate, "targetDate") || publishDate;
|
|
56
|
+
let doneDate = dateArg(args.doneDate, "doneDate");
|
|
57
|
+
let shutdownDate = dateArg(args.shutdownDate, "shutdownDate");
|
|
58
|
+
let difficulty = clampDifficulty(args.difficulty, null);
|
|
59
|
+
let priority = priorityForCreate(status, args.priority, source);
|
|
60
|
+
|
|
61
|
+
if (status === "0") {
|
|
62
|
+
if (difficulty !== null) {
|
|
63
|
+
/* ACTIVE 也允许保留难度,兼容直接调用 */
|
|
64
|
+
}
|
|
65
|
+
} else if (status === "2") {
|
|
66
|
+
if (!doneDate) doneDate = todayStr();
|
|
67
|
+
if (difficulty === null) difficulty = 0;
|
|
68
|
+
if (doneDate < publishDate) throw new Error("doneDate 不能早于 publishDate");
|
|
69
|
+
} else if (status === "1") {
|
|
70
|
+
if (!shutdownDate) shutdownDate = todayStr();
|
|
71
|
+
if (shutdownDate < publishDate) throw new Error("shutdownDate 不能早于 publishDate");
|
|
72
|
+
}
|
|
73
|
+
// 关闭/完成的任务同样清零(见 priorityForStatus);开启任务缺省 P1,不再有「P0 开启」。
|
|
74
|
+
if (targetDate < publishDate) throw new Error("targetDate 不能早于 publishDate");
|
|
75
|
+
|
|
76
|
+
let timelineKey = timelineIdArg(args, false);
|
|
77
|
+
if (source === "0" && timelineKey) throw timelineError("TIMELINE_SOURCE_CONFLICT", "普通任务不接受时间线,请使用 source=1 或 taskTimelines.attach");
|
|
78
|
+
let restartKey = idOf(args.restartKey || args.originTaskId);
|
|
79
|
+
if (source === "1") {
|
|
80
|
+
if (!timelineKey) throw timelineError("TIMELINE_ID_REQUIRED", "时间线任务必须提供 timelineId");
|
|
81
|
+
requireTimeline(db, timelineKey);
|
|
82
|
+
}
|
|
83
|
+
if (source === "2") {
|
|
84
|
+
if (!restartKey) throw new Error("重启任务必须提供 restartKey(原任务 id)");
|
|
85
|
+
const originTask = getTask(db, restartKey);
|
|
86
|
+
if (!originTask) throw new Error("原任务不存在:" + restartKey);
|
|
87
|
+
const inherited = activeTimeline(db,restartKey);
|
|
88
|
+
if (!inherited) throw timelineError('TIMELINE_REQUIRED_FOR_RESTART','请先手动建立并关联时间线,再重启',{taskId:restartKey,reason:'NO_ACTIVE_MEMBERSHIP',nextActions:['taskTimelines.create','taskTimelines.attach','tasks.create']});
|
|
89
|
+
if (timelineKey && timelineKey !== inherited.id) throw timelineError('TIMELINE_INHERITANCE_CONFLICT','重启必须继承原任务时间线');
|
|
90
|
+
timelineKey = inherited.id;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
const { table, createdNodes } = resolveTarget(db, args, validated, origin, api);
|
|
94
|
+
const tagIds = args.tagIds === undefined || args.tagIds === null ? null : normalizeTagIds(args.tagIds);
|
|
95
|
+
// 允许直接传标签名(如 ["工作","紧急"]),缺失的标签按名补建。
|
|
96
|
+
const tagNames = normalizeTagNames(args.tags);
|
|
97
|
+
const tagOn = tagsAvailable(db, api);
|
|
98
|
+
if (tagOn) {
|
|
99
|
+
requireKnownTagNames(db, tagNames);
|
|
100
|
+
if (tagIds) requireTagRows(db, tagIds);
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
const id = newId();
|
|
104
|
+
if (source === "0") {
|
|
105
|
+
timelineKey = null;
|
|
106
|
+
restartKey = id;
|
|
107
|
+
} else if (source === "1") {
|
|
108
|
+
restartKey = id;
|
|
109
|
+
} else {
|
|
110
|
+
restartKey = restartKey;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
const ts = now();
|
|
114
|
+
const row = {
|
|
115
|
+
id,
|
|
116
|
+
title,
|
|
117
|
+
description: String(args.description === undefined || args.description === null ? "" : args.description),
|
|
118
|
+
status,
|
|
119
|
+
priority,
|
|
120
|
+
difficulty,
|
|
121
|
+
review: String(args.review === undefined || args.review === null ? "" : args.review),
|
|
122
|
+
table_id: String(table.id),
|
|
123
|
+
timeline_key: timelineKey || null,
|
|
124
|
+
restart_key: restartKey || null,
|
|
125
|
+
publish_date: publishDate,
|
|
126
|
+
target_date: targetDate,
|
|
127
|
+
done_date: doneDate,
|
|
128
|
+
shutdown_date: shutdownDate,
|
|
129
|
+
dedupe_key: dedupeKey,
|
|
130
|
+
created_at: ts,
|
|
131
|
+
updated_at: ts,
|
|
132
|
+
deleted_at: null,
|
|
133
|
+
rev: 1,
|
|
134
|
+
};
|
|
135
|
+
checkRequiredDates(row);
|
|
136
|
+
|
|
137
|
+
const body = function () {
|
|
138
|
+
if (source === "2") {
|
|
139
|
+
const active = db.prepare(
|
|
140
|
+
"SELECT * FROM task WHERE restart_key=? AND status IN ('0','4') AND deleted_at IS NULL",
|
|
141
|
+
).all(restartKey);
|
|
142
|
+
const shutdownTs = now();
|
|
143
|
+
for (const old of active) {
|
|
144
|
+
const next = Object.assign({}, old, { status: "1", priority: 0, shutdown_date: todayStr(), owner: null, claimed_at: null, claim_token: null, updated_at: shutdownTs, rev: Number(old.rev) + 1 });
|
|
145
|
+
saveTaskRow(db, next);
|
|
146
|
+
writeChange(db, next, "update", origin, api, shutdownTs);
|
|
147
|
+
}
|
|
148
|
+
const shutdown = db.prepare(
|
|
149
|
+
"SELECT * FROM task WHERE restart_key=? AND status='1' AND deleted_at IS NULL",
|
|
150
|
+
).all(restartKey);
|
|
151
|
+
for (const old of shutdown) {
|
|
152
|
+
const next = Object.assign({}, old, { status: "3", priority: 0, updated_at: shutdownTs, rev: Number(old.rev) + 1 });
|
|
153
|
+
saveTaskRow(db, next);
|
|
154
|
+
writeChange(db, next, "update", origin, api, shutdownTs);
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
insertTaskRow(db, row);
|
|
158
|
+
if (timelineKey) setMembership(db,id,timelineKey,origin,api,{ts,project:false,touched:opts?.touchedTimelines});
|
|
159
|
+
if ((tagIds || tagNames.length) && tagOn) {
|
|
160
|
+
const all = (tagIds || []).slice();
|
|
161
|
+
for (const tagId of ensureTagsByNames(db, tagNames, ts, origin)) {
|
|
162
|
+
if (all.indexOf(tagId) < 0) all.push(tagId);
|
|
163
|
+
}
|
|
164
|
+
replaceTaskTags(db, id, all, ts, origin);
|
|
165
|
+
}
|
|
166
|
+
if (args.workspaceIds !== undefined && args.workspaceIds !== null) {
|
|
167
|
+
setTaskWorkspaces(db, id, args.workspaceIds, ts, origin, api);
|
|
168
|
+
}
|
|
169
|
+
writeChange(db, row, "create", origin, api, ts);
|
|
170
|
+
};
|
|
171
|
+
// skipTx 供 bulkCreate 在外层事务里复用;单条创建仍自己开事务。
|
|
172
|
+
body();
|
|
173
|
+
|
|
174
|
+
const task = outOne(db, row);
|
|
175
|
+
attachTags(db, api, task);
|
|
176
|
+
attachWorkspaces(db, [task]);
|
|
177
|
+
return withNotices({ id: id, task: cleanDifficultyReceipt(task), ...ownershipFields(task), createdNodes, deduped: false }, [...tagMissingNotices(args, tagOn), ...difficultyMissingNotices(args, difficulty)]);
|
|
178
|
+
}
|
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
import { setMembership } from "../../timeline/timeline-store.js";
|
|
2
|
+
import { taskTransaction } from "./task-transaction.js";
|
|
3
|
+
// 与 task-bulk 的循环引用只在调用期取值,顶层不求值。
|
|
4
|
+
import {
|
|
5
|
+
now,
|
|
6
|
+
idOf,
|
|
7
|
+
todayStr,
|
|
8
|
+
tx,
|
|
9
|
+
logChange,
|
|
10
|
+
taskOut,
|
|
11
|
+
nodeMap,
|
|
12
|
+
} from "../../db/db.js";
|
|
13
|
+
// task-query 循环依赖仅在调用期读取 tasks 的函数/常量。
|
|
14
|
+
import { listTasks } from "../read/task-query.js";
|
|
15
|
+
import { todayActivity } from "../../stats/stats-today.js";
|
|
16
|
+
import { csvCell } from "../read/task-view.js";
|
|
17
|
+
import { bulkUpdate } from "./task-bulk.js";
|
|
18
|
+
import {
|
|
19
|
+
tagsAvailable,
|
|
20
|
+
attachTags,
|
|
21
|
+
} from "../../tagging/tagging.js";
|
|
22
|
+
import { TAG_DOMAIN_NOTICE, withNotices, dateArg, getTask, saveTaskRow, emitChange, writeChange } from "../model/task-model.js";
|
|
23
|
+
import { clearTaskWorkspaces, attachWorkspaces } from "../../workspace/workspace-store.js";
|
|
24
|
+
import { updateTask } from "./task-update.js";
|
|
25
|
+
export function selectedTasks(db, args) {
|
|
26
|
+
const ids = Array.isArray(args.ids) ? args.ids.map(String) : [];
|
|
27
|
+
if (!ids.length) return [];
|
|
28
|
+
const marks = ids.map(function () { return "?"; }).join(",");
|
|
29
|
+
const rows = db.prepare("SELECT * FROM task WHERE deleted_at IS NULL AND id IN (" + marks + ")").all(...ids);
|
|
30
|
+
const map = nodeMap(db);
|
|
31
|
+
return rows.map(function (r) { return taskOut(r, map); });
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export { timelineTasks, timelineRefactor } from "../../timeline/task-timelines.js";
|
|
35
|
+
|
|
36
|
+
export function restartTasks(db, args) {
|
|
37
|
+
const key = idOf(args.restartKey);
|
|
38
|
+
if (!key) return [];
|
|
39
|
+
const rows = db.prepare("SELECT * FROM task WHERE restart_key=? AND deleted_at IS NULL ORDER BY publish_date ASC, id ASC").all(key);
|
|
40
|
+
const map = nodeMap(db);
|
|
41
|
+
return rows.map(function (r) { return taskOut(r, map); });
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
export function migrateTasks(db, args, origin, api) {
|
|
46
|
+
const result = bulkUpdate(db,{ids:args.ids,patch:{tableId:args.tableId},dryRun:args.dryRun},origin,api);
|
|
47
|
+
return {...result, ids:result.changes.map(c=>c.id), tableId:String(args.tableId), tasks:result.changes.map(c=>c.task)};
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function sweepShutdown(db, args, origin, api) {
|
|
51
|
+
const day = dateArg(args.date, "date") || todayStr();
|
|
52
|
+
const rows = db.prepare(
|
|
53
|
+
"SELECT * FROM task WHERE status='0' AND target_date<=? AND deleted_at IS NULL",
|
|
54
|
+
).all(day);
|
|
55
|
+
const dryRun = args.dryRun === true;
|
|
56
|
+
const ts = now();
|
|
57
|
+
const ids = [];
|
|
58
|
+
const items = rows.map(function (cur) {
|
|
59
|
+
return { id: String(cur.id), title: String(cur.title || ""), targetDate: cur.target_date || null };
|
|
60
|
+
});
|
|
61
|
+
if (dryRun) return { dryRun: true, updated: 0, wouldUpdate: rows.length, ids: rows.map(function (r) { return String(r.id); }), items: items, date: day };
|
|
62
|
+
tx(db, function () {
|
|
63
|
+
for (const cur of rows) {
|
|
64
|
+
const next = Object.assign({}, cur, { status: "1", priority: 0, shutdown_date: day, updated_at: ts, rev: Number(cur.rev) + 1 });
|
|
65
|
+
saveTaskRow(db, next);
|
|
66
|
+
writeChange(db, next, "update", origin, api, ts);
|
|
67
|
+
ids.push(String(cur.id));
|
|
68
|
+
}
|
|
69
|
+
});
|
|
70
|
+
return { updated: ids.length, ids: ids, items: items, date: day };
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export function stats(db, args, api) {
|
|
74
|
+
const a = args || {};
|
|
75
|
+
const day = todayStr();
|
|
76
|
+
const row = db.prepare(
|
|
77
|
+
"SELECT " +
|
|
78
|
+
"SUM(CASE WHEN status='0' AND deleted_at IS NULL THEN 1 ELSE 0 END) AS active, " +
|
|
79
|
+
"SUM(CASE WHEN status='1' AND deleted_at IS NULL THEN 1 ELSE 0 END) AS shutdown, " +
|
|
80
|
+
"SUM(CASE WHEN status='2' AND deleted_at IS NULL THEN 1 ELSE 0 END) AS done, " +
|
|
81
|
+
"SUM(CASE WHEN status='3' AND deleted_at IS NULL THEN 1 ELSE 0 END) AS restarted, " +
|
|
82
|
+
"SUM(CASE WHEN status='0' AND deleted_at IS NULL AND target_date<? THEN 1 ELSE 0 END) AS overdue, " +
|
|
83
|
+
"SUM(CASE WHEN status='0' AND deleted_at IS NULL AND target_date=? THEN 1 ELSE 0 END) AS today " +
|
|
84
|
+
"FROM task",
|
|
85
|
+
).get(day, day);
|
|
86
|
+
const base = {
|
|
87
|
+
open: row.active || 0,
|
|
88
|
+
active: row.active || 0,
|
|
89
|
+
shutdown: row.shutdown || 0,
|
|
90
|
+
done: row.done || 0,
|
|
91
|
+
restarted: row.restarted || 0,
|
|
92
|
+
overdue: row.overdue || 0,
|
|
93
|
+
today: row.today || 0,
|
|
94
|
+
todayActivity: todayActivity(db, day),
|
|
95
|
+
};
|
|
96
|
+
const groupBy = a.groupBy === undefined || a.groupBy === null || a.groupBy === "" ? null : String(a.groupBy);
|
|
97
|
+
if (!groupBy) return base;
|
|
98
|
+
const COLS = { tableId: "t.table_id", status: "t.status", priority: "t.priority" };
|
|
99
|
+
const col = COLS[groupBy];
|
|
100
|
+
const byTag = groupBy === "tag" || groupBy === "tags";
|
|
101
|
+
if (!col && !byTag) throw new Error("groupBy 只支持 tag / tableId / status / priority");
|
|
102
|
+
const where = ["t.deleted_at IS NULL"];
|
|
103
|
+
const params = [];
|
|
104
|
+
const from = dateArg(a.from, "from");
|
|
105
|
+
const to = dateArg(a.to, "to");
|
|
106
|
+
if (from) { where.push("t.target_date>=?"); params.push(from); }
|
|
107
|
+
if (to) { where.push("t.target_date<=?"); params.push(to); }
|
|
108
|
+
if (byTag) {
|
|
109
|
+
if (!tagsAvailable(db, api)) {
|
|
110
|
+
return withNotices(Object.assign({}, base, { groups: [], available: false }), [Object.assign({}, TAG_DOMAIN_NOTICE)]);
|
|
111
|
+
}
|
|
112
|
+
const tagStmt = db.prepare(
|
|
113
|
+
"SELECT g.id AS k, g.name AS label, COUNT(DISTINCT t.id) AS n FROM task t " +
|
|
114
|
+
"JOIN tag_mapping m ON m.item_type='task' AND m.item_id=t.id AND m.deleted_at IS NULL " +
|
|
115
|
+
"JOIN tag g ON g.id=m.tag_id AND g.deleted_at IS NULL WHERE " + where.join(" AND ") +
|
|
116
|
+
" GROUP BY g.id, g.name ORDER BY n DESC",
|
|
117
|
+
);
|
|
118
|
+
const tagRows = tagStmt.all.apply(tagStmt, params);
|
|
119
|
+
const untaggedStmt = db.prepare(
|
|
120
|
+
"SELECT COUNT(*) AS n FROM task t WHERE " + where.join(" AND ") +
|
|
121
|
+
" AND NOT EXISTS (SELECT 1 FROM tag_mapping m WHERE m.item_type='task' AND m.item_id=t.id AND m.deleted_at IS NULL)",
|
|
122
|
+
);
|
|
123
|
+
const untagged = Number(untaggedStmt.get.apply(untaggedStmt, params).n || 0);
|
|
124
|
+
const groups = tagRows.map(function (g) {
|
|
125
|
+
return { key: String(g.k), label: String(g.label || ""), count: Number(g.n || 0) };
|
|
126
|
+
});
|
|
127
|
+
if (untagged > 0) groups.push({ key: "untagged", label: "未打标签", count: untagged });
|
|
128
|
+
return Object.assign({}, base, { groupBy: "tag", from: from, to: to, groups: groups });
|
|
129
|
+
}
|
|
130
|
+
const stmt = db.prepare("SELECT " + col + " AS k, COUNT(*) AS n FROM task t WHERE " + where.join(" AND ") + " GROUP BY " + col + " ORDER BY n DESC");
|
|
131
|
+
const rows = stmt.all.apply(stmt, params);
|
|
132
|
+
const map = groupBy === "tableId" ? nodeMap(db) : null;
|
|
133
|
+
const groups = rows.map(function (g) {
|
|
134
|
+
let label = null;
|
|
135
|
+
if (map && g.k) {
|
|
136
|
+
const n = map[String(g.k)];
|
|
137
|
+
label = n ? String(n.title || "") : null;
|
|
138
|
+
}
|
|
139
|
+
if (groupBy === "status") label = ({ "0": "ACTIVE", "1": "SHUTDOWN", "2": "DONE", "3": "RESTARTED" })[String(g.k)] || String(g.k);
|
|
140
|
+
return { key: g.k === null || g.k === undefined ? null : String(g.k), label: label, count: g.n };
|
|
141
|
+
});
|
|
142
|
+
return Object.assign({}, base, { groupBy: groupBy, from: from, to: to, groups: groups });
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
export function removeTask(db, args, origin, api, skipTx = false) {
|
|
146
|
+
if (!skipTx) return taskTransaction(db,api,buffered=>removeTask(db,args,origin,buffered,true));
|
|
147
|
+
const cur = getTask(db, args.id || args.taskId);
|
|
148
|
+
if (!cur) throw new Error("任务不存在:" + (args.id || args.taskId));
|
|
149
|
+
const ts = now();
|
|
150
|
+
setMembership(db,cur.id,null,origin,api,{ts,project:false});
|
|
151
|
+
const next = Object.assign({}, cur, { timeline_key:null, deleted_at: ts, updated_at: ts, rev: Number(cur.rev) + 1 });
|
|
152
|
+
saveTaskRow(db, next);
|
|
153
|
+
// 删除任务连带软删它的工作区关联,避免 link 变成指向已删任务的孤儿行。
|
|
154
|
+
clearTaskWorkspaces(db, next.id, origin, api, ts);
|
|
155
|
+
logChange(db, "task", next.id, "delete", null, origin, ts);
|
|
156
|
+
emitChange(api, next.id, "delete");
|
|
157
|
+
return { ok: true, id: String(next.id) };
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
export function completeTask(db, args, origin, api) {
|
|
161
|
+
return updateTask(db, {
|
|
162
|
+
id: args.id || args.taskId,
|
|
163
|
+
type: "STATUS",
|
|
164
|
+
status: "2",
|
|
165
|
+
date: args.date || todayStr(),
|
|
166
|
+
difficulty: args.difficulty === undefined ? 0 : args.difficulty,
|
|
167
|
+
}, origin, api);
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
export function exportTasks(db, args, api) {
|
|
171
|
+
const format = String(args.format || "json").toLowerCase();
|
|
172
|
+
if (["json", "markdown", "md", "csv"].indexOf(format) < 0) throw new Error("format 只支持 json / markdown / csv");
|
|
173
|
+
let records;
|
|
174
|
+
let feedback = {};
|
|
175
|
+
if (Array.isArray(args.ids) && args.ids.length) {
|
|
176
|
+
const idStmt = db.prepare("SELECT * FROM task WHERE deleted_at IS NULL AND id IN (" + args.ids.map(function () { return "?"; }).join(",") + ")");
|
|
177
|
+
const rows = idStmt.all.apply(idStmt, args.ids.map(String));
|
|
178
|
+
records = rows.map(function (row) { return taskOut(row, nodeMap(db)); });
|
|
179
|
+
attachTags(db, api, records);
|
|
180
|
+
attachWorkspaces(db, records);
|
|
181
|
+
} else {
|
|
182
|
+
const listed = listTasks(db, Object.assign({}, args, { pageNumber: undefined, pageSize: undefined }), api);
|
|
183
|
+
records = listed.records;
|
|
184
|
+
feedback = withNotices({ filter: listed.filter }, listed.notices);
|
|
185
|
+
}
|
|
186
|
+
if (format === "json") {
|
|
187
|
+
return { ...feedback, format: "json", count: records.length, content: JSON.stringify({ exportedAt: now(), count: records.length, tasks: records }, null, 2) };
|
|
188
|
+
}
|
|
189
|
+
if (format === "csv") {
|
|
190
|
+
const cols = ["id", "title", "status", "priority", "difficulty", "tableId", "publishDate", "targetDate", "doneDate", "shutdownDate", "createdAt", "updatedAt", "tags", "workspaces"];
|
|
191
|
+
const lines = [cols.join(",")];
|
|
192
|
+
for (const t of records) {
|
|
193
|
+
lines.push(cols.map(function (c) {
|
|
194
|
+
if (c === "tags") return csvCell((t.tags || []).map(function (g) { return g.name; }).join("|"));
|
|
195
|
+
if (c === "workspaces") return csvCell((t.workspaces || []).map(function (w) { return w.title; }).join("|"));
|
|
196
|
+
return csvCell(t[c]);
|
|
197
|
+
}).join(","));
|
|
198
|
+
}
|
|
199
|
+
return { ...feedback, format: "csv", count: records.length, content: lines.join("\n") };
|
|
200
|
+
}
|
|
201
|
+
const lines = ["| id | 标题 | 状态 | P | 目标日期 | 标签 | 工作区 |", "| --- | --- | --- | --- | --- | --- | --- |"];
|
|
202
|
+
for (const t of records) {
|
|
203
|
+
lines.push("| " + t.id + " | " + String(t.title).replace(/\|/g, "\\|") + " | " + t.status + " | " + t.priority + " | " + (t.targetDate || "") + " | " + (t.tags || []).map(function (g) { return g.name; }).join(", ") + " | " + (t.workspaces || []).map(function (w) { return w.title; }).join(", ") + " |");
|
|
204
|
+
}
|
|
205
|
+
return { ...feedback, format: "markdown", count: records.length, content: lines.join("\n") };
|
|
206
|
+
}
|
|
207
|
+
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { nodeMap } from '../../db/db.js';
|
|
2
|
+
import { ownershipError, parseTablePath, pathFromMap } from '../model/task-ownership-path.js';
|
|
3
|
+
import { resolveTable, tableCatalog } from '../read/task-discovery.js';
|
|
4
|
+
import { insertOwnedNode } from '../../tree/task-node-write.js';
|
|
5
|
+
|
|
6
|
+
export function validateTargetArgs(db, args, api) {
|
|
7
|
+
const hasId = args.tableId !== undefined && args.tableId !== null && String(args.tableId).trim() !== '';
|
|
8
|
+
const hasPath = args.tablePath !== undefined && args.tablePath !== null && args.tablePath !== '';
|
|
9
|
+
if (hasId && hasPath) throw ownershipError('TARGET_CONFLICT', 'tableId 与 tablePath 恰好提供一个');
|
|
10
|
+
if (hasId && !['string','number'].includes(typeof args.tableId)) throw ownershipError('INVALID_TARGET_OPTIONS', 'tableId 必须是string或number');
|
|
11
|
+
if (!hasId && !hasPath) {
|
|
12
|
+
const query = [args.title, args.description].filter(Boolean).join(' ').trim();
|
|
13
|
+
const found = query ? resolveTable(db, { query, limit: 5 }, api).candidates : [];
|
|
14
|
+
const browse = found.length ? found : tableCatalog(db, api).tables.slice(0,5);
|
|
15
|
+
throw ownershipError('TABLE_REQUIRED', '请先明确选择目标表。' + (found.length ? '以下是词项候选,需核对' : '以下是可浏览表,非推荐'), { candidateTables: browse.map(t => ({ id:t.id, path:t.path, description:t.description, taskCount:t.taskCount })), nextActions: ['tasks.resolveTable(' + JSON.stringify({ query: query || '任务主题' }) + ')', 'tasks.capabilities({limit:50})', '确认新建时使用 tablePath + createMissing:true + pathDescriptions;拿不准就问用户'] });
|
|
16
|
+
}
|
|
17
|
+
if (args.createMissing !== undefined && typeof args.createMissing !== 'boolean') throw ownershipError('INVALID_TARGET_OPTIONS', 'createMissing 必须是 boolean');
|
|
18
|
+
if (hasId && (args.createMissing === true || args.pathDescriptions !== undefined)) throw ownershipError('INVALID_TARGET_OPTIONS', 'createMissing/pathDescriptions 仅用于 tablePath');
|
|
19
|
+
if (args.pathDescriptions !== undefined && args.createMissing !== true) throw ownershipError('INVALID_TARGET_OPTIONS', 'pathDescriptions 仅用于 createMissing=true');
|
|
20
|
+
const parts = hasPath ? parseTablePath(args.tablePath) : null;
|
|
21
|
+
if (args.pathDescriptions !== undefined && (!Array.isArray(args.pathDescriptions) || args.pathDescriptions.length !== parts.length || args.pathDescriptions.some(s => typeof s !== 'string' || s.length > 2000))) throw ownershipError('INVALID_TARGET_OPTIONS', 'pathDescriptions 必须与路径等长,每项为最多2000字符的字符串');
|
|
22
|
+
return { hasId, parts };
|
|
23
|
+
}
|
|
24
|
+
export function requireOwnedTable(db, id) {
|
|
25
|
+
if (!['string','number'].includes(typeof id) || !String(id).trim()) throw ownershipError('TABLE_NOT_FOUND', 'tableId 不能为空');
|
|
26
|
+
const row = db.prepare('SELECT * FROM task_node WHERE id=? AND deleted_at IS NULL').get(String(id));
|
|
27
|
+
if (!row) throw ownershipError('TABLE_NOT_FOUND', '任务表不存在:' + id);
|
|
28
|
+
if (String(row.type) !== '1') throw ownershipError('TARGET_NOT_TABLE', '目标节点不是任务表:' + id);
|
|
29
|
+
pathFromMap(row.id, nodeMap(db));
|
|
30
|
+
return row;
|
|
31
|
+
}
|
|
32
|
+
export function resolveTarget(db, args, validated, origin, api) {
|
|
33
|
+
if (validated.hasId) return { table: requireOwnedTable(db, args.tableId), createdNodes: [] };
|
|
34
|
+
const map = nodeMap(db), roots = [...map.values()].filter(n => n.deleted_at == null && String(n.parent_id) === '0');
|
|
35
|
+
if (roots.length !== 1 || String(roots[0].type) !== '2') throw ownershipError('TREE_CORRUPT', '需要唯一逻辑根;请修复树后重试');
|
|
36
|
+
let parent = roots[0];
|
|
37
|
+
const createdNodes = [];
|
|
38
|
+
for (let i=0;i<validated.parts.length;i++) {
|
|
39
|
+
const name = validated.parts[i], type = i === validated.parts.length-1 ? '1' : '0';
|
|
40
|
+
const matches = db.prepare('SELECT * FROM task_node WHERE parent_id=? AND name=? AND deleted_at IS NULL').all(String(parent.id),name);
|
|
41
|
+
if (matches.length > 1) throw ownershipError('PATH_AMBIGUOUS', '同级路径名称不唯一:' + name, { candidates: matches.map(n => ({ id:String(n.id),type:String(n.type),path:pathFromMap(n.id,nodeMap(db)).path })) });
|
|
42
|
+
let node = matches[0];
|
|
43
|
+
if (node && String(node.type) !== type) throw ownershipError('PATH_TYPE_CONFLICT', '路径段 ' + name + ' 必须是' + (type === '1' ? '任务表' : '任务组'));
|
|
44
|
+
if (!node) {
|
|
45
|
+
if (args.createMissing !== true) throw ownershipError('PATH_NOT_FOUND', '已解析 ' + validated.parts.slice(0,i).join('/') + ';第一个缺失段:' + name);
|
|
46
|
+
const description = args.pathDescriptions?.[i];
|
|
47
|
+
if (typeof description !== 'string' || !description.trim()) throw ownershipError('INVALID_TARGET_OPTIONS', '新节点必须给非空职责描述:' + name);
|
|
48
|
+
node = insertOwnedNode(db, parent.id, name, type, description, origin);
|
|
49
|
+
const info = pathFromMap(node.id, nodeMap(db));
|
|
50
|
+
createdNodes.push({ id:String(node.id),name,type,description,...info });
|
|
51
|
+
api.emit('task-nodes-changed', {id:String(node.id),parentId:String(parent.id),op:'create'});
|
|
52
|
+
}
|
|
53
|
+
parent = node;
|
|
54
|
+
}
|
|
55
|
+
return { table: requireOwnedTable(db,parent.id), createdNodes };
|
|
56
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { ownershipError } from '../model/task-ownership-path.js';
|
|
2
|
+
/** 事务期间只收集事件;成功 COMMIT 后通知,失败/dryRun 不发送。 */
|
|
3
|
+
export function taskTransaction(db, api, body, dryRun = false) {
|
|
4
|
+
const events = [], buffered = Object.create(api);
|
|
5
|
+
buffered.emit = (kind,payload) => events.push([kind,payload]);
|
|
6
|
+
let begun = false, result;
|
|
7
|
+
try {
|
|
8
|
+
db.exec('BEGIN IMMEDIATE'); begun = true;
|
|
9
|
+
result = body(buffered);
|
|
10
|
+
db.exec(dryRun ? 'ROLLBACK' : 'COMMIT'); begun = false;
|
|
11
|
+
} catch (error) {
|
|
12
|
+
if (begun) { try { db.exec('ROLLBACK'); } catch {} }
|
|
13
|
+
if (/SQLITE_BUSY|database is locked/.test(String(error.message))) throw ownershipError('DATABASE_BUSY', '数据库繁忙,请稍后以相同 dedupeKey 重试', { retryable: true });
|
|
14
|
+
throw error;
|
|
15
|
+
}
|
|
16
|
+
if (!dryRun) for (const [kind,payload] of events) api.emit(kind,payload);
|
|
17
|
+
return result;
|
|
18
|
+
}
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
// 与 task-bulk 的循环引用只在调用期取值,顶层不求值。
|
|
2
|
+
import {
|
|
3
|
+
now,
|
|
4
|
+
idOf,
|
|
5
|
+
todayStr,
|
|
6
|
+
} from "../../db/db.js";
|
|
7
|
+
// task-query 循环依赖仅在调用期读取 tasks 的函数/常量。
|
|
8
|
+
import { priorityForStatus } from "../model/task-priority.js";
|
|
9
|
+
import {
|
|
10
|
+
tagsAvailable,
|
|
11
|
+
replaceTaskTags,
|
|
12
|
+
attachTags,
|
|
13
|
+
} from "../../tagging/tagging.js";
|
|
14
|
+
import { tagMissingNotices, withNotices, STATUSES, STATUS_NAMES, asCode, putTypeCode, clampDifficulty, dateArg, getTask, requireTable, saveTaskRow, outOne, writeChange, checkRequiredDates, resolveTagPatch } from "../model/task-model.js";
|
|
15
|
+
import { taskTransaction } from './task-transaction.js';
|
|
16
|
+
import { setTaskWorkspaces, attachWorkspaces } from '../../workspace/workspace-store.js';
|
|
17
|
+
import { assertClaimToken, clearClaimFields, claimError } from './task-claim.js';
|
|
18
|
+
import { ownershipFields } from '../model/task-ownership-path.js';
|
|
19
|
+
export function updateTask(db, args, origin, api, opts) {
|
|
20
|
+
if (!opts?.skipTx) return taskTransaction(db, api, buffered => updateTask(db,args,origin,buffered,{skipTx:true}));
|
|
21
|
+
const id = idOf(args.id || args.taskId);
|
|
22
|
+
const cur = getTask(db, id);
|
|
23
|
+
if (!cur) throw new Error("任务不存在:" + (id || "(空)"));
|
|
24
|
+
const ts = now();
|
|
25
|
+
const next = Object.assign({}, cur);
|
|
26
|
+
const token = args.claimToken === undefined || args.claimToken === null ? "" : String(args.claimToken).trim();
|
|
27
|
+
if (token) assertClaimToken(db, id, token);
|
|
28
|
+
const type = putTypeCode(args.type);
|
|
29
|
+
|
|
30
|
+
if (type === "0") {
|
|
31
|
+
if (args.status === undefined) throw new Error("STATUS 更新缺少 status");
|
|
32
|
+
next.status = asCode(args.status, STATUS_NAMES, STATUSES, "status");
|
|
33
|
+
const date = dateArg(args.date || args.doneDate || args.shutdownDate, "date");
|
|
34
|
+
if (next.status === "2") {
|
|
35
|
+
next.done_date = date || todayStr();
|
|
36
|
+
next.difficulty = clampDifficulty(args.difficulty, cur.difficulty === null ? 0 : Number(cur.difficulty));
|
|
37
|
+
if (args.review !== undefined) next.review = String(args.review === null ? "" : args.review);
|
|
38
|
+
if (next.done_date < String(cur.publish_date)) throw new Error("doneDate 不能早于 publishDate");
|
|
39
|
+
} else if (next.status === "1") {
|
|
40
|
+
next.shutdown_date = date || todayStr();
|
|
41
|
+
if (next.shutdown_date < String(cur.publish_date)) throw new Error("shutdownDate 不能早于 publishDate");
|
|
42
|
+
}
|
|
43
|
+
} else if (type === "1") {
|
|
44
|
+
next.priority = priorityForStatus(next.status, args.priority, Number(cur.priority) || 1);
|
|
45
|
+
} else if (type === "2") {
|
|
46
|
+
const title = String(args.title === undefined || args.title === null ? "" : args.title).trim();
|
|
47
|
+
if (!title) throw new Error("title 不能为空");
|
|
48
|
+
next.title = title;
|
|
49
|
+
} else if (type === "3") {
|
|
50
|
+
next.description = String(args.description === undefined || args.description === null ? "" : args.description);
|
|
51
|
+
} else if (type === "4") {
|
|
52
|
+
next.review = String(args.review === undefined || args.review === null ? "" : args.review);
|
|
53
|
+
} else {
|
|
54
|
+
if (args.title !== undefined) {
|
|
55
|
+
const title = String(args.title === null ? "" : args.title).trim();
|
|
56
|
+
if (!title) throw new Error("title 不能为空");
|
|
57
|
+
next.title = title;
|
|
58
|
+
}
|
|
59
|
+
if (args.description !== undefined) next.description = String(args.description === null ? "" : args.description);
|
|
60
|
+
if (args.review !== undefined) next.review = String(args.review === null ? "" : args.review);
|
|
61
|
+
if (args.status !== undefined) next.status = asCode(args.status, STATUS_NAMES, STATUSES, "status");
|
|
62
|
+
if (args.priority !== undefined) next.priority = priorityForStatus(next.status, args.priority, Number(cur.priority) || 1);
|
|
63
|
+
if (args.difficulty !== undefined) next.difficulty = clampDifficulty(args.difficulty, null);
|
|
64
|
+
if (args.publishDate !== undefined) next.publish_date = dateArg(args.publishDate, "publishDate") || String(cur.publish_date);
|
|
65
|
+
if (args.targetDate !== undefined) next.target_date = dateArg(args.targetDate, "targetDate") || String(cur.target_date);
|
|
66
|
+
if (args.doneDate !== undefined) next.done_date = dateArg(args.doneDate, "doneDate");
|
|
67
|
+
if (args.shutdownDate !== undefined) next.shutdown_date = dateArg(args.shutdownDate, "shutdownDate");
|
|
68
|
+
if (args.tableId !== undefined) {
|
|
69
|
+
const table = requireTable(db, args.tableId);
|
|
70
|
+
next.table_id = String(table.id);
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// 只有「显式写 status」才拦截;已接取任务改标题等字段时 next.status 本来就等于 4。
|
|
75
|
+
if (next.status === "4" && args.status !== undefined) {
|
|
76
|
+
throw claimError("CLAIM_REQUIRED", "状态「已接取」不能通过 tasks.update 直接写入,请使用 tasks.claim / tasks.claimBatch / tasks.grab 以 CAS 方式接取", { nextActions: ["tasks.claim({id})", "tasks.claimBatch({ids:[...]})"] });
|
|
77
|
+
}
|
|
78
|
+
if (next.status === "2" && next.done_date === null) next.done_date = todayStr();
|
|
79
|
+
if (next.status === "2" && (next.difficulty === null || next.difficulty === undefined)) next.difficulty = 0;
|
|
80
|
+
// 优先级不变量兜底:非开启/非已接取状态一律 P0;开启类不允许 P0(历史数据回落到 P1)。
|
|
81
|
+
if (next.status !== "0" && next.status !== "4") next.priority = 0;
|
|
82
|
+
else if (!next.priority) next.priority = 1;
|
|
83
|
+
// 进入终态时清空接取字段,保持「status=4 才允许有 owner/token」的列不变量。
|
|
84
|
+
if (next.status === "1" || next.status === "2") Object.assign(next, clearClaimFields(next));
|
|
85
|
+
if (next.status === "1" && next.shutdown_date === null) next.shutdown_date = todayStr();
|
|
86
|
+
checkRequiredDates(next);
|
|
87
|
+
next.updated_at = ts;
|
|
88
|
+
next.rev = Number(cur.rev) + 1;
|
|
89
|
+
const wantsTagWrite = args.tagIds !== undefined || args.tags !== undefined
|
|
90
|
+
|| args.addTagIds !== undefined || args.addTags !== undefined
|
|
91
|
+
|| args.removeTagIds !== undefined || args.removeTags !== undefined;
|
|
92
|
+
const tagWritable = tagsAvailable(db, api);
|
|
93
|
+
const desiredTags = wantsTagWrite && tagWritable ? resolveTagPatch(db, next, args, ts, origin, false) : null;
|
|
94
|
+
saveTaskRow(db, next);
|
|
95
|
+
if (desiredTags) replaceTaskTags(db, String(next.id), desiredTags, ts, origin);
|
|
96
|
+
if (args.workspaceIds !== undefined && args.workspaceIds !== null) {
|
|
97
|
+
setTaskWorkspaces(db, String(next.id), args.workspaceIds, ts, origin, api);
|
|
98
|
+
}
|
|
99
|
+
writeChange(db, next, "update", origin, api, ts);
|
|
100
|
+
const task = outOne(db, next);
|
|
101
|
+
attachTags(db, api, task);
|
|
102
|
+
attachWorkspaces(db, [task]);
|
|
103
|
+
return withNotices({ task: task, ...ownershipFields(task) }, tagMissingNotices(args, tagWritable));
|
|
104
|
+
}
|