summaryrefslogtreecommitdiff
path: root/internal/tui/history_box.go
blob: 6856a634f71a30fa7d04291b94cc019ba5265cb8 (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
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
package tui

import (
	"fmt"
	"slices"
	"strconv"
	"strings"
	"time"

	"git.tjp.lol/punchcard/internal/queries"

	"github.com/charmbracelet/bubbles/viewport"
	"github.com/charmbracelet/lipgloss/v2"
)

// HistoryViewLevel represents the level of detail in history view
type HistoryViewLevel int

const (
	HistoryLevelSummary HistoryViewLevel = iota // Level 1: Date/project summaries
	HistoryLevelDetails                         // Level 2: Individual entries
)

type HistorySummaryKey struct {
	Date      time.Time
	ClientID  int64
	ProjectID int64
}

// HistoryFilter represents the filtering criteria for the history view
type HistoryFilter struct {
	StartDate time.Time  // Required - start of date range to display
	EndDate   *time.Time // Optional - end of date range to display (nil means no end date)
	ClientID  *int64     // Optional - filter to specific client
	ProjectID *int64     // Optional - filter to specific project
}

type HistoryBoxModel struct {
	viewLevel HistoryViewLevel
	filter    HistoryFilter

	summaryItems     []HistorySummaryItem
	summarySelection int

	entries         map[HistorySummaryKey][]queries.TimeEntry
	detailSelection int

	// Total duration of all entries in current filter, excluding active timer
	totalDuration time.Duration
}

// HistorySummaryItem represents a date + client/project combination with total duration
type HistorySummaryItem struct {
	Date          time.Time
	ClientID      int64
	ClientName    string
	ProjectID     *int64
	ProjectName   *string
	TotalDuration time.Duration // will exclude the currently running timer, if any
	EntryCount    int
}

func (item HistorySummaryItem) key() HistorySummaryKey {
	key := HistorySummaryKey{
		Date:     dateOnly(item.Date),
		ClientID: item.ClientID,
	}
	if item.ProjectID != nil {
		key.ProjectID = *item.ProjectID
	}
	return key
}

// NewHistoryBoxModel creates a new history box model
func NewHistoryBoxModel() HistoryBoxModel {
	now := time.Now()
	startOfPreviousMonth := time.Date(now.Year(), now.Month()-1, 1, 0, 0, 0, 0, time.UTC)

	return HistoryBoxModel{
		filter: HistoryFilter{
			StartDate: startOfPreviousMonth,
			EndDate:   nil,
			ClientID:  nil,
			ProjectID: nil,
		},
	}
}

func buildIndex[T any, K comparable](items []T, keyf func(T) K) map[K][]T {
	idx := make(map[K][]T)
	for _, item := range items {
		key := keyf(item)
		idx[key] = append(idx[key], item)
	}
	return idx
}

func (m *HistoryBoxModel) regenerateSummaries(
	clients []queries.Client,
	projects map[int64][]queries.Project,
	entries []queries.TimeEntry,
	active TimerInfo,
) {
	m.summaryItems = make([]HistorySummaryItem, 0)

	clientNames := make(map[int64]string)
	for _, client := range clients {
		clientNames[client.ID] = client.Name
	}
	projectNames := make(map[int64]string)
	for _, group := range projects {
		for _, project := range group {
			projectNames[project.ID] = project.Name
		}
	}

	m.entries = buildIndex(entries, func(entry queries.TimeEntry) HistorySummaryKey {
		var projectID int64 = 0
		if entry.ProjectID.Valid {
			projectID = entry.ProjectID.Int64
		}
		return HistorySummaryKey{dateOnly(entry.StartTime.Local()), entry.ClientID, projectID}
	})

	m.totalDuration = 0
	for key, entries := range m.entries {
		var totalDur time.Duration = 0
		for _, entry := range entries {
			if active.IsActive && active.EntryID == entry.ID {
				continue
			}
			totalDur += entry.EndTime.Time.Sub(entry.StartTime)
		}

		item := HistorySummaryItem{
			Date:          key.Date.Local(),
			ClientID:      key.ClientID,
			ClientName:    clientNames[key.ClientID],
			TotalDuration: totalDur,
			EntryCount:    len(entries),
		}
		if key.ProjectID != 0 {
			item.ProjectID = &key.ProjectID
			for _, project := range projects[key.ClientID] {
				if project.ID == key.ProjectID {
					item.ProjectName = &project.Name
					break
				}
			}
		}

		m.summaryItems = append(m.summaryItems, item)
		m.totalDuration += totalDur
	}

	slices.SortFunc(m.summaryItems, func(a, b HistorySummaryItem) int {
		if a.Date.Before(b.Date) {
			return 1
		} else if a.Date.After(b.Date) {
			return -1
		}

		if a.ClientName < b.ClientName {
			return -1
		} else if a.ClientName > b.ClientName {
			return 1
		}

		if a.ProjectName == nil {
			return -1
		}
		if b.ProjectName == nil {
			return 1
		}
		if *a.ProjectName < *b.ProjectName {
			return -1
		}
		return 1
	})
}

// View renders the history box
func (m HistoryBoxModel) View(width, height int, isSelected bool, timer TimerBoxModel, clients []queries.Client, projects map[int64][]queries.Project) string {
	var content string

	if len(m.entries) == 0 {
		content = "📝 Recent History\n\n"
		content += inactiveTimerStyle.Render("No recent entries\n\nStart tracking time to\nsee your history here.")
	} else {
		switch m.viewLevel {
		case HistoryLevelSummary:
			content = m.renderSummaryView(timer, clients, projects)
		case HistoryLevelDetails:
			content = m.renderDetailsView(timer)
		}
	}

	style := unselectedBoxStyle
	if isSelected {
		style = selectedBoxStyle
	}
	style = style.Width(width).Height(height)

	vp := viewport.New(width-2, height-4)
	vp.SetContent(content)

	selectionHeight := m.selectionHeight()
	visible := vp.VisibleLineCount()
	if selectionHeight > vp.VisibleLineCount() {
		vp.ScrollDown(selectionHeight - visible)
	}

	return style.Render(vp.View())
}

func (m HistoryBoxModel) selectionHeight() int {
	switch m.viewLevel {
	case HistoryLevelSummary:
		return m.summarySelectionHeight()
	case HistoryLevelDetails:
		return m.detailsSelectionHeight()
	}
	return 0
}

func (m HistoryBoxModel) summarySelectionHeight() int {
	height := 1 // "Recent History" title line

	if len(m.summaryItems) > 0 {
		height += 3 // 2 newlines + filter info line
	}

	var date *time.Time
	for i, item := range m.summaryItems {
		if date == nil || !date.Equal(item.Date) {
			date = &item.Date
			height += 4 // 2 newlines, the date, 1 more newline
		}
		height += 1 // newline before the selectable line
		if i == m.summarySelection {
			return height
		}
		height += 1 // the selectable line that's not selected
	}
	return 0
}

func (m HistoryBoxModel) detailsSelectionHeight() int {
	height := 3 // "Details" title line + 2 newlines

	for i := range m.selectedEntries() {
		if i == m.detailSelection {
			return height
		}
		height += 3 // un-selected line + 2 new lines
	}
	return 0
}

var (
	titleStyle               = lipgloss.NewStyle().Bold(true)
	dateStyle                = lipgloss.NewStyle().Bold(true).Foreground(lipgloss.Color("3"))
	summaryItemStyle         = lipgloss.NewStyle()
	selectedItemStyle        = lipgloss.NewStyle().Background(lipgloss.Color("62")).Foreground(lipgloss.Color("230"))
	entryStyle               = lipgloss.NewStyle()
	selectedEntryStyle       = lipgloss.NewStyle().Background(lipgloss.Color("62")).Foreground(lipgloss.Color("230"))
	activeEntryStyle         = lipgloss.NewStyle().Bold(true).Foreground(lipgloss.Color("196"))
	selectedActiveEntryStyle = lipgloss.NewStyle().Background(lipgloss.Color("196")).Foreground(lipgloss.Color("230"))
	descriptionStyle         = lipgloss.NewStyle()
	activeDescriptionStyle   = lipgloss.NewStyle().Background(lipgloss.Color("62")).Foreground(lipgloss.Color("230"))
	filterInfoStyle          = lipgloss.NewStyle().Foreground(lipgloss.Color("248"))
)

// renderSummaryView renders the summary view (level 1) with date headers and client/project summaries
func (m HistoryBoxModel) renderSummaryView(timer TimerBoxModel, clients []queries.Client, projects map[int64][]queries.Project) string {
	content := titleStyle.Render("📝 Recent History")

	if len(m.summaryItems) > 0 {
		filterInfo := m.formatFilterInfo(clients, projects, timer)
		content += "\n\n" + filterInfoStyle.Render(filterInfo)
	}

	var activeKey HistorySummaryKey
	if timer.timerInfo.IsActive {
		activeKey = HistorySummaryKey{
			Date:     dateOnly(timer.timerInfo.StartTime.Local()),
			ClientID: timer.timerInfo.ClientID,
		}
		if timer.timerInfo.ProjectID != nil {
			activeKey.ProjectID = *timer.timerInfo.ProjectID
		}
	}

	if len(m.summaryItems) == 0 {
		return "\n\nNo recent entries found."
	}

	var date *time.Time
	for i, item := range m.summaryItems {
		if date == nil || !date.Equal(item.Date) {
			date = &item.Date
			content += fmt.Sprintf("\n\n%s\n", dateStyle.Render(date.Format("Mon 01/02")))
		}

		style := summaryItemStyle
		if m.summarySelection == i {
			style = selectedItemStyle
		}

		dur := item.TotalDuration
		if item.key() == activeKey {
			dur += timer.currentTime.Sub(timer.timerInfo.StartTime)
		}

		line := fmt.Sprintf("  %s (%s)", m.formatSummaryTitle(item), FormatDuration(dur))
		content += fmt.Sprintf("\n%s", style.Render(line))
	}

	return content
}

func (m HistoryBoxModel) selectedEntries() []queries.TimeEntry {
	if len(m.summaryItems) == 0 {
		return nil
	}
	summary := m.summaryItems[m.summarySelection]
	key := HistorySummaryKey{
		Date:     summary.Date.Local(),
		ClientID: summary.ClientID,
	}
	if summary.ProjectID != nil {
		key.ProjectID = *summary.ProjectID
	}
	return m.entries[key]
}

// renderDetailsView renders the details view (level 2) showing individual entries
func (m HistoryBoxModel) renderDetailsView(timer TimerBoxModel) string {
	summary := m.summaryItems[m.summarySelection]
	clientProject := m.formatSummaryTitle(summary)
	date := summary.Date.Format("Mon 01/02")
	content := titleStyle.Render(fmt.Sprintf("📝 %s on %s", clientProject, date)) + "\n\n"
	entries := m.selectedEntries()

	if len(entries) == 0 {
		return "No entries found for this selection."
	}

	for i, entry := range entries {
		var duration time.Duration
		if entry.EndTime.Valid {
			duration = entry.EndTime.Time.Sub(entry.StartTime)
		} else {
			duration = timer.currentTime.Sub(entry.StartTime)
		}

		startTime := entry.StartTime.Local().Format("3:04 PM")
		var timeRange string
		if entry.EndTime.Valid {
			endTime := entry.EndTime.Time.Local().Format("3:04 PM")
			timeRange = fmt.Sprintf("%s - %s", startTime, endTime)
		} else {
			timeRange = fmt.Sprintf("%s - now", startTime)
		}

		entryLine := fmt.Sprintf("%s (%s)", timeRange, FormatDuration(duration))

		var style lipgloss.Style
		if m.detailSelection == i {
			if !entry.EndTime.Valid {
				style = selectedActiveEntryStyle
			} else {
				style = selectedEntryStyle
			}
		} else {
			if !entry.EndTime.Valid {
				style = activeEntryStyle
			} else {
				style = entryStyle
			}
		}

		content += style.Render(entryLine)

		descStyle := descriptionStyle
		if m.detailSelection == i {
			descStyle = activeDescriptionStyle
		}
		if entry.Description.Valid {
			content += descStyle.Render(fmt.Sprintf("  \"%s\"", entry.Description.String))
		}
		content += "\n"

		// Add spacing between entries
		if i < len(entries)-1 {
			content += "\n"
		}
	}

	return content
}

// formatSummaryTitle creates a display title for a summary item
func (m HistoryBoxModel) formatSummaryTitle(summary HistorySummaryItem) string {
	if summary.ProjectID != nil {
		return fmt.Sprintf("%s / %s", summary.ClientName, *summary.ProjectName)
	}
	return summary.ClientName
}

func dateOnly(t time.Time) time.Time {
	return time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, t.Location())
}

