mirror of
https://github.com/RuoJi6/ARTEX.git
synced 2026-12-04 12:41:50 +08:00
feat(schedules,chat): redesign schedules as interactive calendar with server clock and chat tools
- Expose top-level server_time, server_timezone, and server_utc_offset_minutes on GET /api/schedules - Add list_task_schedules, create_task_schedule, update_task_schedule, and delete_task_schedule chat agent tools - Redesign /function/schedules into a calendar workspace (mini month, status filters, Up next, Day/Week/Month/Agenda views, server-time red indicator, TZ/date switcher, drag-move/resize, rich detail popover) - Add schedule-calendar math unit tests and Postgres integration tests for chat schedule tools
This commit is contained in:
1 parent
778e49317d
commit
8568c41528
10 files changed
+2527
-26
No files matched your search
File diff suppressed because it is too large.
Load diff
@@ -29,6 +29,7 @@ import { Button } from "@/components/ui/button";
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { Checkbox } from "@/components/ui/checkbox";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
|
||||
@@ -36,7 +37,9 @@ import { localizedError } from "@/i18n/errors";
|
||||
import { useLiveTranslation } from "@/i18n/use-live-translation";
|
||||
import { api, type ScheduleInput } from "@/lib/api";
|
||||
import { scheduleDisplay } from "@/lib/schedule-display";
|
||||
import { formatMinutesAsClock, weekdayOfDateKey } from "@/lib/schedule-calendar";
|
||||
import type { ProxyPoolEntry, Task, TaskSchedule } from "@/lib/types";
|
||||
import { ScheduleCalendarWorkspace } from "./_components/schedule-calendar-workspace";
|
||||
|
||||
const blank: ScheduleInput = {
|
||||
name: "",
|
||||
@@ -381,6 +384,8 @@ export default function SchedulesPage() {
|
||||
const [items, setItems] = React.useState<TaskSchedule[]>([]);
|
||||
const [tasks, setTasks] = React.useState<Task[]>([]);
|
||||
const [proxyPool, setProxyPool] = React.useState<ProxyPoolEntry[]>([]);
|
||||
const [serverTimeISO, setServerTimeISO] = React.useState<string | undefined>(undefined);
|
||||
const [serverUtcOffsetMinutes, setServerUtcOffsetMinutes] = React.useState<number | undefined>(undefined);
|
||||
const [loading, setLoading] = React.useState(true);
|
||||
const [editing, setEditing] = React.useState<{ id?: number; value: ScheduleInput } | null>(null);
|
||||
const [saving, setSaving] = React.useState(false);
|
||||
@@ -394,12 +399,14 @@ export default function SchedulesPage() {
|
||||
const load = React.useCallback(async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const [s, t, pool] = await Promise.all([
|
||||
api.schedules(),
|
||||
const [sRes, t, pool] = await Promise.all([
|
||||
api.schedulesWithMeta(),
|
||||
api.tasks(),
|
||||
api.proxyPool().catch(() => ({ entries: [] as ProxyPoolEntry[], active_id: "", switch_log: [] })),
|
||||
]);
|
||||
setItems(s);
|
||||
setItems(sRes.schedules);
|
||||
setServerTimeISO(sRes.server_time);
|
||||
setServerUtcOffsetMinutes(sRes.server_utc_offset_minutes);
|
||||
setTasks(t.tasks);
|
||||
setProxyPool(pool.entries ?? []);
|
||||
} catch (e) {
|
||||
@@ -468,6 +475,71 @@ export default function SchedulesPage() {
|
||||
setTimelineLoadingId(null);
|
||||
}
|
||||
};
|
||||
const openEdit = (item: TaskSchedule) => {
|
||||
setEditing({
|
||||
id: item.id,
|
||||
value: {
|
||||
name: item.name,
|
||||
enabled: item.enabled,
|
||||
timezone_mode: item.timezone_mode,
|
||||
schedule_type: item.schedule_type,
|
||||
run_date: item.run_date,
|
||||
end_date: item.end_date,
|
||||
weekdays: item.weekdays,
|
||||
start_time: item.start_time.slice(0, 5),
|
||||
end_time: item.end_time?.slice(0, 5),
|
||||
start_immediately: item.start_immediately,
|
||||
proxy_mode: item.proxy_mode ?? "inherit",
|
||||
proxy_pool_id: item.proxy_pool_id ?? "",
|
||||
proxy_url: item.proxy_url ?? "",
|
||||
task_ids: item.task_ids,
|
||||
},
|
||||
});
|
||||
};
|
||||
const openDuplicate = (item: TaskSchedule) => {
|
||||
setEditing({
|
||||
value: {
|
||||
name: `${item.name}${translate("schedule.calendar.duplicateSuffix")}`,
|
||||
enabled: item.enabled,
|
||||
timezone_mode: item.timezone_mode,
|
||||
schedule_type: item.schedule_type,
|
||||
run_date: item.run_date,
|
||||
end_date: item.end_date,
|
||||
weekdays: item.weekdays,
|
||||
start_time: item.start_time.slice(0, 5),
|
||||
end_time: item.end_time?.slice(0, 5),
|
||||
start_immediately: false,
|
||||
proxy_mode: item.proxy_mode ?? "inherit",
|
||||
proxy_pool_id: item.proxy_pool_id ?? "",
|
||||
proxy_url: item.proxy_url ?? "",
|
||||
task_ids: item.task_ids,
|
||||
},
|
||||
});
|
||||
};
|
||||
const openCreateAtSlot = (dateKey: string, startMin: number, endMin: number) => {
|
||||
setEditing({
|
||||
value: {
|
||||
...blank,
|
||||
schedule_type: "once",
|
||||
run_date: dateKey,
|
||||
end_date: "",
|
||||
weekdays: [weekdayOfDateKey(dateKey)],
|
||||
start_time: formatMinutesAsClock(startMin),
|
||||
end_time: formatMinutesAsClock(endMin),
|
||||
task_ids: [],
|
||||
},
|
||||
});
|
||||
};
|
||||
const quickUpdateSchedule = async (id: number, input: ScheduleInput) => {
|
||||
try {
|
||||
await api.updateSchedule(id, input);
|
||||
await invalidateTimeline(id);
|
||||
await load();
|
||||
toast.success(translate("schedule.calendar.dragUpdated"));
|
||||
} catch (e) {
|
||||
toast.error(scheduleErrorText(localizedError(e, translate)));
|
||||
}
|
||||
};
|
||||
const invalidateTimeline = async (id: number) => {
|
||||
setTimelineById((current) => {
|
||||
if (!current[id]) return current;
|
||||
@@ -909,28 +981,48 @@ export default function SchedulesPage() {
|
||||
);
|
||||
}
|
||||
return (
|
||||
<div className="flex flex-1 flex-col gap-5 p-5">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex flex-1 flex-col gap-3 p-4">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<div>
|
||||
<h1 className="flex items-center gap-2 font-semibold text-xl">
|
||||
<CalendarClock />
|
||||
<h1 className="flex items-center gap-2 font-semibold text-lg">
|
||||
<CalendarClock className="size-5" />
|
||||
{translate("schedule.title")}
|
||||
</h1>
|
||||
<p className="mt-1 text-muted-foreground text-sm">{translate("schedule.description")}</p>
|
||||
<p className="text-muted-foreground text-xs">{translate("schedule.description")}</p>
|
||||
</div>
|
||||
<Button onClick={() => setEditing({ value: { ...blank, task_ids: [] } })}>
|
||||
<Plus data-icon="inline-start" />
|
||||
{translate("schedule.create")}
|
||||
</Button>
|
||||
</div>
|
||||
{editing && (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>{editing.id ? translate("schedule.editSchedule") : translate("schedule.create")}</CardTitle>
|
||||
<CardDescription>{translate("schedule.pauseHelp")}</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
|
||||
<ScheduleCalendarWorkspace
|
||||
schedules={items}
|
||||
tasks={tasks}
|
||||
proxyPool={proxyPool}
|
||||
serverTimeISO={serverTimeISO}
|
||||
serverUtcOffsetMinutes={serverUtcOffsetMinutes}
|
||||
query={query}
|
||||
onQueryChange={updateQuery}
|
||||
onCreateNew={() => setEditing({ value: { ...blank, task_ids: [] } })}
|
||||
onCreateAtSlot={openCreateAtSlot}
|
||||
onEdit={openEdit}
|
||||
onDuplicate={openDuplicate}
|
||||
onAction={action}
|
||||
onDelete={remove}
|
||||
onQuickUpdateSchedule={quickUpdateSchedule}
|
||||
onLoadTimeline={async (id) => {
|
||||
if (!timelineById[id]) await refreshTimeline(id);
|
||||
}}
|
||||
renderTimeline={(id) => <ScheduleTimeline schedule={timelineById[id]} loading={timelineLoadingId === id} />}
|
||||
listViewContent={scheduleContent}
|
||||
/>
|
||||
|
||||
<Dialog open={!!editing} onOpenChange={(open) => !open && setEditing(null)}>
|
||||
<DialogContent className="max-h-[90vh] max-w-2xl overflow-y-auto">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{editing?.id ? translate("schedule.editSchedule") : translate("schedule.create")}</DialogTitle>
|
||||
<DialogDescription>{translate("schedule.pauseHelp")}</DialogDescription>
|
||||
</DialogHeader>
|
||||
{editing ? (
|
||||
<ScheduleForm
|
||||
key={editing.id ?? `new-${editing.value.run_date ?? ""}-${editing.value.start_time}`}
|
||||
value={editing.value}
|
||||
tasks={tasks}
|
||||
proxyPool={proxyPool}
|
||||
@@ -938,10 +1030,9 @@ export default function SchedulesPage() {
|
||||
onCancel={() => setEditing(null)}
|
||||
onSave={save}
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
{scheduleContent}
|
||||
) : null}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -211,4 +211,49 @@ export const scheduleMessages = {
|
||||
"设为直连、代理池或指定代理后,保存与计划触发时会自动应用到所有关联任务的容器。",
|
||||
"When set to direct, proxy pool, or specific proxy, bound tasks automatically apply this route on save and when the schedule runs.",
|
||||
],
|
||||
"schedule.calendar.searchEvents": ["搜索计划、备注或任务 ID…", "Search schedules, remarks, or task IDs…"],
|
||||
"schedule.calendar.today": ["今天", "Today"],
|
||||
"schedule.calendar.view.day": ["日", "Day"],
|
||||
"schedule.calendar.view.week": ["周", "Week"],
|
||||
"schedule.calendar.view.month": ["月", "Month"],
|
||||
"schedule.calendar.view.list": ["列表", "Agenda"],
|
||||
"schedule.calendar.allDay": ["全天 / 持续", "All day"],
|
||||
"schedule.calendar.filters": ["计划状态", "Calendars"],
|
||||
"schedule.calendar.upNext": ["即将执行", "Up next"],
|
||||
"schedule.calendar.noUpcoming": ["暂无待触发计划", "No upcoming schedules"],
|
||||
"schedule.calendar.clockMode": ["日历时间基准", "Calendar clock"],
|
||||
"schedule.calendar.clockServer": ["服务器时间", "Server time"],
|
||||
"schedule.calendar.clockBeijing": ["北京时间", "Beijing (GMT+8)"],
|
||||
"schedule.calendar.clockLocal": ["本地时间", "Local time"],
|
||||
"schedule.calendar.jumpDate": ["跳转日期", "Jump to date"],
|
||||
"schedule.calendar.duplicate": ["复制计划", "Duplicate"],
|
||||
"schedule.calendar.duplicateSuffix": ["(副本)", " (copy)"],
|
||||
"schedule.calendar.boundTasksCount": ["{{count}} 个关联任务", "{{count}} linked tasks"],
|
||||
"schedule.calendar.boundTasksCount_one": ["1 个关联任务", "1 linked task"],
|
||||
"schedule.calendar.boundTasksCount_other": ["{{count}} 个关联任务", "{{count}} linked tasks"],
|
||||
"schedule.calendar.noBoundTasks": ["未绑定任务", "No linked tasks"],
|
||||
"schedule.calendar.moreEvents": ["还有 {{count}} 项", "+{{count}} more"],
|
||||
"schedule.calendar.inMinutes": ["{{count}} 分钟后", "in {{count}}m"],
|
||||
"schedule.calendar.inHours": ["{{count}} 小时后", "in {{count}}h"],
|
||||
"schedule.calendar.inDays": ["{{count}} 天后", "in {{count}}d"],
|
||||
"schedule.calendar.nowRunning": ["进行中", "Now"],
|
||||
"schedule.calendar.dragUpdated": ["已更新计划时间窗", "Schedule window updated"],
|
||||
"schedule.calendar.dragHint": ["拖动调整时段 · 拖底边改时长", "Drag to move · drag bottom edge to resize"],
|
||||
"schedule.calendar.durationHours": ["{{hours}}小时", "{{hours}}h"],
|
||||
"schedule.calendar.durationHoursMinutes": ["{{hours}}小时{{minutes}}分", "{{hours}}h {{minutes}}m"],
|
||||
"schedule.calendar.durationMinutes": ["{{minutes}}分钟", "{{minutes}}m"],
|
||||
"schedule.calendar.timelineToggle": ["运行记录", "Run timeline"],
|
||||
"schedule.calendar.prevMonth": ["上个月", "Previous month"],
|
||||
"schedule.calendar.nextMonth": ["下个月", "Next month"],
|
||||
"schedule.calendar.prevPeriod": ["上一周期", "Previous period"],
|
||||
"schedule.calendar.nextPeriod": ["下一周期", "Next period"],
|
||||
"schedule.calendar.selectAll": ["全选", "All"],
|
||||
"schedule.calendar.continuousTag": ["持续运行", "Continuous"],
|
||||
"schedule.calendar.weekdayShort.1": ["一", "M"],
|
||||
"schedule.calendar.weekdayShort.2": ["二", "T"],
|
||||
"schedule.calendar.weekdayShort.3": ["三", "W"],
|
||||
"schedule.calendar.weekdayShort.4": ["四", "T"],
|
||||
"schedule.calendar.weekdayShort.5": ["五", "F"],
|
||||
"schedule.calendar.weekdayShort.6": ["六", "S"],
|
||||
"schedule.calendar.weekdayShort.7": ["日", "S"],
|
||||
} as const;
|
||||
@@ -530,6 +530,18 @@ export const api = {
|
||||
schedule: input.schedule ? schedulePayload(input.schedule) : undefined,
|
||||
proxy_route: input.proxyRoute && input.proxyRoute.mode !== "inherit" ? input.proxyRoute : undefined,
|
||||
}),
|
||||
schedulesWithMeta: () =>
|
||||
get<{
|
||||
schedules: TaskSchedule[];
|
||||
server_time?: string;
|
||||
server_timezone?: string;
|
||||
server_utc_offset_minutes?: number;
|
||||
}>("/schedules").then((r) => ({
|
||||
schedules: arr(r.schedules),
|
||||
server_time: r.server_time,
|
||||
server_timezone: r.server_timezone,
|
||||
server_utc_offset_minutes: r.server_utc_offset_minutes,
|
||||
})),
|
||||
schedules: () => get<{ schedules: TaskSchedule[] }>("/schedules").then((r) => arr(r.schedules)),
|
||||
renameSchedule: (id: number, name: string) => patch<TaskSchedule>(`/schedules/${id}/metadata`, { name }),
|
||||
updateScheduleRemark: (id: number, remark: string) => patch<TaskSchedule>(`/schedules/${id}/remark`, { remark }),
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import {
|
||||
buildScheduleInputFromDrag,
|
||||
buildWeekDateKeys,
|
||||
expandSchedulesForDateKeys,
|
||||
formatGMTOffset,
|
||||
layoutDayTimedEvents,
|
||||
toZonedParts,
|
||||
} from "./schedule-calendar.ts";
|
||||
|
||||
test("server timezone offset formatting and zoned parts stay deterministic", () => {
|
||||
assert.equal(formatGMTOffset(480), "GMT+8");
|
||||
assert.equal(formatGMTOffset(330), "GMT+5:30");
|
||||
assert.equal(formatGMTOffset(0), "UTC");
|
||||
const utcMs = Date.UTC(2026, 11, 2, 16, 15, 0); // 2026-12-02T16:15:00Z -> 2026-12-03 00:15 GMT+8
|
||||
const bj = toZonedParts(utcMs, 480);
|
||||
assert.equal(bj.dateKey, "2026-12-03");
|
||||
assert.equal(bj.hour, 0);
|
||||
assert.equal(bj.minute, 15);
|
||||
assert.equal(bj.weekday, 4); // Thursday
|
||||
});
|
||||
|
||||
test("weekly, cross-midnight, open-ended, and timezone shift expansion work accurately", () => {
|
||||
const weekKeys = buildWeekDateKeys("2026-12-02"); // Mon 2026-11-30 .. Sun 2026-12-06
|
||||
assert.equal(weekKeys[0], "2026-11-30");
|
||||
assert.equal(weekKeys[6], "2026-12-06");
|
||||
|
||||
const schedules = [
|
||||
{
|
||||
id: 1,
|
||||
name: "Nightly cross-midnight",
|
||||
enabled: true,
|
||||
timezone_mode: "beijing",
|
||||
schedule_type: "weekly",
|
||||
weekdays: [1], // Monday
|
||||
start_time: "22:00:00",
|
||||
end_time: "02:00:00",
|
||||
start_immediately: false,
|
||||
status: "waiting",
|
||||
task_ids: [10],
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
name: "Open continuous",
|
||||
enabled: true,
|
||||
timezone_mode: "beijing",
|
||||
schedule_type: "weekly",
|
||||
weekdays: [3], // Wednesday
|
||||
start_time: "09:00:00",
|
||||
end_time: "",
|
||||
start_immediately: false,
|
||||
status: "running",
|
||||
task_ids: [11],
|
||||
},
|
||||
];
|
||||
|
||||
const occs = expandSchedulesForDateKeys(schedules, weekKeys, 480, 480);
|
||||
const seg1 = occs.filter((o) => o.scheduleId === 1);
|
||||
assert.equal(seg1.length, 2);
|
||||
assert.equal(seg1[0].dateKey, "2026-11-30");
|
||||
assert.equal(seg1[0].startMin, 22 * 60);
|
||||
assert.equal(seg1[0].endMin, 24 * 60);
|
||||
assert.equal(seg1[1].dateKey, "2026-12-01");
|
||||
assert.equal(seg1[1].startMin, 0);
|
||||
assert.equal(seg1[1].endMin, 2 * 60);
|
||||
|
||||
const openOcc = occs.filter((o) => o.scheduleId === 2);
|
||||
assert.equal(openOcc.length, 1);
|
||||
assert.equal(openOcc[0].allDay, true);
|
||||
assert.equal(openOcc[0].dateKey, "2026-12-02");
|
||||
});
|
||||
|
||||
test("overlap layout and drag/resize schedule update preserve timezone and weekday", () => {
|
||||
const baseSchedule = {
|
||||
id: 7,
|
||||
name: "Design crit",
|
||||
enabled: true,
|
||||
timezone_mode: "beijing",
|
||||
schedule_type: "weekly",
|
||||
weekdays: [3],
|
||||
start_time: "16:00:00",
|
||||
end_time: "17:00:00",
|
||||
start_immediately: false,
|
||||
status: "waiting",
|
||||
proxy_mode: "pool",
|
||||
task_ids: [5],
|
||||
};
|
||||
const occs = expandSchedulesForDateKeys(
|
||||
[
|
||||
baseSchedule,
|
||||
{ ...baseSchedule, id: 8, name: "Overlap", start_time: "16:30:00", end_time: "17:30:00" },
|
||||
],
|
||||
["2026-12-02"],
|
||||
480,
|
||||
480,
|
||||
);
|
||||
const laid = layoutDayTimedEvents(occs);
|
||||
assert.equal(laid.length, 2);
|
||||
assert.equal(laid[0].colCount, 2);
|
||||
assert.notEqual(laid[0].col, laid[1].col);
|
||||
|
||||
// Resize from 16:00-17:00 to 16:00-17:45 and move to Thursday 2026-12-03
|
||||
const updated = buildScheduleInputFromDrag(occs[0], "2026-12-03", 16 * 60, 17 * 60 + 45, 480, 480);
|
||||
assert.equal(updated.start_time, "16:00");
|
||||
assert.equal(updated.end_time, "17:45");
|
||||
assert.deepEqual(updated.weekdays, [4]);
|
||||
assert.equal(updated.proxy_mode, "pool");
|
||||
});
|
||||
@@ -0,0 +1,398 @@
|
||||
import type { ScheduleInput } from "./api";
|
||||
import type { TaskSchedule } from "./types";
|
||||
|
||||
export type CalendarViewMode = "day" | "week" | "month" | "list";
|
||||
export type CalendarClockMode = "server" | "beijing" | "local";
|
||||
|
||||
export interface ZonedDateParts {
|
||||
year: number;
|
||||
month: number; // 1..12
|
||||
day: number; // 1..31
|
||||
weekday: number; // 1=Mon .. 7=Sun
|
||||
hour: number; // 0..23
|
||||
minute: number; // 0..59
|
||||
dateKey: string; // YYYY-MM-DD
|
||||
}
|
||||
|
||||
export interface CalendarEventOccurrence {
|
||||
id: string;
|
||||
scheduleId: number;
|
||||
schedule: TaskSchedule;
|
||||
dateKey: string; // YYYY-MM-DD in displayed timezone
|
||||
startMin: number; // 0..1440
|
||||
endMin: number; // 0..1440
|
||||
allDay: boolean;
|
||||
isContinuedFromPrev?: boolean;
|
||||
isContinuesToNext?: boolean;
|
||||
sourceWeekday?: number; // original weekday (1..7) for weekly drag updates
|
||||
displayTimeRange: string;
|
||||
}
|
||||
|
||||
export interface PositionedCalendarEvent extends CalendarEventOccurrence {
|
||||
col: number;
|
||||
colCount: number;
|
||||
}
|
||||
|
||||
export function pad2(n: number): string {
|
||||
return String(Math.floor(Math.abs(n))).padStart(2, "0");
|
||||
}
|
||||
|
||||
export function makeDateKey(year: number, month: number, day: number): string {
|
||||
return `${year}-${pad2(month)}-${pad2(day)}`;
|
||||
}
|
||||
|
||||
export function parseDateKey(dateKey: string): { year: number; month: number; day: number } | null {
|
||||
const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(dateKey.trim());
|
||||
if (!m) return null;
|
||||
return { year: Number(m[1]), month: Number(m[2]), day: Number(m[3]) };
|
||||
}
|
||||
|
||||
export function addDaysToDateKey(dateKey: string, deltaDays: number): string {
|
||||
const p = parseDateKey(dateKey);
|
||||
if (!p) return dateKey;
|
||||
const d = new Date(Date.UTC(p.year, p.month - 1, p.day + deltaDays));
|
||||
return makeDateKey(d.getUTCFullYear(), d.getUTCMonth() + 1, d.getUTCDate());
|
||||
}
|
||||
|
||||
export function weekdayOfDateKey(dateKey: string): number {
|
||||
const p = parseDateKey(dateKey);
|
||||
if (!p) return 1;
|
||||
const day = new Date(Date.UTC(p.year, p.month - 1, p.day)).getUTCDay();
|
||||
return day === 0 ? 7 : day;
|
||||
}
|
||||
|
||||
export function toZonedParts(utcMs: number, offsetMinutes: number): ZonedDateParts {
|
||||
const d = new Date(utcMs + offsetMinutes * 60_000);
|
||||
const year = d.getUTCFullYear();
|
||||
const month = d.getUTCMonth() + 1;
|
||||
const day = d.getUTCDate();
|
||||
const rawWd = d.getUTCDay();
|
||||
const weekday = rawWd === 0 ? 7 : rawWd;
|
||||
const hour = d.getUTCHours();
|
||||
const minute = d.getUTCMinutes();
|
||||
return {
|
||||
year,
|
||||
month,
|
||||
day,
|
||||
weekday,
|
||||
hour,
|
||||
minute,
|
||||
dateKey: makeDateKey(year, month, day),
|
||||
};
|
||||
}
|
||||
|
||||
export function formatGMTOffset(offsetMinutes: number): string {
|
||||
if (offsetMinutes === 0) return "UTC";
|
||||
const sign = offsetMinutes > 0 ? "+" : "-";
|
||||
const abs = Math.abs(offsetMinutes);
|
||||
const h = Math.floor(abs / 60);
|
||||
const m = abs % 60;
|
||||
return m === 0 ? `GMT${sign}${h}` : `GMT${sign}${h}:${pad2(m)}`;
|
||||
}
|
||||
|
||||
export function resolveDisplayOffsetMinutes(
|
||||
clockMode: CalendarClockMode,
|
||||
serverOffsetMinutes: number | null,
|
||||
): number {
|
||||
const localOffset = -new Date().getTimezoneOffset();
|
||||
if (clockMode === "beijing") return 480;
|
||||
if (clockMode === "local") return localOffset;
|
||||
return serverOffsetMinutes ?? localOffset;
|
||||
}
|
||||
|
||||
export function parseClockMinutes(clock?: string): number | null {
|
||||
if (!clock) return null;
|
||||
const trimmed = clock.trim();
|
||||
if (trimmed === "24:00" || trimmed === "24:00:00") return 1440;
|
||||
const m = /^(\d{1,2}):(\d{2})/.exec(trimmed);
|
||||
if (!m) return null;
|
||||
const h = Number(m[1]);
|
||||
const min = Number(m[2]);
|
||||
if (Number.isNaN(h) || Number.isNaN(min) || h < 0 || h > 24 || min < 0 || min > 59) return null;
|
||||
return Math.min(1440, h * 60 + min);
|
||||
}
|
||||
|
||||
export function formatMinutesAsClock(totalMinutes: number): string {
|
||||
const clamped = Math.max(0, Math.min(1440, Math.round(totalMinutes)));
|
||||
if (clamped === 1440) return "24:00";
|
||||
const h = Math.floor(clamped / 60);
|
||||
const m = clamped % 60;
|
||||
return `${pad2(h)}:${pad2(m)}`;
|
||||
}
|
||||
|
||||
export function startOfWeekDateKey(dateKey: string): string {
|
||||
const wd = weekdayOfDateKey(dateKey);
|
||||
return addDaysToDateKey(dateKey, -(wd - 1));
|
||||
}
|
||||
|
||||
export function buildWeekDateKeys(anchorDateKey: string): string[] {
|
||||
const monday = startOfWeekDateKey(anchorDateKey);
|
||||
return Array.from({ length: 7 }, (_, i) => addDaysToDateKey(monday, i));
|
||||
}
|
||||
|
||||
export function buildMonthGridDateKeys(year: number, month: number): string[] {
|
||||
const firstOfMonth = makeDateKey(year, month, 1);
|
||||
const firstMonday = startOfWeekDateKey(firstOfMonth);
|
||||
return Array.from({ length: 42 }, (_, i) => addDaysToDateKey(firstMonday, i));
|
||||
}
|
||||
|
||||
function scheduleOwnOffsetMinutes(item: TaskSchedule, serverOffsetMinutes: number): number {
|
||||
if (item.timezone_mode === "beijing") return 480;
|
||||
return serverOffsetMinutes;
|
||||
}
|
||||
|
||||
function emitShiftedTimedInterval(
|
||||
out: CalendarEventOccurrence[],
|
||||
schedule: TaskSchedule,
|
||||
baseDateKey: string,
|
||||
startMinInScheduleTZ: number,
|
||||
endMinInScheduleTZ: number, // may exceed 1440 for cross-midnight
|
||||
shiftMinutes: number,
|
||||
visibleSet: Set<string>,
|
||||
sourceWeekday?: number,
|
||||
) {
|
||||
const absStart = startMinInScheduleTZ + shiftMinutes;
|
||||
const absEnd = endMinInScheduleTZ + shiftMinutes;
|
||||
const startDayShift = Math.floor(absStart / 1440);
|
||||
const endDayShift = Math.floor((absEnd - 1) / 1440);
|
||||
|
||||
const labelStart = formatMinutesAsClock(((absStart % 1440) + 1440) % 1440);
|
||||
const rawEndMod = ((absEnd % 1440) + 1440) % 1440;
|
||||
const labelEnd = rawEndMod === 0 ? "24:00" : formatMinutesAsClock(rawEndMod);
|
||||
const displayTimeRange = `${labelStart} - ${labelEnd}`;
|
||||
|
||||
for (let dShift = startDayShift; dShift <= endDayShift; dShift++) {
|
||||
const dk = addDaysToDateKey(baseDateKey, dShift);
|
||||
if (!visibleSet.has(dk)) continue;
|
||||
const segStart = Math.max(dShift * 1440, absStart) - dShift * 1440;
|
||||
const segEnd = Math.min((dShift + 1) * 1440, absEnd) - dShift * 1440;
|
||||
if (segEnd <= segStart) continue;
|
||||
out.push({
|
||||
id: `${schedule.id}:${dk}:${segStart}:${segEnd}`,
|
||||
scheduleId: schedule.id,
|
||||
schedule,
|
||||
dateKey: dk,
|
||||
startMin: segStart,
|
||||
endMin: segEnd,
|
||||
allDay: false,
|
||||
isContinuedFromPrev: dShift > startDayShift,
|
||||
isContinuesToNext: dShift < endDayShift,
|
||||
sourceWeekday,
|
||||
displayTimeRange,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Expands TaskSchedule rules (weekly / once / cross-midnight / open-ended) into
|
||||
* concrete occurrences for the requested visible date keys in the chosen display timezone.
|
||||
*/
|
||||
export function expandSchedulesForDateKeys(
|
||||
schedules: TaskSchedule[],
|
||||
visibleDateKeys: string[],
|
||||
displayOffsetMinutes: number,
|
||||
serverOffsetMinutes: number,
|
||||
): CalendarEventOccurrence[] {
|
||||
if (!visibleDateKeys.length || !schedules.length) return [];
|
||||
const visibleSet = new Set(visibleDateKeys);
|
||||
const sorted = [...visibleDateKeys].sort();
|
||||
const minDate = addDaysToDateKey(sorted[0], -1);
|
||||
const maxDate = addDaysToDateKey(sorted[sorted.length - 1], 1);
|
||||
|
||||
const scanDays: string[] = [];
|
||||
let cur = minDate;
|
||||
for (let guard = 0; guard < 60 && cur <= maxDate; guard++) {
|
||||
scanDays.push(cur);
|
||||
cur = addDaysToDateKey(cur, 1);
|
||||
}
|
||||
|
||||
const out: CalendarEventOccurrence[] = [];
|
||||
for (const item of schedules) {
|
||||
const startMin = parseClockMinutes(item.start_time) ?? 0;
|
||||
const endMin = parseClockMinutes(item.end_time);
|
||||
const ownOffset = scheduleOwnOffsetMinutes(item, serverOffsetMinutes);
|
||||
const shiftMin = displayOffsetMinutes - ownOffset;
|
||||
|
||||
if (item.schedule_type === "weekly") {
|
||||
const wdSet = new Set(item.weekdays ?? []);
|
||||
if (wdSet.size === 0) continue;
|
||||
for (const dk of scanDays) {
|
||||
const wd = weekdayOfDateKey(dk);
|
||||
if (!wdSet.has(wd)) continue;
|
||||
if (endMin === null) {
|
||||
// Open-ended continuous schedule -> render in All day strip on each scheduled weekday.
|
||||
const shiftedStart = startMin + shiftMin;
|
||||
const dayShift = Math.floor(shiftedStart / 1440);
|
||||
const targetDK = addDaysToDateKey(dk, dayShift);
|
||||
if (!visibleSet.has(targetDK)) continue;
|
||||
const clock = formatMinutesAsClock(((shiftedStart % 1440) + 1440) % 1440);
|
||||
out.push({
|
||||
id: `${item.id}:${targetDK}:allday`,
|
||||
scheduleId: item.id,
|
||||
schedule: item,
|
||||
dateKey: targetDK,
|
||||
startMin: 0,
|
||||
endMin: 1440,
|
||||
allDay: true,
|
||||
sourceWeekday: wd,
|
||||
displayTimeRange: `${clock} →`,
|
||||
});
|
||||
} else {
|
||||
const effEnd = endMin <= startMin ? endMin + 1440 : endMin;
|
||||
emitShiftedTimedInterval(out, item, dk, startMin, effEnd, shiftMin, visibleSet, wd);
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
// schedule_type === "once"
|
||||
if (!item.run_date) continue;
|
||||
if (item.end_date && item.end_date > item.run_date) {
|
||||
// Multi-day once schedule -> render in All day strip across run_date..end_date.
|
||||
let d = item.run_date;
|
||||
for (let guard = 0; guard < 120 && d <= item.end_date; guard++) {
|
||||
if (visibleSet.has(d)) {
|
||||
const startClock = formatMinutesAsClock(startMin);
|
||||
const endClock = endMin !== null ? formatMinutesAsClock(endMin) : "24:00";
|
||||
out.push({
|
||||
id: `${item.id}:${d}:multiday`,
|
||||
scheduleId: item.id,
|
||||
schedule: item,
|
||||
dateKey: d,
|
||||
startMin: 0,
|
||||
endMin: 1440,
|
||||
allDay: true,
|
||||
isContinuedFromPrev: d > item.run_date,
|
||||
isContinuesToNext: d < item.end_date,
|
||||
displayTimeRange: `${startClock} - ${endClock}`,
|
||||
});
|
||||
}
|
||||
d = addDaysToDateKey(d, 1);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (endMin === null) {
|
||||
const shiftedStart = startMin + shiftMin;
|
||||
const dayShift = Math.floor(shiftedStart / 1440);
|
||||
const targetDK = addDaysToDateKey(item.run_date, dayShift);
|
||||
if (visibleSet.has(targetDK)) {
|
||||
const clock = formatMinutesAsClock(((shiftedStart % 1440) + 1440) % 1440);
|
||||
out.push({
|
||||
id: `${item.id}:${targetDK}:once-open`,
|
||||
scheduleId: item.id,
|
||||
schedule: item,
|
||||
dateKey: targetDK,
|
||||
startMin: 0,
|
||||
endMin: 1440,
|
||||
allDay: true,
|
||||
displayTimeRange: `${clock} →`,
|
||||
});
|
||||
}
|
||||
} else {
|
||||
const effEnd = endMin <= startMin ? endMin + 1440 : endMin;
|
||||
emitShiftedTimedInterval(out, item, item.run_date, startMin, effEnd, shiftMin, visibleSet);
|
||||
}
|
||||
}
|
||||
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Assigns side-by-side column indices for overlapping timed events within a single day.
|
||||
*/
|
||||
export function layoutDayTimedEvents(events: CalendarEventOccurrence[]): PositionedCalendarEvent[] {
|
||||
const timed = events
|
||||
.filter((e) => !e.allDay)
|
||||
.sort((a, b) => a.startMin - b.startMin || b.endMin - a.endMin || a.scheduleId - b.scheduleId);
|
||||
if (timed.length === 0) return [];
|
||||
|
||||
// Group into connected overlap clusters so column counts stay local.
|
||||
const clusters: CalendarEventOccurrence[][] = [];
|
||||
let currentCluster: CalendarEventOccurrence[] = [];
|
||||
let clusterEnd = -1;
|
||||
for (const ev of timed) {
|
||||
if (currentCluster.length === 0 || ev.startMin < clusterEnd) {
|
||||
currentCluster.push(ev);
|
||||
clusterEnd = Math.max(clusterEnd, ev.endMin);
|
||||
} else {
|
||||
clusters.push(currentCluster);
|
||||
currentCluster = [ev];
|
||||
clusterEnd = ev.endMin;
|
||||
}
|
||||
}
|
||||
if (currentCluster.length > 0) clusters.push(currentCluster);
|
||||
|
||||
const result: PositionedCalendarEvent[] = [];
|
||||
for (const cluster of clusters) {
|
||||
const colEnds: number[] = [];
|
||||
const placed: Array<{ ev: CalendarEventOccurrence; col: number }> = [];
|
||||
for (const ev of cluster) {
|
||||
let col = colEnds.findIndex((end) => end <= ev.startMin);
|
||||
if (col === -1) {
|
||||
col = colEnds.length;
|
||||
colEnds.push(ev.endMin);
|
||||
} else {
|
||||
colEnds[col] = ev.endMin;
|
||||
}
|
||||
placed.push({ ev, col });
|
||||
}
|
||||
const colCount = Math.max(1, colEnds.length);
|
||||
for (const p of placed) {
|
||||
result.push({ ...p.ev, col: p.col, colCount });
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds an updated ScheduleInput after dragging/resizing a timed occurrence in the UI.
|
||||
*/
|
||||
export function buildScheduleInputFromDrag(
|
||||
occurrence: CalendarEventOccurrence,
|
||||
newDateKey: string,
|
||||
newStartMinInDisplayTZ: number,
|
||||
newEndMinInDisplayTZ: number,
|
||||
displayOffsetMinutes: number,
|
||||
serverOffsetMinutes: number,
|
||||
): ScheduleInput {
|
||||
const item = occurrence.schedule;
|
||||
const ownOffset = scheduleOwnOffsetMinutes(item, serverOffsetMinutes);
|
||||
const reverseShift = ownOffset - displayOffsetMinutes;
|
||||
|
||||
const clampedStart = Math.max(0, Math.min(1425, Math.round(newStartMinInDisplayTZ / 15) * 15));
|
||||
const clampedEnd = Math.max(clampedStart + 15, Math.min(1440, Math.round(newEndMinInDisplayTZ / 15) * 15));
|
||||
|
||||
const ownStartAbs = clampedStart + reverseShift;
|
||||
const ownEndAbs = clampedEnd + reverseShift;
|
||||
const dayShift = Math.floor(ownStartAbs / 1440);
|
||||
const ownStartMod = ((ownStartAbs % 1440) + 1440) % 1440;
|
||||
const ownEndRel = ownEndAbs - dayShift * 1440;
|
||||
const ownEndClock = ownEndRel === 1440 ? "24:00" : formatMinutesAsClock(((ownEndRel % 1440) + 1440) % 1440);
|
||||
const targetDateKey = addDaysToDateKey(newDateKey, dayShift);
|
||||
|
||||
let weekdays = [...(item.weekdays ?? [])];
|
||||
if (item.schedule_type === "weekly" && newDateKey !== occurrence.dateKey && occurrence.sourceWeekday) {
|
||||
const newWd = weekdayOfDateKey(targetDateKey);
|
||||
const filtered = weekdays.filter((w) => w !== occurrence.sourceWeekday);
|
||||
if (!filtered.includes(newWd)) filtered.push(newWd);
|
||||
weekdays = filtered.sort((a, b) => a - b);
|
||||
}
|
||||
|
||||
return {
|
||||
name: item.name,
|
||||
enabled: item.enabled,
|
||||
timezone_mode: item.timezone_mode,
|
||||
schedule_type: item.schedule_type,
|
||||
run_date: item.schedule_type === "once" ? targetDateKey : item.run_date,
|
||||
end_date: item.schedule_type === "once" ? "" : item.end_date,
|
||||
weekdays: item.schedule_type === "weekly" ? weekdays : [],
|
||||
start_time: formatMinutesAsClock(ownStartMod),
|
||||
end_time: ownEndClock,
|
||||
start_immediately: item.start_immediately,
|
||||
proxy_mode: item.proxy_mode ?? "inherit",
|
||||
proxy_pool_id: item.proxy_pool_id ?? "",
|
||||
proxy_url: item.proxy_url ?? "",
|
||||
task_ids: item.task_ids,
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user