diff --git a/server/orchestration.go b/server/orchestration.go index 53e82a4..ca22838 100644 --- a/server/orchestration.go +++ b/server/orchestration.go @@ -85,6 +85,10 @@ func (s *Server) orchestrationTools() []actool.CoreTool { s.toolBindFindingTraffic(), s.toolListProxyPool(), s.toolSetTaskProxy(), + s.toolListTaskSchedules(), + s.toolCreateTaskSchedule(), + s.toolUpdateTaskSchedule(), + s.toolDeleteTaskSchedule(), }, s.findingCaseTools()...) } @@ -668,7 +672,9 @@ func defaultOrchestrationToolBindings(name string) json.RawMessage { switch { case name == "resume_task": return json.RawMessage(`["auto","mainagent"]`) - case name == "list_proxy_pool" || name == "set_task_proxy": + case name == "list_proxy_pool" || name == "set_task_proxy" || + name == "list_task_schedules" || name == "create_task_schedule" || + name == "update_task_schedule" || name == "delete_task_schedule": return json.RawMessage(`["auto","mainagent","pentest"]`) case name == "bind_finding_traffic" || strings.Contains(name, "finding_case") || name == "search_finding_duplicates" || name == "get_finding_record" || name == "merge_finding_records": return json.RawMessage(`["reporter"]`) @@ -693,6 +699,7 @@ func (s *Server) seedOrchestrationTools() { s.seedAutoDefaultBindings() s.seedTaskReopenBindings() s.seedProxyToolBindings() + s.seedScheduleToolBindings() s.seedPlannerDefaultBindings() s.seedPlannerListAssetsBinding() s.seedCompanyScopeRebind() @@ -784,7 +791,7 @@ func (s *Server) migrateReporterWorkflow() { // reaches an old DB otherwise. Preserves each tool's agent binding + enabled flag. // Bump the flag whenever these tools' schemas/descriptions change in code. func (s *Server) refreshBuiltinToolSchemas() { - const flag = "tool_schema_refresh_v10_proxy_tools" + const flag = "tool_schema_refresh_v11_schedule_tools" if v, _, _ := s.m.pg.GetSetting(flag); v == "true" { return } diff --git a/server/schedule_tools.go b/server/schedule_tools.go new file mode 100644 index 0000000..836618a --- /dev/null +++ b/server/schedule_tools.go @@ -0,0 +1,343 @@ +package server + +import ( + "context" + "encoding/json" + "fmt" + "log" + "strconv" + "strings" + "time" + actool "github.com/Autumn-27/norma/tool" +) + +func parseInt64Flexible(raw json.RawMessage) (int64, bool) { + if len(raw) == 0 { + return 0, false + } + var n int64 + if json.Unmarshal(raw, &n) == nil && n > 0 { + return n, true + } + var s string + if json.Unmarshal(raw, &s) == nil { + s = strings.TrimSpace(strings.TrimPrefix(strings.TrimSpace(s), "#")) + if v, err := strconv.ParseInt(s, 10, 64); err == nil && v > 0 { + return v, true + } + } + return 0, false +} + +func parseInt64SliceFlexible(raws []json.RawMessage) ([]int64, error) { + out := make([]int64, 0, len(raws)) + seen := map[int64]bool{} + for _, r := range raws { + id, ok := parseInt64Flexible(r) + if !ok { + return nil, fmt.Errorf("无效的任务 ID: %s", string(r)) + } + if !seen[id] { + seen[id] = true + out = append(out, id) + } + } + return out, nil +} + +func serverClockMeta(now time.Time) (string, string, int) { + _, offsetSec := now.Zone() + return now.Format(time.RFC3339), time.Local.String(), offsetSec / 60 +} + +func (s *Server) toolListTaskSchedules() actool.CoreTool { + return roTool("list_task_schedules", + "查看所有定时日历计划任务(包含当前服务器时间与时区、规则类型、起止时间、关联任务、代理配置、状态与下次触发时间)。", + objSchema(map[string]any{}), + func(context.Context, json.RawMessage) (actool.Result, error) { + if s.m.pg == nil { + return actool.Errorf("数据库未初始化"), nil + } + items, err := s.m.pg.ListTaskSchedules() + if err != nil { + return actool.Errorf("查询计划任务失败: " + err.Error()), nil + } + dtos := make([]map[string]any, 0, len(items)) + for _, item := range items { + dtos = append(dtos, s.scheduleDTO(item)) + } + srvTime, srvTZ, srvOffset := serverClockMeta(time.Now()) + return jsonResult(map[string]any{ + "server_time": srvTime, + "server_timezone": srvTZ, + "server_utc_offset_minutes": srvOffset, + "schedules": dtos, + }) + }) +} + +func (s *Server) toolCreateTaskSchedule() actool.CoreTool { + return wrTool("create_task_schedule", + "创建一个定时日历计划任务,按指定日历时间窗口自动控制一个或多个任务的运行与暂停(并可选绑定出口代理/代理池)。\n"+ + "- schedule_type=weekly:按周重复,weekdays 填 1-7(1=周一…7=周日),start_time 必填(HH:MM),end_time 可选(留空表示开始后持续运行;早于 start_time 表示跨午夜到次日)。\n"+ + "- schedule_type=once:一次性或跨多天区间,run_date 必填(YYYY-MM-DD),end_date 可选(YYYY-MM-DD),start_time 必填,end_time 可选。\n"+ + "- 创建前可先用 list_task_schedules 查看当前 server_time,或用 list_tasks 查看任务 ID。", + objSchema(map[string]any{ + "name": strParam("计划名称(必填)"), + "schedule_type": map[string]any{"type": "string", "enum": []string{"once", "weekly"}, "description": "规则类型:once=一次性,weekly=按周重复"}, + "start_time": strParam("开始时间,格式 HH:MM(如 18:00)"), + "end_time": strParam("结束时间,格式 HH:MM(可选;留空=持续运行,小于 start_time=次日结束)"), + "run_date": strParam("开始日期 YYYY-MM-DD(schedule_type=once 时必填)"), + "end_date": strParam("结束日期 YYYY-MM-DD(可选,仅 schedule_type=once 跨多天时使用)"), + "weekdays": map[string]any{"type": "array", "items": map[string]any{"type": "integer"}, "description": "按周重复的星期列表 1-7(1=周一…7=周日;schedule_type=weekly 时必填)"}, + "timezone_mode": map[string]any{"type": "string", "enum": []string{"beijing", "system"}, "description": "时区模式:beijing=北京时间(默认),system=服务器当前时区"}, + "enabled": map[string]any{"type": "boolean", "description": "是否启用,默认 true"}, + "start_immediately": map[string]any{"type": "boolean", "description": "保存后是否立即运行关联任务,默认 false"}, + "task_ids": map[string]any{"type": "array", "items": map[string]any{"type": "string"}, "description": "关联的任务 ID 列表(可传数字或字符串)"}, + "proxy_mode": map[string]any{"type": "string", "enum": []string{"inherit", "direct", "pool", "proxy"}, "description": "可选:计划触发时应用到关联任务的代理模式"}, + "proxy_pool_id": strParam("可选(proxy_mode=proxy 时):代理池节点 ID 或名称"), + "proxy_url": strParam("可选(proxy_mode=proxy 且未指定 proxy_pool_id 时):自定义代理 URL"), + }, "name", "schedule_type", "start_time"), + func(_ context.Context, in json.RawMessage) (actool.Result, error) { + if s.m.pg == nil { + return actool.Errorf("数据库未初始化"), nil + } + var a struct { + Name string `json:"name"` + Enabled *bool `json:"enabled"` + TimezoneMode string `json:"timezone_mode"` + ScheduleType string `json:"schedule_type"` + RunDate string `json:"run_date"` + EndDate string `json:"end_date"` + Weekdays []int `json:"weekdays"` + StartTime string `json:"start_time"` + EndTime string `json:"end_time"` + StartImmediately bool `json:"start_immediately"` + TaskIDs []json.RawMessage `json:"task_ids"` + ProxyMode string `json:"proxy_mode"` + ProxyPoolID string `json:"proxy_pool_id"` + ProxyURL string `json:"proxy_url"` + } + if err := json.Unmarshal(in, &a); err != nil { + return actool.Errorf("参数无效: " + err.Error()), nil + } + taskIDs, err := parseInt64SliceFlexible(a.TaskIDs) + if err != nil { + return actool.Errorf(err.Error()), nil + } + enabled := true + if a.Enabled != nil { + enabled = *a.Enabled + } + req := scheduleRequest{ + Name: a.Name, + Enabled: &enabled, + TimezoneMode: a.TimezoneMode, + ScheduleType: a.ScheduleType, + RunDate: a.RunDate, + EndDate: a.EndDate, + Weekdays: a.Weekdays, + StartTime: a.StartTime, + EndTime: a.EndTime, + StartImmediately: a.StartImmediately, + ProxyMode: a.ProxyMode, + ProxyPoolID: a.ProxyPoolID, + ProxyURL: a.ProxyURL, + TaskIDs: taskIDs, + } + input := s.scheduleInput(req, nil) + if err := s.validateScheduleProxy(&input, nil); err != nil { + return actool.Errorf("代理配置无效: " + err.Error()), nil + } + item, err := s.m.pg.CreateTaskSchedule(input) + if err != nil { + return actool.Errorf("创建计划任务失败: " + err.Error()), nil + } + s.applyScheduleProxyToTasks(item) + if req.StartImmediately && item.Enabled { + s.runScheduleTasks(item) + } + return jsonResult(s.scheduleDTO(item)) + }) +} + +func (s *Server) toolUpdateTaskSchedule() actool.CoreTool { + return wrTool("update_task_schedule", + "修改已有定时日历计划任务(仅需传要变更的字段,未传字段保持原值)。可修改时间窗、星期、关联任务、启停状态或代理/代理池配置。", + objSchema(map[string]any{ + "schedule_id": strParam("要修改的计划任务 ID(必填)"), + "name": strParam("可选:新名称"), + "enabled": map[string]any{"type": "boolean", "description": "可选:启用或暂停该计划"}, + "schedule_type": map[string]any{"type": "string", "enum": []string{"once", "weekly"}, "description": "可选:规则类型"}, + "timezone_mode": map[string]any{"type": "string", "enum": []string{"beijing", "system"}, "description": "可选:时区模式"}, + "run_date": strParam("可选:开始日期 YYYY-MM-DD"), + "end_date": strParam("可选:结束日期 YYYY-MM-DD(传空字符串清除)"), + "weekdays": map[string]any{"type": "array", "items": map[string]any{"type": "integer"}, "description": "可选:星期列表 1-7"}, + "start_time": strParam("可选:开始时间 HH:MM"), + "end_time": strParam("可选:结束时间 HH:MM(传空字符串表示持续运行)"), + "start_immediately": map[string]any{"type": "boolean", "description": "可选:是否立即运行"}, + "task_ids": map[string]any{"type": "array", "items": map[string]any{"type": "string"}, "description": "可选:替换关联任务 ID 列表"}, + "proxy_mode": map[string]any{"type": "string", "enum": []string{"inherit", "direct", "pool", "proxy"}, "description": "可选:代理模式"}, + "proxy_pool_id": strParam("可选:代理池节点 ID 或名称"), + "proxy_url": strParam("可选:自定义代理 URL"), + }, "schedule_id"), + func(_ context.Context, in json.RawMessage) (actool.Result, error) { + if s.m.pg == nil { + return actool.Errorf("数据库未初始化"), nil + } + var a struct { + ScheduleID json.RawMessage `json:"schedule_id"` + Name *string `json:"name"` + Enabled *bool `json:"enabled"` + TimezoneMode *string `json:"timezone_mode"` + ScheduleType *string `json:"schedule_type"` + RunDate *string `json:"run_date"` + EndDate *string `json:"end_date"` + Weekdays *[]int `json:"weekdays"` + StartTime *string `json:"start_time"` + EndTime *string `json:"end_time"` + StartImmediately *bool `json:"start_immediately"` + TaskIDs *[]json.RawMessage `json:"task_ids"` + ProxyMode *string `json:"proxy_mode"` + ProxyPoolID *string `json:"proxy_pool_id"` + ProxyURL *string `json:"proxy_url"` + } + if err := json.Unmarshal(in, &a); err != nil { + return actool.Errorf("参数无效: " + err.Error()), nil + } + id, ok := parseInt64Flexible(a.ScheduleID) + if !ok { + return actool.Errorf("schedule_id 无效"), nil + } + old, err := s.m.pg.GetTaskSchedule(id) + if err != nil { + return actool.Errorf(fmt.Sprintf("计划任务 #%d 不存在", id)), nil + } + trimClock := func(v string) string { + if len(v) >= 5 { + return v[:5] + } + return v + } + req := scheduleRequest{ + Name: old.Name, + Enabled: &old.Enabled, + TimezoneMode: old.TimezoneMode, + ScheduleType: old.ScheduleType, + RunDate: old.RunDate, + EndDate: old.EndDate, + Weekdays: old.Weekdays, + StartTime: trimClock(old.StartTime), + EndTime: trimClock(old.EndTime), + StartImmediately: old.StartImmediately, + ProxyMode: old.ProxyMode, + ProxyPoolID: old.ProxyPoolID, + ProxyURL: old.ProxyURL, + TaskIDs: old.TaskIDs, + } + if a.Name != nil { + req.Name = *a.Name + } + if a.Enabled != nil { + req.Enabled = a.Enabled + } + if a.TimezoneMode != nil { + req.TimezoneMode = *a.TimezoneMode + } + if a.ScheduleType != nil { + req.ScheduleType = *a.ScheduleType + } + if a.RunDate != nil { + req.RunDate = *a.RunDate + } + if a.EndDate != nil { + req.EndDate = *a.EndDate + } + if a.Weekdays != nil { + req.Weekdays = *a.Weekdays + } + if a.StartTime != nil { + req.StartTime = *a.StartTime + } + if a.EndTime != nil { + req.EndTime = *a.EndTime + } + if a.StartImmediately != nil { + req.StartImmediately = *a.StartImmediately + } + if a.TaskIDs != nil { + ids, perr := parseInt64SliceFlexible(*a.TaskIDs) + if perr != nil { + return actool.Errorf(perr.Error()), nil + } + req.TaskIDs = ids + } + if a.ProxyMode != nil { + req.ProxyMode = *a.ProxyMode + } + if a.ProxyPoolID != nil { + req.ProxyPoolID = *a.ProxyPoolID + } + if a.ProxyURL != nil { + req.ProxyURL = *a.ProxyURL + } + + input := s.scheduleInput(req, old) + if err := s.validateScheduleProxy(&input, old); err != nil { + return actool.Errorf("代理配置无效: " + err.Error()), nil + } + item, err := s.m.pg.UpdateTaskSchedule(id, input) + if err != nil { + return actool.Errorf("更新计划任务失败: " + err.Error()), nil + } + s.applyScheduleProxyToTasks(item) + return jsonResult(s.scheduleDTO(item)) + }) +} + +func (s *Server) toolDeleteTaskSchedule() actool.CoreTool { + return wrTool("delete_task_schedule", + "删除指定的定时日历计划任务(不会删除其关联的任务本身)。", + objSchema(map[string]any{ + "schedule_id": strParam("要删除的计划任务 ID(必填)"), + }, "schedule_id"), + func(_ context.Context, in json.RawMessage) (actool.Result, error) { + if s.m.pg == nil { + return actool.Errorf("数据库未初始化"), nil + } + var a struct { + ScheduleID json.RawMessage `json:"schedule_id"` + } + if err := json.Unmarshal(in, &a); err != nil { + return actool.Errorf("参数无效: " + err.Error()), nil + } + id, ok := parseInt64Flexible(a.ScheduleID) + if !ok { + return actool.Errorf("schedule_id 无效"), nil + } + if _, err := s.m.pg.GetTaskSchedule(id); err != nil { + return actool.Errorf(fmt.Sprintf("计划任务 #%d 不存在", id)), nil + } + if err := s.m.pg.DeleteTaskSchedule(id); err != nil { + return actool.Errorf("删除计划任务失败: " + err.Error()), nil + } + return jsonResult(map[string]any{"deleted": true, "schedule_id": id}) + }) +} + +// seedScheduleToolBindings binds calendar schedule tools to chat agents ONCE +// on existing DBs so users can create/manage calendar schedules from chat. +func (s *Server) seedScheduleToolBindings() { + const flag = "schedule_tool_bindings_v1" + if v, _, _ := s.m.pg.GetSetting(flag); v == "true" { + return + } + keys := []string{"list_task_schedules", "create_task_schedule", "update_task_schedule", "delete_task_schedule"} + for _, agentKey := range []string{"auto", "mainagent", "pentest"} { + if err := s.m.pg.AddAgentToToolBinding(agentKey, keys); err != nil { + log.Printf("[%s] 日历计划工具默认绑定失败: %v", agentKey, err) + return + } + } + _ = s.m.pg.SetSetting(flag, "true") +} diff --git a/server/schedule_tools_test.go b/server/schedule_tools_test.go new file mode 100644 index 0000000..641c41e --- /dev/null +++ b/server/schedule_tools_test.go @@ -0,0 +1,125 @@ +package server + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "os" + "strings" + "testing" + + "github.com/Autumn-27/artex/db" +) + +func TestChatScheduleToolsAndServerClock(t *testing.T) { + dsn := strings.TrimSpace(os.Getenv("ARTEX_PG_DSN")) + if dsn == "" { + t.Skip("requires ARTEX_PG_DSN") + } + pg, err := db.Open(dsn) + if err != nil { + t.Fatalf("open pg: %v", err) + } + defer pg.Close() + + m := &Manager{ + pg: pg, + dir: t.TempDir(), + tasks: map[string]*Task{}, + proxyPool: &proxyPoolState{ + active: "pool-1", + entries: []proxyPoolEntry{ + { + ProxyPoolEntry: ProxyPoolEntry{ID: "pool-1", Name: "Node1", URL: "http://127.0.0.1:19801", Enabled: true, Health: "healthy"}, + RawURL: "http://127.0.0.1:19801", + }, + }, + }, + globalProxy: "http://127.0.0.1:19801", + } + s := &Server{m: m} + s.initProxyRoutesAndGateway() + + task, err := m.CreateTask("calendar-chat-task", "test calendar creation from chat", nil, 0, 0) + if err != nil { + t.Fatalf("CreateTask: %v", err) + } + + // 1. Create schedule from chat tool with proxy_mode=pool. + createTool := s.toolCreateTaskSchedule() + in := fmt.Sprintf(`{"name":"工作日夜间扫描","schedule_type":"weekly","weekdays":[1,2,3,4,5],"start_time":"18:00","end_time":"23:00","task_ids":[%q],"proxy_mode":"pool"}`, task.ID) + res, err := createTool.Call(context.Background(), json.RawMessage(in), nil) + if err != nil || res.IsError { + t.Fatalf("create_task_schedule failed: err=%v res=%+v", err, res) + } + text := "" + for _, b := range res.Content { + text += b.Text + } + var created map[string]any + if err := json.Unmarshal([]byte(text), &created); err != nil { + t.Fatalf("decode create_task_schedule: %v (%s)", err, text) + } + schedID := int64(created["id"].(float64)) + if created["proxy_mode"] != "pool" { + t.Fatalf("expected proxy_mode=pool, got %+v", created) + } + + // Verify bound task inherited proxy_mode=pool immediately. + view, _ := s.containerProxyRouteView("task", task.ID) + if view.Mode != "pool" { + t.Fatalf("expected task route mode=pool after create_task_schedule, got %+v", view) + } + + // 2. List schedules via HTTP GET /api/schedules -> verify top-level server_time & offset. + rec := httptest.NewRecorder() + s.listSchedules(rec, httptest.NewRequest(http.MethodGet, "/api/schedules", nil)) + if rec.Code != http.StatusOK { + t.Fatalf("listSchedules: %d %s", rec.Code, rec.Body.String()) + } + var listResp map[string]any + if err := json.Unmarshal(rec.Body.Bytes(), &listResp); err != nil { + t.Fatalf("decode listSchedules: %v", err) + } + if listResp["server_time"] == "" || listResp["server_timezone"] == "" || listResp["server_utc_offset_minutes"] == nil { + t.Fatalf("expected server clock metadata in /api/schedules, got %+v", listResp) + } + + // 3. Update schedule via chat tool (partial update). + updTool := s.toolUpdateTaskSchedule() + updIn := fmt.Sprintf(`{"schedule_id":%d,"end_time":"23:45"}`, schedID) + updRes, err := updTool.Call(context.Background(), json.RawMessage(updIn), nil) + if err != nil || updRes.IsError { + t.Fatalf("update_task_schedule failed: err=%v res=%+v", err, updRes) + } + updText := "" + for _, b := range updRes.Content { + updText += b.Text + } + if !strings.Contains(updText, "23:45") || !strings.Contains(updText, "工作日夜间扫描") { + t.Fatalf("unexpected update_task_schedule output: %s", updText) + } + + // 4. List via chat tool. + listTool := s.toolListTaskSchedules() + listRes, err := listTool.Call(context.Background(), json.RawMessage(`{}`), nil) + if err != nil || listRes.IsError { + t.Fatalf("list_task_schedules failed: err=%v res=%+v", err, listRes) + } + listText := "" + for _, b := range listRes.Content { + listText += b.Text + } + if !strings.Contains(listText, `"server_time"`) || !strings.Contains(listText, "工作日夜间扫描") { + t.Fatalf("unexpected list_task_schedules output: %s", listText) + } + + // 5. Delete via chat tool. + delTool := s.toolDeleteTaskSchedule() + delRes, err := delTool.Call(context.Background(), json.RawMessage(fmt.Sprintf(`{"schedule_id":%d}`, schedID)), nil) + if err != nil || delRes.IsError { + t.Fatalf("delete_task_schedule failed: err=%v res=%+v", err, delRes) + } +} diff --git a/server/schedules.go b/server/schedules.go index 6d749f7..0cee5ea 100644 --- a/server/schedules.go +++ b/server/schedules.go @@ -147,7 +147,13 @@ func (s *Server) listSchedules(w http.ResponseWriter, r *http.Request) { for _, item := range items { dtos = append(dtos, s.scheduleDTO(item)) } - writeJSON(w, 200, map[string]any{"schedules": dtos}) + srvTime, srvTZ, srvOffset := serverClockMeta(time.Now()) + writeJSON(w, 200, map[string]any{ + "schedules": dtos, + "server_time": srvTime, + "server_timezone": srvTZ, + "server_utc_offset_minutes": srvOffset, + }) } func (s *Server) getSchedule(w http.ResponseWriter, r *http.Request) { diff --git a/web/src/app/(main)/function/schedules/_components/schedule-calendar-workspace.tsx b/web/src/app/(main)/function/schedules/_components/schedule-calendar-workspace.tsx new file mode 100644 index 0000000..c7c6c05 --- /dev/null +++ b/web/src/app/(main)/function/schedules/_components/schedule-calendar-workspace.tsx @@ -0,0 +1,1365 @@ +"use client"; + +import * as React from "react"; + +import Link from "next/link"; + +import type { TFunction } from "i18next"; +import { + CalendarIcon, + ChevronLeft, + ChevronRight, + ClockIcon, + CopyIcon, + HistoryIcon, + ListChecksIcon, + Pause, + PencilIcon, + Play, + Plus, + RouteIcon, + Search, + Trash2, + XIcon, + Zap, +} from "lucide-react"; + +import { formatProxyRouteSummary } from "@/components/proxy-route-selector"; +import { Badge } from "@/components/ui/badge"; +import { Button } from "@/components/ui/button"; +import { Checkbox } from "@/components/ui/checkbox"; +import { Input } from "@/components/ui/input"; +import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"; +import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"; +import { useLiveTranslation } from "@/i18n/use-live-translation"; +import type { ScheduleInput } from "@/lib/api"; +import { + addDaysToDateKey, + buildMonthGridDateKeys, + buildScheduleInputFromDrag, + buildWeekDateKeys, + type CalendarClockMode, + type CalendarEventOccurrence, + type CalendarViewMode, + expandSchedulesForDateKeys, + formatGMTOffset, + formatMinutesAsClock, + layoutDayTimedEvents, + makeDateKey, + parseDateKey, + resolveDisplayOffsetMinutes, + toZonedParts, +} from "@/lib/schedule-calendar"; +import { scheduleDisplay } from "@/lib/schedule-display"; +import type { ProxyPoolEntry, Task, TaskSchedule } from "@/lib/types"; +import { cn } from "@/lib/utils"; + +const HOUR_HEIGHT = 56; // px per hour +const ALL_STATUSES: TaskSchedule["status"][] = ["running", "waiting", "outside", "paused", "completed", "error"]; + +const STATUS_STYLE: Record< + TaskSchedule["status"], + { + card: string; + cardSelected: string; + dot: string; + pill: string; + } +> = { + running: { + card: "border-emerald-300/90 bg-emerald-50/90 text-emerald-950 hover:bg-emerald-100/90 dark:border-emerald-800 dark:bg-emerald-950/60 dark:text-emerald-100 dark:hover:bg-emerald-900/60", + cardSelected: "ring-2 ring-emerald-500/70 bg-emerald-100 dark:bg-emerald-900/80", + dot: "bg-emerald-500", + pill: "border-emerald-200 bg-emerald-50 text-emerald-700 dark:border-emerald-800 dark:bg-emerald-950/50 dark:text-emerald-300", + }, + waiting: { + card: "border-blue-300/90 bg-blue-50/90 text-blue-950 hover:bg-blue-100/90 dark:border-blue-800 dark:bg-blue-950/60 dark:text-blue-100 dark:hover:bg-blue-900/60", + cardSelected: "ring-2 ring-blue-500/70 bg-blue-100 dark:bg-blue-900/80", + dot: "bg-blue-500", + pill: "border-blue-200 bg-blue-50 text-blue-700 dark:border-blue-800 dark:bg-blue-950/50 dark:text-blue-300", + }, + outside: { + card: "border-orange-300/90 bg-orange-50/90 text-orange-950 hover:bg-orange-100/90 dark:border-orange-800 dark:bg-orange-950/60 dark:text-orange-100 dark:hover:bg-orange-900/60", + cardSelected: "ring-2 ring-orange-500/70 bg-orange-100 dark:bg-orange-900/80", + dot: "bg-orange-500", + pill: "border-orange-200 bg-orange-50 text-orange-700 dark:border-orange-800 dark:bg-orange-950/50 dark:text-orange-300", + }, + completed: { + card: "border-sky-300/90 bg-sky-50/90 text-sky-950 hover:bg-sky-100/90 dark:border-sky-800 dark:bg-sky-950/60 dark:text-sky-100 dark:hover:bg-sky-900/60", + cardSelected: "ring-2 ring-sky-500/70 bg-sky-100 dark:bg-sky-900/80", + dot: "bg-sky-500", + pill: "border-sky-200 bg-sky-50 text-sky-700 dark:border-sky-800 dark:bg-sky-950/50 dark:text-sky-300", + }, + paused: { + card: "border-slate-300/90 bg-slate-100/90 text-slate-800 hover:bg-slate-200/80 dark:border-slate-700 dark:bg-slate-800/70 dark:text-slate-200 dark:hover:bg-slate-800", + cardSelected: "ring-2 ring-slate-400/70 bg-slate-200/90 dark:bg-slate-700/80", + dot: "bg-slate-400", + pill: "border-slate-200 bg-slate-100 text-slate-700 dark:border-slate-700 dark:bg-slate-800 dark:text-slate-300", + }, + error: { + card: "border-rose-300/90 bg-rose-50/90 text-rose-950 hover:bg-rose-100/90 dark:border-rose-800 dark:bg-rose-950/60 dark:text-rose-100 dark:hover:bg-rose-900/60", + cardSelected: "ring-2 ring-rose-500/70 bg-rose-100 dark:bg-rose-900/80", + dot: "bg-rose-500", + pill: "border-rose-200 bg-rose-50 text-rose-700 dark:border-rose-800 dark:bg-rose-950/50 dark:text-rose-300", + }, +}; + +type DragState = { + occurrence: CalendarEventOccurrence; + mode: "move" | "resize"; + originClientX: number; + originClientY: number; + originDayIndex: number; + previewDateKey: string; + previewStartMin: number; + previewEndMin: number; + moved: boolean; +}; + +function formatDurationBadge(minutes: number, translate: TFunction): string { + const safe = Math.max(0, Math.round(minutes)); + const h = Math.floor(safe / 60); + const m = safe % 60; + if (h > 0 && m > 0) return translate("schedule.calendar.durationHoursMinutes", { hours: h, minutes: m }); + if (h > 0) return translate("schedule.calendar.durationHours", { hours: h }); + return translate("schedule.calendar.durationMinutes", { minutes: m }); +} + +function formatHourGutter(hour: number, isEn: boolean): string { + if (!isEn) return `${String(hour).padStart(2, "0")}:00`; + if (hour === 0) return "12 am"; + if (hour < 12) return `${hour} am`; + if (hour === 12) return "12 pm"; + return `${hour - 12} pm`; +} + +export function ScheduleCalendarWorkspace({ + schedules, + tasks, + proxyPool, + serverTimeISO, + serverUtcOffsetMinutes, + query, + onQueryChange, + onCreateNew, + onCreateAtSlot, + onEdit, + onDuplicate, + onAction, + onDelete, + onQuickUpdateSchedule, + onLoadTimeline, + renderTimeline, + listViewContent, +}: { + schedules: TaskSchedule[]; + tasks: Task[]; + proxyPool: ProxyPoolEntry[]; + serverTimeISO?: string; + serverUtcOffsetMinutes?: number; + query: string; + onQueryChange: (q: string) => void; + onCreateNew: () => void; + onCreateAtSlot: (dateKey: string, startMin: number, endMin: number) => void; + onEdit: (item: TaskSchedule) => void; + onDuplicate: (item: TaskSchedule) => void; + onAction: (id: number, type: "pause" | "resume" | "run") => Promise; + onDelete: (id: number) => Promise; + onQuickUpdateSchedule: (id: number, input: ScheduleInput) => Promise; + onLoadTimeline: (id: number) => Promise; + renderTimeline: (id: number) => React.ReactNode; + listViewContent: React.ReactNode; +}) { + const { t: translate, i18n, isEn } = useLiveTranslation(); + const locale = i18n.resolvedLanguage ?? "zh-CN"; + const { statusText, timezoneLabel, windowLabel, formatDateValue } = scheduleDisplay(translate, locale); + + // Calibrate server clock offset (ms) when server_time arrives. + const [clockOffsetMs, setClockOffsetMs] = React.useState(0); + const [tickNowMs, setTickNowMs] = React.useState(() => Date.now()); + React.useEffect(() => { + if (!serverTimeISO) return; + const parsed = Date.parse(serverTimeISO); + if (!Number.isNaN(parsed)) { + setClockOffsetMs(parsed - Date.now()); + setTickNowMs(Date.now()); + } + }, [serverTimeISO]); + React.useEffect(() => { + const timer = setInterval(() => setTickNowMs(Date.now()), 30_000); + return () => clearInterval(timer); + }, []); + + const serverOffset = serverUtcOffsetMinutes ?? -new Date().getTimezoneOffset(); + const [clockMode, setClockMode] = React.useState("server"); + const displayOffset = resolveDisplayOffsetMinutes(clockMode, serverOffset); + const calibratedNowMs = tickNowMs + clockOffsetMs; + const nowParts = toZonedParts(calibratedNowMs, displayOffset); + const todayKey = nowParts.dateKey; + const nowMinutes = nowParts.hour * 60 + nowParts.minute; + + const [viewMode, setViewMode] = React.useState("week"); + const [anchorDateKey, setAnchorDateKey] = React.useState(todayKey); + const initializedAnchor = React.useRef(false); + React.useEffect(() => { + if (!initializedAnchor.current && serverTimeISO) { + initializedAnchor.current = true; + setAnchorDateKey(todayKey); + } + }, [serverTimeISO, todayKey]); + + const anchorParts = parseDateKey(anchorDateKey) ?? { + year: nowParts.year, + month: nowParts.month, + day: nowParts.day, + }; + const [miniMonth, setMiniMonth] = React.useState<{ year: number; month: number }>({ + year: anchorParts.year, + month: anchorParts.month, + }); + React.useEffect(() => { + setMiniMonth({ year: anchorParts.year, month: anchorParts.month }); + }, [anchorParts.year, anchorParts.month]); + + const [enabledStatuses, setEnabledStatuses] = React.useState>({ + running: true, + waiting: true, + outside: true, + paused: true, + completed: true, + error: true, + }); + const [selectedOccurrence, setSelectedOccurrence] = React.useState(null); + const [popoverTimelineOpen, setPopoverTimelineOpen] = React.useState(false); + const [dragState, setDragState] = React.useState(null); + const gridBodyRef = React.useRef(null); + const dayColumnsRef = React.useRef(null); + + // Scroll the week/day time grid near current server hour (or 07:00) on view entry. + React.useEffect(() => { + if (viewMode !== "week" && viewMode !== "day") return; + const el = gridBodyRef.current; + if (!el) return; + const targetHour = Math.max(0, Math.min(18, nowParts.hour >= 6 ? nowParts.hour - 2 : 7)); + el.scrollTop = targetHour * HOUR_HEIGHT; + }, [viewMode]); // intentionally run on view switch + + const taskById = React.useMemo(() => { + const map = new Map(); + for (const t of tasks) { + map.set(Number(t.id), t); + } + return map; + }, [tasks]); + + // Filter schedules by search query + status checkboxes. + const searchMatchedSchedules = React.useMemo(() => { + const q = query.trim().toLowerCase(); + if (!q) return schedules; + return schedules.filter((item) => + [item.name, item.remark ?? "", String(item.id), ...item.task_ids.map(String)] + .join(" ") + .toLowerCase() + .includes(q), + ); + }, [schedules, query]); + + const statusCounts = React.useMemo(() => { + const counts: Record = { + running: 0, + waiting: 0, + outside: 0, + paused: 0, + completed: 0, + error: 0, + }; + for (const s of searchMatchedSchedules) { + if (s.status in counts) counts[s.status] += 1; + } + return counts; + }, [searchMatchedSchedules]); + + const visibleSchedules = React.useMemo( + () => searchMatchedSchedules.filter((s) => enabledStatuses[s.status] !== false), + [searchMatchedSchedules, enabledStatuses], + ); + + // Visible date keys for current view. + const visibleDateKeys = React.useMemo(() => { + if (viewMode === "day") return [anchorDateKey]; + if (viewMode === "week") return buildWeekDateKeys(anchorDateKey); + return buildMonthGridDateKeys(anchorParts.year, anchorParts.month); + }, [viewMode, anchorDateKey, anchorParts.year, anchorParts.month]); + + const occurrences = React.useMemo( + () => expandSchedulesForDateKeys(visibleSchedules, visibleDateKeys, displayOffset, serverOffset), + [visibleSchedules, visibleDateKeys, displayOffset, serverOffset], + ); + + // Mini month calendar dots. + const miniMonthKeys = React.useMemo( + () => buildMonthGridDateKeys(miniMonth.year, miniMonth.month), + [miniMonth.year, miniMonth.month], + ); + const miniMonthDotDays = React.useMemo(() => { + const occs = expandSchedulesForDateKeys(visibleSchedules, miniMonthKeys, displayOffset, serverOffset); + const set = new Set(); + for (const o of occs) set.add(o.dateKey); + return set; + }, [visibleSchedules, miniMonthKeys, displayOffset, serverOffset]); + + // Upcoming schedules for "Up next" sidebar list. + const upcomingItems = React.useMemo(() => { + return visibleSchedules + .filter((s) => s.enabled && s.status !== "completed" && (s.status === "running" || s.next_start)) + .map((s) => { + const nextMs = s.next_start ? Date.parse(s.next_start) : calibratedNowMs; + const deltaMs = s.status === "running" ? 0 : nextMs - calibratedNowMs; + return { schedule: s, deltaMs, nextMs }; + }) + .sort((a, b) => a.deltaMs - b.deltaMs) + .slice(0, 5); + }, [visibleSchedules, calibratedNowMs]); + + const formatCountdown = (deltaMs: number, status: TaskSchedule["status"]) => { + if (status === "running" || deltaMs <= 0) return translate("schedule.calendar.nowRunning"); + const mins = Math.max(1, Math.round(deltaMs / 60_000)); + if (mins < 60) return translate("schedule.calendar.inMinutes", { count: mins }); + const hrs = Math.round(mins / 60); + if (hrs < 48) return translate("schedule.calendar.inHours", { count: hrs }); + return translate("schedule.calendar.inDays", { count: Math.round(hrs / 24) }); + }; + + // Period header label (e.g. "Nov – Dec 2026" or "2026年12月"). + const headerRangeLabel = React.useMemo(() => { + const fmtMonthYear = (y: number, m: number) => + new Intl.DateTimeFormat(locale, { year: "numeric", month: "short" }).format(new Date(Date.UTC(y, m - 1, 15))); + if (viewMode === "day") { + return formatDateValue(anchorDateKey); + } + if (viewMode === "week") { + const first = parseDateKey(visibleDateKeys[0]); + const last = parseDateKey(visibleDateKeys[visibleDateKeys.length - 1]); + if (first && last) { + if (first.year === last.year && first.month === last.month) { + return fmtMonthYear(first.year, first.month); + } + const m1 = new Intl.DateTimeFormat(locale, { month: "short" }).format( + new Date(Date.UTC(first.year, first.month - 1, 15)), + ); + const m2 = new Intl.DateTimeFormat(locale, { month: "short" }).format( + new Date(Date.UTC(last.year, last.month - 1, 15)), + ); + return `${m1} – ${m2} ${last.year}`; + } + } + return new Intl.DateTimeFormat(locale, { year: "numeric", month: "long" }).format( + new Date(Date.UTC(anchorParts.year, anchorParts.month - 1, 15)), + ); + }, [viewMode, anchorDateKey, visibleDateKeys, anchorParts.year, anchorParts.month, locale, formatDateValue]); + + const navigatePeriod = (dir: -1 | 1) => { + if (viewMode === "day") { + setAnchorDateKey(addDaysToDateKey(anchorDateKey, dir)); + } else if (viewMode === "week") { + setAnchorDateKey(addDaysToDateKey(anchorDateKey, dir * 7)); + } else { + const d = new Date(Date.UTC(anchorParts.year, anchorParts.month - 1 + dir, 1)); + setAnchorDateKey(makeDateKey(d.getUTCFullYear(), d.getUTCMonth() + 1, 1)); + } + }; + + const shiftMiniMonth = (dir: -1 | 1) => { + const d = new Date(Date.UTC(miniMonth.year, miniMonth.month - 1 + dir, 1)); + setMiniMonth({ year: d.getUTCFullYear(), month: d.getUTCMonth() + 1 }); + }; + + // Drag-to-move and drag-to-resize handlers for Week/Day grid. + React.useEffect(() => { + if (!dragState) return; + const handleMove = (e: PointerEvent) => { + const dx = e.clientX - dragState.originClientX; + const dy = e.clientY - dragState.originClientY; + const moved = dragState.moved || Math.abs(dx) > 4 || Math.abs(dy) > 4; + const deltaMinutes = Math.round(((dy / HOUR_HEIGHT) * 60) / 15) * 15; + + if (dragState.mode === "resize") { + const nextEnd = Math.max( + dragState.occurrence.startMin + 15, + Math.min(1440, dragState.occurrence.endMin + deltaMinutes), + ); + setDragState((prev) => (prev ? { ...prev, previewEndMin: nextEnd, moved } : null)); + return; + } + + // Move mode (supports vertical time shift + horizontal day column shift in Week view) + let nextDateKey = dragState.occurrence.dateKey; + if (viewMode === "week" && dayColumnsRef.current) { + const rect = dayColumnsRef.current.getBoundingClientRect(); + if (rect.width > 0) { + const colW = rect.width / visibleDateKeys.length; + const colIdx = Math.max(0, Math.min(visibleDateKeys.length - 1, Math.floor((e.clientX - rect.left) / colW))); + nextDateKey = visibleDateKeys[colIdx]; + } + } + const dur = dragState.occurrence.endMin - dragState.occurrence.startMin; + const nextStart = Math.max(0, Math.min(1440 - dur, dragState.occurrence.startMin + deltaMinutes)); + setDragState((prev) => + prev + ? { + ...prev, + previewDateKey: nextDateKey, + previewStartMin: nextStart, + previewEndMin: nextStart + dur, + moved, + } + : null, + ); + }; + + const handleUp = () => { + const current = dragState; + setDragState(null); + if (!current.moved) { + // Treat as a click -> open detail popover. + setPopoverTimelineOpen(false); + setSelectedOccurrence(current.occurrence); + return; + } + const changed = + current.previewDateKey !== current.occurrence.dateKey || + current.previewStartMin !== current.occurrence.startMin || + current.previewEndMin !== current.occurrence.endMin; + if (!changed) return; + const payload = buildScheduleInputFromDrag( + current.occurrence, + current.previewDateKey, + current.previewStartMin, + current.previewEndMin, + displayOffset, + serverOffset, + ); + void onQuickUpdateSchedule(current.occurrence.scheduleId, payload); + }; + + window.addEventListener("pointermove", handleMove); + window.addEventListener("pointerup", handleUp, { once: true }); + return () => { + window.removeEventListener("pointermove", handleMove); + window.removeEventListener("pointerup", handleUp); + }; + }, [dragState, viewMode, visibleDateKeys, displayOffset, serverOffset, onQuickUpdateSchedule]); + + // Keep selectedOccurrence synced if schedule refreshes. + const activeSelectedSchedule = React.useMemo(() => { + if (!selectedOccurrence) return null; + return schedules.find((s) => s.id === selectedOccurrence.scheduleId) ?? null; + }, [selectedOccurrence, schedules]); + + const gmtLabel = formatGMTOffset(displayOffset); + const liveClockStr = `${String(nowParts.hour).padStart(2, "0")}:${String(nowParts.minute).padStart(2, "0")}`; + const miniMonthTitle = new Intl.DateTimeFormat(locale, { year: "numeric", month: "long" }).format( + new Date(Date.UTC(miniMonth.year, miniMonth.month - 1, 15)), + ); + + // Group occurrences by dateKey. + const allDayByDate = React.useMemo(() => { + const map = new Map(); + for (const ev of occurrences) { + if (!ev.allDay) continue; + const list = map.get(ev.dateKey) ?? []; + list.push(ev); + map.set(ev.dateKey, list); + } + return map; + }, [occurrences]); + + const timedByDate = React.useMemo(() => { + const map = new Map(); + for (const ev of occurrences) { + if (ev.allDay) continue; + const list = map.get(ev.dateKey) ?? []; + list.push(ev); + map.set(ev.dateKey, list); + } + return map; + }, [occurrences]); + + const renderEventDetailCard = (item: TaskSchedule, occ: CalendarEventOccurrence) => { + const style = STATUS_STYLE[item.status] ?? STATUS_STYLE.waiting; + const durationMins = occ.allDay ? 0 : Math.max(0, occ.endMin - occ.startMin); + const linkedTasks = item.task_ids.map((id) => ({ id, task: taskById.get(id) })); + + return ( +
+ {/* Top row: status badge + quick actions (Edit / Pause / Duplicate / Delete / Close) */} +
+
+ + {statusText(item)} +
+
+ + + + + +
+
+ + {/* Title & Time range */} +
+
{item.name}
+
+ {formatDateValue(occ.dateKey)} + · + {occ.allDay ? windowLabel(item) : occ.displayTimeRange} + {durationMins > 0 ? ( + + {formatDurationBadge(durationMins, translate)} + + ) : null} +
+
+ + {timezoneLabel(item)} + {item.proxy_mode && item.proxy_mode !== "inherit" ? ( + + + {formatProxyRouteSummary( + { + mode: item.proxy_mode, + proxy_pool_id: item.proxy_pool_id, + proxy_url: item.proxy_url, + effective_proxy: item.effective_proxy, + }, + isEn, + proxyPool, + )} + + ) : null} +
+ {item.remark ?

{item.remark}

: null} +
+ + {/* Primary Run Now CTA button (matching screenshot's blue action button) */} +
+ + +
+ + {/* Linked Tasks section (matching screenshot's guests list) */} +
+
+ + + {linkedTasks.length > 0 + ? translate("schedule.calendar.boundTasksCount", { count: linkedTasks.length }) + : translate("schedule.calendar.noBoundTasks")} + +
+ {linkedTasks.length > 0 ? ( +
+ {linkedTasks.map(({ id, task }) => ( + + + + + #{id} {task?.name?.trim() || task?.description || ""} + + + {task?.status ? ( + {task.status} + ) : null} + + ))} +
+ ) : null} +
+ + {/* Optional expandable timeline */} + {popoverTimelineOpen ? ( +
{renderTimeline(item.id)}
+ ) : null} +
+ ); + }; + + return ( +
+ {/* Left Sidebar: Search + Mini Month Calendar + Status Filters + Up Next */} + + + {/* Main Right Area */} +
+ {/* Top Toolbar */} +
+ {/* Left: Today + arrows + period title */} +
+ +
+ + +
+

{headerRangeLabel}

+
+ + {/* Right: Server clock & TZ switcher + manual date picker + view switcher + New button */} +
+ {/* Server time & timezone switcher */} +
+ + {liveClockStr} + +
+ + {/* Manual date jump */} + + + + + +
{translate("schedule.calendar.jumpDate")}
+ { + if (e.target.value) setAnchorDateKey(e.target.value); + }} + className="h-8 font-mono text-xs" + /> +
+
+ + {/* View mode segmented control */} +
+ {(["day", "week", "month", "list"] as CalendarViewMode[]).map((mode) => ( + + ))} +
+ + {/* Primary New Schedule button */} + +
+
+ + {/* Main Content Body */} + {viewMode === "list" ? ( +
{listViewContent}
+ ) : viewMode === "month" ? ( + /* Month Grid View */ +
+
+ {[1, 2, 3, 4, 5, 6, 7].map((wd) => ( +
+ {translate(`schedule.weekday.${wd}`)} +
+ ))} +
+
+ {visibleDateKeys.map((dk) => { + const p = parseDateKey(dk); + const inMonth = p?.month === anchorParts.month; + const isToday = dk === todayKey; + const dayEvents = occurrences.filter((o) => o.dateKey === dk); + return ( +
onCreateAtSlot(dk, 9 * 60, 10 * 60)} + className={cn( + "flex min-h-24 cursor-pointer flex-col gap-1 border-r border-b p-1.5 transition-colors hover:bg-muted/20", + !inMonth && "bg-muted/15 text-muted-foreground", + )} + > +
+ +
+
+ {dayEvents.slice(0, 3).map((ev) => { + const st = STATUS_STYLE[ev.schedule.status] ?? STATUS_STYLE.waiting; + return ( + + ); + })} + {dayEvents.length > 3 ? ( + + ) : null} +
+
+ ); + })} +
+
+ ) : ( + /* Week & Day Time Grid View */ +
+ {/* Sticky Day Column Headers */} +
+
+ {gmtLabel} +
+ {visibleDateKeys.map((dk) => { + const p = parseDateKey(dk); + const isToday = dk === todayKey; + const d = p ? new Date(Date.UTC(p.year, p.month - 1, p.day)) : new Date(); + const wdShort = new Intl.DateTimeFormat(locale, { weekday: "short", timeZone: "UTC" }).format(d); + return ( +
+ + {wdShort} + + +
+ ); + })} +
+ + {/* All-day / Continuous strip */} +
+
+ {translate("schedule.calendar.allDay")} +
+ {visibleDateKeys.map((dk) => { + const pills = allDayByDate.get(dk) ?? []; + return ( +
+ {pills.map((ev) => { + const st = STATUS_STYLE[ev.schedule.status] ?? STATUS_STYLE.waiting; + return ( + + ); + })} +
+ ); + })} +
+ + {/* Scrollable 24-hour Grid */} +
+
+ {/* Left Time Gutter */} +
+ {Array.from({ length: 24 }, (_, hour) => ( +
+ {hour > 0 ? ( + {formatHourGutter(hour, isEn)} + ) : null} +
+ ))} + {/* Red Current-Time Pill on Gutter (matching screenshot's 1:10 red pill) */} + {visibleDateKeys.includes(todayKey) ? ( +
+ {liveClockStr} +
+ ) : null} +
+ + {/* Day Columns */} +
+ {visibleDateKeys.map((dk, colIdx) => { + const isToday = dk === todayKey; + const dayTimed = timedByDate.get(dk) ?? []; + const positioned = layoutDayTimedEvents(dayTimed); + + return ( +
+ {/* Hourly clickable background slots */} + {Array.from({ length: 24 }, (_, hour) => ( +
onCreateAtSlot(dk, hour * 60, Math.min(1440, (hour + 1) * 60))} + className="cursor-crosshair border-b border-border/50 transition-colors hover:bg-blue-50/40 dark:hover:bg-blue-950/20" + style={{ height: `${HOUR_HEIGHT}px` }} + /> + ))} + + {/* Red Current-Time Line with Leading Dot on Today */} + {isToday ? ( +
+ +
+
+ ) : null} + + {/* Timed Event Blocks */} + {positioned.map((ev) => { + const isBeingDragged = dragState?.occurrence.id === ev.id; + if (isBeingDragged && dragState.previewDateKey !== dk) { + return null; + } + const startM = isBeingDragged ? dragState.previewStartMin : ev.startMin; + const endM = isBeingDragged ? dragState.previewEndMin : ev.endMin; + const topPx = (startM / 60) * HOUR_HEIGHT; + const heightPx = Math.max(22, ((endM - startM) / 60) * HOUR_HEIGHT - 2); + const widthPct = 100 / ev.colCount; + const leftPct = ev.col * widthPct; + const st = STATUS_STYLE[ev.schedule.status] ?? STATUS_STYLE.waiting; + const canDrag = !ev.isContinuedFromPrev && !ev.isContinuesToNext; + + return ( +
{ + if (e.button !== 0) return; + e.stopPropagation(); + if (!canDrag) { + setPopoverTimelineOpen(false); + setSelectedOccurrence(ev); + return; + } + setDragState({ + occurrence: ev, + mode: "move", + originClientX: e.clientX, + originClientY: e.clientY, + originDayIndex: colIdx, + previewDateKey: dk, + previewStartMin: ev.startMin, + previewEndMin: ev.endMin, + moved: false, + }); + }} + title={`${ev.schedule.name} · ${ev.displayTimeRange}`} + style={{ + top: `${topPx}px`, + height: `${heightPx}px`, + left: `calc(${leftPct}% + 2px)`, + width: `calc(${widthPct}% - 4px)`, + }} + className={cn( + "group absolute z-10 flex select-none flex-col overflow-hidden rounded-md border px-2 py-1 text-left shadow-[0_1px_2px_rgba(0,0,0,0.04)] transition-shadow", + st.card, + selectedOccurrence?.id === ev.id && st.cardSelected, + isBeingDragged && "z-30 shadow-lg opacity-95", + canDrag ? "cursor-grab active:cursor-grabbing" : "cursor-pointer", + )} + > +
{ev.schedule.name}
+ {heightPx >= 34 ? ( +
+ {isBeingDragged + ? `${formatMinutesAsClock(startM)} - ${formatMinutesAsClock(endM)}` + : ev.displayTimeRange} +
+ ) : null} + {heightPx >= 56 && ev.schedule.task_ids.length > 0 ? ( +
+ {ev.schedule.task_ids.map((id) => `#${id}`).join(", ")} +
+ ) : null} + + {/* Bottom resize handle (matching Image #1 vertical resize cursor) */} + {canDrag ? ( +
{ + if (e.button !== 0) return; + e.stopPropagation(); + setDragState({ + occurrence: ev, + mode: "resize", + originClientX: e.clientX, + originClientY: e.clientY, + originDayIndex: colIdx, + previewDateKey: dk, + previewStartMin: ev.startMin, + previewEndMin: ev.endMin, + moved: false, + }); + }} + className="absolute inset-x-1 bottom-0 flex h-2 cursor-ns-resize items-center justify-center opacity-0 transition-opacity group-hover:opacity-100" + > + +
+ ) : null} +
+ ); + })} + + {/* Render drag ghost when dragged into another column */} + {dragState && + dragState.mode === "move" && + dragState.previewDateKey === dk && + dragState.occurrence.dateKey !== dk ? ( +
+
+ {dragState.occurrence.schedule.name} +
+
+ {formatMinutesAsClock(dragState.previewStartMin)} -{" "} + {formatMinutesAsClock(dragState.previewEndMin)} +
+
+ ) : null} +
+ ); + })} +
+
+
+
+ )} +
+ + {/* Floating Event Detail Card Modal / Popover (matching Image #2) */} + {selectedOccurrence && activeSelectedSchedule ? ( +
setSelectedOccurrence(null)} + > +
e.stopPropagation()} + > + {renderEventDetailCard(activeSelectedSchedule, selectedOccurrence)} +
+
+ ) : null} +
+ ); +} diff --git a/web/src/app/(main)/function/schedules/page.tsx b/web/src/app/(main)/function/schedules/page.tsx index 4f96312..7096fad 100644 --- a/web/src/app/(main)/function/schedules/page.tsx +++ b/web/src/app/(main)/function/schedules/page.tsx @@ -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([]); const [tasks, setTasks] = React.useState([]); const [proxyPool, setProxyPool] = React.useState([]); + const [serverTimeISO, setServerTimeISO] = React.useState(undefined); + const [serverUtcOffsetMinutes, setServerUtcOffsetMinutes] = React.useState(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 ( -
-
+
+
-

- +

+ {translate("schedule.title")}

-

{translate("schedule.description")}

+

{translate("schedule.description")}

-
- {editing && ( - - - {editing.id ? translate("schedule.editSchedule") : translate("schedule.create")} - {translate("schedule.pauseHelp")} - - + + 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) => } + listViewContent={scheduleContent} + /> + + !open && setEditing(null)}> + + + {editing?.id ? translate("schedule.editSchedule") : translate("schedule.create")} + {translate("schedule.pauseHelp")} + + {editing ? ( setEditing(null)} onSave={save} /> - - - )} - {scheduleContent} + ) : null} + +
); } diff --git a/web/src/i18n/schedule-messages.ts b/web/src/i18n/schedule-messages.ts index 06d9ae1..812d4c5 100644 --- a/web/src/i18n/schedule-messages.ts +++ b/web/src/i18n/schedule-messages.ts @@ -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; diff --git a/web/src/lib/api.ts b/web/src/lib/api.ts index 769c980..6425f20 100644 --- a/web/src/lib/api.ts +++ b/web/src/lib/api.ts @@ -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(`/schedules/${id}/metadata`, { name }), updateScheduleRemark: (id: number, remark: string) => patch(`/schedules/${id}/remark`, { remark }), diff --git a/web/src/lib/schedule-calendar.test.mjs b/web/src/lib/schedule-calendar.test.mjs new file mode 100644 index 0000000..e044870 --- /dev/null +++ b/web/src/lib/schedule-calendar.test.mjs @@ -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"); +}); diff --git a/web/src/lib/schedule-calendar.ts b/web/src/lib/schedule-calendar.ts new file mode 100644 index 0000000..2134831 --- /dev/null +++ b/web/src/lib/schedule-calendar.ts @@ -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, + 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, + }; +}