func (m *HistoryBoxModel) changeSelection(forward bool) {
	switch m.viewLevel {
	case HistoryLevelSummary:
		m.changeSummarySelection(forward)
	case HistoryLevelDetails:
		m.changeDetailsSelection(forward)
	}
}

func (m *HistoryBoxModel) changeSelectionToEnd(top bool) {
	switch m.viewLevel {
	case HistoryLevelSummary:
		m.changeSummarySelectionToEnd(top)
	case HistoryLevelDetails:
		m.changeDetailsSelectionToEnd(top)
	}
}

func (m *HistoryBoxModel) changeSummarySelection(forward bool) {
	newIdx := m.summarySelection
	if forward {
		newIdx++
		if newIdx < len(m.summaryItems) {
			m.summarySelection = newIdx
		}
	} else {
		newIdx--
		if newIdx >= 0 {
			m.summarySelection = newIdx
		}
	}
}

func (m *HistoryBoxModel) changeSummarySelectionToEnd(top bool) {
	if top {
		m.summarySelection = 0
	} else {
		m.summarySelection = len(m.summaryItems) - 1
	}
}

func (m *HistoryBoxModel) changeDetailsSelection(forward bool) {
	newIdx := m.detailSelection
	entries := m.selectedEntries()
	if forward {
		newIdx++
		if newIdx < len(entries) {
			m.detailSelection = newIdx
		}
	} else {
		newIdx--
		if newIdx >= 0 {
			m.detailSelection = newIdx
		}
	}
}

