summaryrefslogtreecommitdiff
path: root/internal/handlers/timeline_logic_test.go
blob: 11406b94f62f4e3cee29d8d685c5358db97369dc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
package handlers

import (
	"context"
	"os"
	"path/filepath"
	"testing"
	"time"

	"task-dashboard/internal/models"
	"task-dashboard/internal/store"

	_ "github.com/mattn/go-sqlite3"
)

// MockCalendarClient implements GoogleCalendarAPI interface for testing
type MockCalendarClient struct {
	Events []models.CalendarEvent
	Err    error
}

func (m *MockCalendarClient) GetUpcomingEvents(ctx context.Context, maxResults int) ([]models.CalendarEvent, error) {
	return m.Events, m.Err
}

func (m *MockCalendarClient) GetEventsByDateRange(ctx context.Context, start, end time.Time) ([]models.CalendarEvent, error) {
	return m.Events, m.Err
}

func (m *MockCalendarClient) GetCalendarList(ctx context.Context) ([]models.CalendarInfo, error) {
	return nil, m.Err
}

func setupTestStore(t *testing.T) *store.Store {
	t.Helper()
	tempDir := t.TempDir()
	dbPath := filepath.Join(tempDir, "test.db")
	migrationDir := filepath.Join(tempDir, "migrations")

	if err := os.MkdirAll(migrationDir, 0755); err != nil {
		t.Fatalf("Failed to create migration dir: %v", err)
	}

	schema := `
		CREATE TABLE IF NOT EXISTS tasks (
			id TEXT PRIMARY KEY,
			content TEXT NOT NULL,
			description TEXT,
			project_id TEXT,
			project_name TEXT,
			due_date DATETIME,
			priority INTEGER DEFAULT 1,
			completed BOOLEAN DEFAULT FALSE,
			labels TEXT,
			url TEXT,
			created_at DATETIME,
			updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
		);
		CREATE TABLE IF NOT EXISTS meals (
			id TEXT PRIMARY KEY,
			recipe_name TEXT NOT NULL,
			date DATETIME,
			meal_type TEXT,
			recipe_url TEXT,
			updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
		);
		CREATE TABLE IF NOT EXISTS boards (
			id TEXT PRIMARY KEY,
			name TEXT NOT NULL,
			updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
		);
		CREATE TABLE IF NOT EXISTS cards (
			id TEXT PRIMARY KEY,
			name TEXT NOT NULL,
			board_id TEXT NOT NULL,
			list_id TEXT,
			list_name TEXT,
			due_date DATETIME,
			url TEXT,
			updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
		);
	`
	if err := os.WriteFile(filepath.Join(migrationDir, "001_init.sql"), []byte(schema), 0644); err != nil {
		t.Fatalf("Failed to write migration file: %v", err)
	}

	// Initialize store (this creates tables)
	s, err := store.New(dbPath, migrationDir)
	if err != nil {
		t.Fatalf("Failed to create store: %v", err)
	}
	return s
}

func TestBuildTimeline(t *testing.T) {
	s := setupTestStore(t)
	
	// Fix a base time: 2023-01-01 08:00:00
	baseTime := time.Date(2023, 1, 1, 8, 0, 0, 0, time.UTC)
	
	// Task: 10:00
	taskDate := baseTime.Add(2 * time.Hour)
	_ = s.SaveTasks([]models.Task{
		{ID: "t1", Content: "Task 1", DueDate: &taskDate},
	})

	// Meal: Lunch (defaults to 12:00)
	mealDate := baseTime // Date part matters
	_ = s.SaveMeals([]models.Meal{
		{ID: "m1", RecipeName: "Lunch", Date: mealDate, MealType: "lunch"},
	})

	// Card: 14:00
	cardDate := baseTime.Add(6 * time.Hour)
	_ = s.SaveBoards([]models.Board{
		{
			ID: "b1",
			Name: "Board 1",
			Cards: []models.Card{
				{ID: "c1", Name: "Card 1", DueDate: &cardDate, ListID: "l1"},
			},
		},
	})

	// Calendar Event: 09:00
	eventDate := baseTime.Add(1 * time.Hour)
	mockCal := &MockCalendarClient{
		Events: []models.CalendarEvent{
			{ID: "e1", Summary: "Event 1", Start: eventDate, End: eventDate.Add(1 * time.Hour)},
		},
	}

	// Test Range: Full Day
	start := time.Date(2023, 1, 1, 0, 0, 0, 0, time.UTC)
	end := time.Date(2023, 1, 2, 0, 0, 0, 0, time.UTC)

	items, err := BuildTimeline(context.Background(), s, mockCal, nil, start, end)
	if err != nil {
		t.Fatalf("BuildTimeline failed: %v", err)
	}

	if len(items) != 4 {
		t.Errorf("Expected 4 items, got %d", len(items))
	}

	// Expected Order:
	// 1. Event (09:00)
	// 2. Task (10:00)
	// 3. Meal (12:00)
	// 4. Card (14:00)

	if items[0].Type != models.TimelineItemTypeEvent {
		t.Errorf("Expected item 0 to be Event, got %s", items[0].Type)
	}
	if items[1].Type != models.TimelineItemTypeTask {
		t.Errorf("Expected item 1 to be Task, got %s", items[1].Type)
	}
	if items[2].Type != models.TimelineItemTypeMeal {
		t.Errorf("Expected item 2 to be Meal, got %s", items[2].Type)
	}
	if items[3].Type != models.TimelineItemTypeCard {
		t.Errorf("Expected item 3 to be Card, got %s", items[3].Type)
	}
}

