schedule-service.js
5.87 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
/**
* ScheduleService — 公司级工作日历系统
*
* 数据目录: data/{companyId}/schedule.json
*
* 核心概念:
* Schedule = 公司的每日时间表
* TimeSlot = 某个Agent在某个时间点执行的固定任务
*
* 与 HeartbeatService 集成:
* 心跳触发时,ScheduleService 检查当前时间是否有需要执行的日程
* 匹配到的日程自动触发对应 Agent 的 Chat
*/
const fs = require('fs');
const path = require('path');
const DATA_DIR = path.resolve(__dirname, '../../data');
class ScheduleService {
/**
* 获取公司的日程配置
* @param {string} companyId
* @returns {object} schedule config
*/
getSchedule(companyId) {
const fp = path.join(DATA_DIR, companyId, 'schedule.json');
if (!fs.existsSync(fp)) return { timezone: 'Asia/Shanghai', slots: [] };
try {
return JSON.parse(fs.readFileSync(fp, 'utf-8'));
} catch {
return { timezone: 'Asia/Shanghai', slots: [] };
}
}
/**
* 保存公司日程配置
* @param {string} companyId
* @param {object} schedule
*/
saveSchedule(companyId, schedule) {
const fp = path.join(DATA_DIR, companyId, 'schedule.json');
fs.writeFileSync(fp, JSON.stringify(schedule, null, 2), 'utf-8');
}
/**
* 添加日程时间槽
* @param {string} companyId
* @param {object} slot - { time, agent, task, days?, enabled? }
* time: "09:00" (24小时制)
* agent: "trend-hunter" (Agent ID)
* task: "执行每日热点抓取" (任务描述)
* days: ["mon","tue","wed","thu","fri","sat","sun"] (可选,默认每天)
* enabled: true (可选)
*/
addSlot(companyId, slot) {
const schedule = this.getSchedule(companyId);
const newSlot = {
id: `S-${Date.now().toString(36)}`,
time: slot.time,
agent: slot.agent,
task: slot.task,
days: slot.days || ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'],
enabled: slot.enabled !== false,
type: slot.type || 'task', // task | meeting | review
createdAt: new Date().toISOString(),
};
schedule.slots.push(newSlot);
this.saveSchedule(companyId, schedule);
console.log(`[Schedule] 📅 ${companyId} 新增日程: ${newSlot.time} ${newSlot.agent} - ${newSlot.task}`);
return newSlot;
}
/**
* 删除日程
*/
removeSlot(companyId, slotId) {
const schedule = this.getSchedule(companyId);
schedule.slots = schedule.slots.filter(s => s.id !== slotId);
this.saveSchedule(companyId, schedule);
return true;
}
/**
* 更新日程
*/
updateSlot(companyId, slotId, updates) {
const schedule = this.getSchedule(companyId);
const slot = schedule.slots.find(s => s.id === slotId);
if (!slot) return null;
if (updates.time !== undefined) slot.time = updates.time;
if (updates.agent !== undefined) slot.agent = updates.agent;
if (updates.task !== undefined) slot.task = updates.task;
if (updates.days !== undefined) slot.days = updates.days;
if (updates.enabled !== undefined) slot.enabled = updates.enabled;
this.saveSchedule(companyId, schedule);
return slot;
}
/**
* 获取当前时间应该触发的日程
*
* @param {string} companyId
* @param {number} toleranceMinutes - 容差(分钟),默认 15 分钟
* @returns {Array} 到期的 slots
*/
getDueSlots(companyId, toleranceMinutes = 15) {
const schedule = this.getSchedule(companyId);
if (!schedule.slots || schedule.slots.length === 0) return [];
const now = new Date();
// 转换到公司时区
const tz = schedule.timezone || 'Asia/Shanghai';
const localTime = new Date(now.toLocaleString('en-US', { timeZone: tz }));
const currentHour = localTime.getHours();
const currentMinute = localTime.getMinutes();
const dayNames = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'];
const currentDay = dayNames[localTime.getDay()];
// 记录已执行的日程(防重复触发)
const executedPath = path.join(DATA_DIR, companyId, '.schedule-executed.json');
let executed = {};
try { executed = JSON.parse(fs.readFileSync(executedPath, 'utf-8')); } catch {}
const today = localTime.toISOString().slice(0, 10);
// 清理前一天的记录
for (const key of Object.keys(executed)) {
if (!key.startsWith(today)) delete executed[key];
}
const dueSlots = [];
for (const slot of schedule.slots) {
if (!slot.enabled) continue;
if (!slot.days.includes(currentDay)) continue;
// 解析 slot 时间
const [slotHour, slotMinute] = slot.time.split(':').map(Number);
const diffMinutes = (currentHour * 60 + currentMinute) - (slotHour * 60 + slotMinute);
// 在容差范围内且未执行过
if (diffMinutes >= 0 && diffMinutes < toleranceMinutes) {
const execKey = `${today}:${slot.id}`;
if (!executed[execKey]) {
dueSlots.push(slot);
executed[execKey] = new Date().toISOString();
}
}
}
// 保存执行记录
if (dueSlots.length > 0) {
fs.writeFileSync(executedPath, JSON.stringify(executed, null, 2), 'utf-8');
}
return dueSlots;
}
/**
* 生成人类可读的日程表文本 (用于注入 Agent prompt)
*/
formatScheduleForAgent(companyId, agentId) {
const schedule = this.getSchedule(companyId);
const mySlots = schedule.slots.filter(s => s.agent === agentId && s.enabled);
if (mySlots.length === 0) return '';
const lines = ['## 📅 我的每日日程', ''];
const sorted = [...mySlots].sort((a, b) => a.time.localeCompare(b.time));
for (const slot of sorted) {
const daysStr = slot.days.length === 7 ? '每天' : slot.days.join('/');
const typeEmoji = slot.type === 'meeting' ? '📋' : slot.type === 'review' ? '🔍' : '📌';
lines.push(`- **${slot.time}** ${typeEmoji} ${slot.task} (${daysStr})`);
}
return lines.join('\n');
}
}
module.exports = { ScheduleService };