func (m *HistoryBoxModel) changeDetailsSelectionToEnd(top bool) {
	if top {
		m.detailSelection = 0
	} else {
		m.detailSelection = len(m.selectedEntries()) - 1
	}
}

func (m HistoryBoxModel) selectedEntry() queries.TimeEntry {
	if m.viewLevel != HistoryLevelDetails {
		panic("fetching selected entry in history summary level")
	}
	return m.selectedEntries()[m.detailSelection]
}

func (m HistoryBoxModel) selection() (string, string, string, *float64) {
	if len(m.summaryItems) == 0 {
		return "", "", "", nil
	}

	item := m.summaryItems[m.summarySelection]

	clientID := strconv.FormatInt(item.ClientID, 10)

	projectID := ""
	if item.ProjectID != nil {
		projectID = strconv.FormatInt(*item.ProjectID, 10)
	}

	description := ""
	var rate *float64
	if m.viewLevel == HistoryLevelDetails {
		entry := m.selectedEntries()[m.detailSelection]
		if entry.Description.Valid {
			description = entry.Description.String
		}
		if entry.BillableRate.Valid {
			cents := entry.BillableRate.Int64
			dollars := float64(cents) / 100
			rate = &dollars
		}
	}

	return clientID, projectID, description, rate
}

func (m *HistoryBoxModel) drillDown() {
	m.viewLevel = HistoryLevelDetails
	m.detailSelection = 0
}

