summaryrefslogtreecommitdiff
path: root/internal/tui/history_box.go
blob: a524d6d1f048316fd894709086f8ddf1230be3aa (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
package tui

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

	"punchcard/internal/queries"

	"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
}

type HistoryBoxModel struct {
	viewLevel HistoryViewLevel

	summaryItems     []HistorySummaryItem
	summarySelection int

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

// 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
}

// NewHistoryBoxModel creates a new history box model
func NewHistoryBoxModel() HistoryBoxModel {
	return HistoryBoxModel{}
}

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), entry.ClientID, projectID}
	})

	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,
			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)
	}

	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) string {
	var content string

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

	style := unselectedBoxStyle
	if isSelected {
		style = selectedBoxStyle
	}

	return style.Width(width).Height(height).Render(content)
}

var (
	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"))
)

// renderSummaryView renders the summary view (level 1) with date headers and client/project summaries
func (m HistoryBoxModel) renderSummaryView() string {
	content := "📝 Recent History"

	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("2006/01/02")))
		}

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

		// TODO: add in duration from the currently running timer (requires other data from AppModel)
		line := fmt.Sprintf("  %s (%s)", m.formatSummaryTitle(item), FormatDuration(item.TotalDuration))
		content += fmt.Sprintf("\n%s", style.Render(line))
	}

	return content
}

func (m HistoryBoxModel) selectedEntries() []queries.TimeEntry {
	summary := m.summaryItems[m.summarySelection]
	key := HistorySummaryKey{
		Date:     summary.Date,
		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 {
	content := fmt.Sprintf("📝 Details: %s\n\n", m.formatSummaryTitle(m.summaryItems[m.summarySelection]))
	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 fmt.Sprintf("%s / General work", 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) 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) 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) selection() (string, string, string, *float64) {
	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
}