func TestCalcCalendarBounds(t *testing.T) {
	tests := []struct {
		name        string
		items       []models.TimelineItem
		currentHour int
		wantStart   int
		wantEnd     int
	}{
		{
			name:        "no timed events returns default",
			items:       []models.TimelineItem{},
			currentHour: -1,
			wantStart:   8,
			wantEnd:     18,
		},
		{
			name: "single event at 10am",
			items: []models.TimelineItem{
				{Time: time.Date(2023, 1, 1, 10, 0, 0, 0, time.UTC)},
			},
			currentHour: -1,
			wantStart:   9,  // 1 hour buffer before
			wantEnd:     11, // 1 hour buffer after
		},
		{
			name: "includes current hour",
			items: []models.TimelineItem{
				{Time: time.Date(2023, 1, 1, 10, 0, 0, 0, time.UTC)},
			},
			currentHour: 8,
			wantStart:   7,  // 1 hour before 8am
			wantEnd:     11, // 1 hour after 10am
		},
		{
			name: "event with end time extends range",
			items: []models.TimelineItem{
				{
					Time:    time.Date(2023, 1, 1, 10, 0, 0, 0, time.UTC),
					EndTime: timePtr(time.Date(2023, 1, 1, 14, 0, 0, 0, time.UTC)),
				},
			},
			currentHour: -1,
			wantStart:   9,  // 1 hour before 10am
			wantEnd:     15, // 1 hour after 2pm end
		},
		{
			name: "all-day events are skipped",
			items: []models.TimelineItem{
				{Time: time.Date(2023, 1, 1, 0, 0, 0, 0, time.UTC), IsAllDay: true},
			},
			currentHour: -1,
			wantStart:   8,
			wantEnd:     18,
		},
		{
			name: "overdue events are skipped",
			items: []models.TimelineItem{
				{Time: time.Date(2023, 1, 1, 10, 0, 0, 0, time.UTC), IsOverdue: true},
			},
			currentHour: -1,
			wantStart:   8,
			wantEnd:     18,
		},
		{
			name: "clamps to 0-23 range",
			items: []models.TimelineItem{
				{Time: time.Date(2023, 1, 1, 0, 30, 0, 0, time.UTC)},
				{Time: time.Date(2023, 1, 1, 23, 0, 0, 0, time.UTC)},
			},
			currentHour: -1,
			wantStart:   0,  // Can't go below 0
			wantEnd:     23, // Can't go above 23
		},
	}

	for _, tc := range tests {
		t.Run(tc.name, func(t *testing.T) {
			start, end := calcCalendarBounds(tc.items, tc.currentHour)
			if start != tc.wantStart {
				t.Errorf("Expected start %d, got %d", tc.wantStart, start)
			}
			if end != tc.wantEnd {
				t.Errorf("Expected end %d, got %d", tc.wantEnd, end)
			}
		})
	}
}

func TestBuildTimeline_IncludesOverdueItems(t *testing.T) {
	s := setupTestStore(t)

	// Base: "today" is Jan 2, 2023
	today := time.Date(2023, 1, 2, 0, 0, 0, 0, time.UTC)
	yesterday := time.Date(2023, 1, 1, 10, 0, 0, 0, time.UTC) // overdue
	todayNoon := time.Date(2023, 1, 2, 12, 0, 0, 0, time.UTC) // current

	// Save a task that is overdue (yesterday) and one that is current (today)
	_ = s.SaveTasks([]models.Task{
		{ID: "overdue1", Content: "Overdue task", DueDate: &yesterday},
		{ID: "current1", Content: "Current task", DueDate: &todayNoon},
	})

	// Query range: today through tomorrow
	end := today.AddDate(0, 0, 1)

	items, err := BuildTimeline(context.Background(), s, nil, nil, today, end)
	if err != nil {
		t.Fatalf("BuildTimeline failed: %v", err)
	}

	// Should include both the overdue task and the current task
	if len(items) < 2 {
		t.Errorf("Expected at least 2 items (overdue + current), got %d", len(items))
		for _, item := range items {
			t.Logf("  item: %s (type=%s, time=%s)", item.Title, item.Type, item.Time)
		}
	}

	// Verify overdue task is marked as overdue
	foundOverdue := false
	for _, item := range items {
		if item.ID == "overdue1" {
			foundOverdue = true
			if !item.IsOverdue {
				t.Error("Expected overdue task to be marked IsOverdue=true")
			}
			if item.DaySection != models.DaySectionToday {
				t.Errorf("Expected overdue task in Today section, got %s", item.DaySection)
			}
		}
	}
	if !foundOverdue {
		t.Error("Overdue task was not included in timeline results")
	}
}

func TestBuildTimeline_ExcludesCompletedOverdue(t *testing.T) {
	s := setupTestStore(t)

	yesterday := time.Date(2023, 1, 1, 10, 0, 0, 0, time.UTC)
	today := time.Date(2023, 1, 2, 0, 0, 0, 0, time.UTC)
	end := today.AddDate(0, 0, 1)

	// Save a completed overdue task — should NOT appear
	_ = s.SaveTasks([]models.Task{
		{ID: "done1", Content: "Done overdue", DueDate: &yesterday, Completed: true},
	})

	items, err := BuildTimeline(context.Background(), s, nil, nil, today, end)
	if err != nil {
		t.Fatalf("BuildTimeline failed: %v", err)
	}

	for _, item := range items {
		if item.ID == "done1" {
			t.Error("Completed overdue task should not appear in timeline")
		}
	}
}

func timePtr(t time.Time) *time.Time {
	return &t
}