func (m *HistoryBoxModel) drillUp() {
	m.viewLevel = HistoryLevelSummary
}

func (m *HistoryBoxModel) recheckBounds() {
	for m.summarySelection >= len(m.summaryItems) {
		m.summarySelection--
	}
	if m.summarySelection < 0 {
		m.summarySelection = 0
	}

	if m.viewLevel == HistoryLevelDetails {
		ents := m.selectedEntries()
		for m.detailSelection >= len(ents) {
			m.detailSelection--
		}
		if m.detailSelection < 0 {
			m.detailSelection = 0
		}
	}
}

// formatFilterInfo formats the filter criteria line showing client/project, time range, and total duration
func (m HistoryBoxModel) formatFilterInfo(clients []queries.Client, projects map[int64][]queries.Project, timer TimerBoxModel) string {
	var parts []string

	if m.filter.ClientID != nil {
		clientName := ""
		for _, client := range clients {
			if client.ID == *m.filter.ClientID {
				clientName = client.Name
				break
			}
		}

		if m.filter.ProjectID != nil {
			projectName := ""
			if clientProjects, ok := projects[*m.filter.ClientID]; ok {
				for _, project := range clientProjects {
					if project.ID == *m.filter.ProjectID {
						projectName = project.Name
						break
					}
				}
			}
			parts = append(parts, fmt.Sprintf("%s / %s", clientName, projectName))
		} else {
			parts = append(parts, clientName)
		}
	}

	if m.filter.EndDate != nil {
		parts = append(parts, fmt.Sprintf("%s to %s",
			m.filter.StartDate.Format(time.DateOnly),
			m.filter.EndDate.Format(time.DateOnly)))
	} else {
		parts = append(parts, fmt.Sprintf("since %s", m.filter.StartDate.Format(time.DateOnly)))
	}

	// Start with cached total (excluding active timer), then add active timer if it matches filter
	totalDur := m.totalDuration
	if timer.timerInfo.IsActive {
		// Check if active timer matches current filter criteria
		matchesFilter := true

		// Check client filter
		if m.filter.ClientID != nil && *m.filter.ClientID != timer.timerInfo.ClientID {
			matchesFilter = false
		}

		// Check project filter
		if matchesFilter && m.filter.ProjectID != nil {
			if timer.timerInfo.ProjectID == nil || *timer.timerInfo.ProjectID != *m.filter.ProjectID {
				matchesFilter = false
			}
		}

		// Check date filter
		if matchesFilter {
			startTime := timer.timerInfo.StartTime.Local()
			if startTime.Before(m.filter.StartDate) {
				matchesFilter = false
			}
			if matchesFilter && m.filter.EndDate != nil && startTime.After(*m.filter.EndDate) {
				matchesFilter = false
			}
		}

		if matchesFilter {
			totalDur += timer.currentTime.Sub(timer.timerInfo.StartTime)
		}
	}
	parts = append(parts, FormatDuration(totalDur))

	return strings.Join(parts, " - ")
}