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

import (
	"context"
	"database/sql"
	"errors"
	"fmt"
	"slices"
	"time"

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

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

// Maximum content width for large displays - prevents over-stretching
const maxContentWidth = 180

var (
	// Color palette
	colorAccent       = lipgloss.Color("4")   // Blue accent
	colorAccentBright = lipgloss.Color("12")  // Bright blue
	colorTimerActive  = lipgloss.Color("2")   // Green for active timer
	colorTimerText    = lipgloss.Color("10")  // Bright green
	colorDimmed       = lipgloss.Color("242") // Dimmed text
	colorSubtle       = lipgloss.Color("238") // Very subtle borders/separators
	colorFg           = lipgloss.Color("253") // Main foreground
	colorBg           = lipgloss.Color("235") // Slightly lighter than terminal default
	colorBarBg        = lipgloss.Color("236") // Bar background
	colorSelected     = lipgloss.Color("4")   // Selection background
	colorSelectedFg   = lipgloss.Color("15")  // White text on selection
	colorDate         = lipgloss.Color("6")   // Cyan for dates
	colorWarning      = lipgloss.Color("1")   // Red for warnings/errors

	// Styles for the TUI
	topBarStyle = lipgloss.NewStyle().
			Background(colorBarBg).
			Foreground(colorFg).
			Padding(0, 1)

	bottomBarStyle = lipgloss.NewStyle().
			Background(colorBarBg).
			Foreground(colorDimmed)

	// Box styles
	selectedBoxStyle = lipgloss.NewStyle().
				Border(lipgloss.RoundedBorder()).
				BorderForeground(colorAccent).
				Padding(1, 2)

	unselectedBoxStyle = lipgloss.NewStyle().
				Border(lipgloss.RoundedBorder()).
				BorderForeground(colorSubtle).
				Padding(1, 2)

	activeTimerStyle = lipgloss.NewStyle().
				Foreground(colorTimerText).
				Bold(true)

	activeBoxStyle = lipgloss.NewStyle().
			Border(lipgloss.RoundedBorder()).
			BorderForeground(colorTimerActive).
			Padding(1, 2)

	inactiveTimerStyle = lipgloss.NewStyle().
				Foreground(colorDimmed)
)

// FormatDuration formats a duration in a human-readable way
func FormatDuration(d time.Duration) string {
	d = d.Round(time.Second)
	hours := int(d.Hours())
	minutes := int(d.Minutes()) % 60
	seconds := int(d.Seconds()) % 60

	if hours > 0 {
		return fmt.Sprintf("%dh %02dm %02ds", hours, minutes, seconds)
	}
	if minutes > 0 {
		return fmt.Sprintf("%dm %02ds", minutes, seconds)
	}
	return fmt.Sprintf("%ds", seconds)
}

func getContractorInfo(ctx context.Context, q *queries.Queries) (ContractorInfo, error) {
	c, err := q.GetContractor(ctx)
	if err != nil {
		return ContractorInfo{}, err
	}

	return ContractorInfo{
		name:  c.Name,
		label: c.Label,
		email: c.Email,
	}, nil
}

func getTimerInfo(ctx context.Context, q *queries.Queries) (TimerInfo, error) {
	var info TimerInfo

	activeEntry, err := q.GetActiveTimeEntry(ctx)
	if err != nil && !errors.Is(err, sql.ErrNoRows) {
		return info, fmt.Errorf("failed to get active timer: %w", err)
	}
	if err != nil {
		return getMostRecentTimerInfo(ctx, q)
	}

	info.IsActive = true
	info.EntryID = activeEntry.ID
	info.Duration = time.Since(activeEntry.StartTime)
	info.StartTime = activeEntry.StartTime
	info.ClientID = activeEntry.ClientID
	if activeEntry.ProjectID.Valid {
		info.ProjectID = &activeEntry.ProjectID.Int64
	}
	if activeEntry.Description.Valid {
		info.Description = &activeEntry.Description.String
	}
	if activeEntry.BillableRate.Valid {
		rate := float64(activeEntry.BillableRate.Int64) / 100
		info.BillableRate = &rate
	}

	return info, nil
}

func getMostRecentTimerInfo(ctx context.Context, q *queries.Queries) (TimerInfo, error) {
	var info TimerInfo

	entry, err := q.GetMostRecentTimeEntry(ctx)
	if err != nil && !errors.Is(err, sql.ErrNoRows) {
		return info, fmt.Errorf("failed to get most recent timer: %w", err)
	}
	if err != nil {
		return info, nil
	}

	info.IsActive = false
	info.EntryID = entry.ID
	info.Duration = entry.EndTime.Time.Sub(entry.StartTime)
	info.StartTime = entry.StartTime
	info.ClientID = entry.ClientID
	if entry.ProjectID.Valid {
		info.ProjectID = &entry.ProjectID.Int64
	}
	if entry.Description.Valid {
		info.Description = &entry.Description.String
	}
	if entry.BillableRate.Valid {
		rate := float64(entry.BillableRate.Int64) / 100
		info.BillableRate = &rate
	}

	return info, nil
}

// RenderTopBar renders the top bar with view name and time stats
func RenderTopBar(m AppModel, contentWidth int) string {
	leftText := fmt.Sprintf("Punchcard 👊 💳 / %s", m.selectedBox.String())

	today := m.timeStats.TodayTotal
	week := m.timeStats.WeekTotal

	if m.timerBox.timerInfo.IsActive {
		activeTime := m.timerBox.currentTime.Sub(m.timerBox.timerInfo.StartTime)
		today += activeTime
		week += activeTime
	}

	rightText := fmt.Sprintf("today %s  week %s", FormatDuration(today), FormatDuration(week))

	leftStyle := lipgloss.NewStyle().Align(lipgloss.Left)
	rightStyle := lipgloss.NewStyle().Align(lipgloss.Right)

	// Account for the 2 chars of padding in topBarStyle
	innerWidth := contentWidth - 2

	content := lipgloss.JoinHorizontal(
		lipgloss.Top,
		leftStyle.Width(innerWidth/2).Render(leftText),
		rightStyle.Width(innerWidth-innerWidth/2).Render(rightText),
	)

	return topBarStyle.Width(contentWidth).Render(content)
}

// RenderBottomBar renders the bottom bar with key bindings
func RenderBottomBar(m AppModel, bindings []KeyBinding, err error, contentWidth int) string {
	var content string

	keyStyle := lipgloss.NewStyle().
		Background(lipgloss.Color("240")).
		Foreground(lipgloss.Color("15")).
		Padding(0, 1)
	descStyle := lipgloss.NewStyle().
		Background(colorBarBg).
		Foreground(colorDimmed)
	sepStyle := lipgloss.NewStyle().Background(colorBarBg)

	for i, binding := range bindings {
		if binding.Hide {
			continue
		}
		desc := binding.Description(m)
		if desc == "" {
			continue
		}
		if i > 0 {
			content += sepStyle.Render(" ")
		}
		content += keyStyle.Render(binding.Key)
		content += descStyle.Render(" " + desc)
	}

	if err != nil {
		errStyle := lipgloss.NewStyle().Background(colorBarBg).Bold(true).Foreground(colorWarning)
		content += sepStyle.Render("  ")
		content += errStyle.Render(err.Error())
	}

	return bottomBarStyle.Width(contentWidth).Align(lipgloss.Left).Render(content)
}

// GetAppData fetches all data needed for the TUI
func getAppData(
	ctx context.Context,
	q *queries.Queries,
	filter HistoryFilter,
) (
	contractor ContractorInfo,
	info TimerInfo,
	stats TimeStats,
	clients []queries.Client,
	projectsIdx map[int64][]queries.Project,
	entries []queries.TimeEntry,
	err error,
) {
	contractor, err = getContractorInfo(ctx, q)
	if err != nil {
		return
	}

	info, err = getTimerInfo(ctx, q)
	if err != nil {
		return
	}

	clients, err = q.ListAllClients(ctx)
	if err != nil {
		return
	}
	slices.SortFunc(clients, func(a, b queries.Client) int {
		if a.Name <= b.Name {
			return -1
		}
		return 1
	})

	projects, err := q.ListAllProjects(ctx)
	if err != nil {
		return
	}
	slices.SortFunc(projects, func(a, b queries.ListAllProjectsRow) int {
		if a.Name <= b.Name {
			return -1
		}
		return 1
	})
	projectsIdx = make(map[int64][]queries.Project)
	for i := range projects {
		projectsIdx[projects[i].ClientID] = append(
			projectsIdx[projects[i].ClientID],
			queries.Project{
				ID:           projects[i].ID,
				Name:         projects[i].Name,
				ClientID:     projects[i].ClientID,
				BillableRate: projects[i].BillableRate,
				Archived:     projects[i].Archived,
				CreatedAt:    projects[i].CreatedAt,
			},
		)
	}

	// Use filtered query with the provided filter
	var endTimeParam interface{}
	if filter.EndDate != nil {
		endTimeParam = *filter.EndDate
	}

	var clientIDParam interface{}
	if filter.ClientID != nil {
		clientIDParam = *filter.ClientID
	}

	var projectIDParam interface{}
	if filter.ProjectID != nil {
		projectIDParam = *filter.ProjectID
	}

	entries, err = q.GetFilteredTimeEntries(ctx, queries.GetFilteredTimeEntriesParams{
		StartTime: filter.StartDate,
		EndTime:   endTimeParam,
		ClientID:  clientIDParam,
		ProjectID: projectIDParam,
	})
	if err != nil {
		return
	}

	now := time.Now().Local()
	todayY, todayM, todayD := now.Date()
	lastMon := mostRecentMonday(now)
	inDay := true
	for i := range entries {
		e := entries[i]

		if info.IsActive && e.ID == info.EntryID {
			// skip the active timer
			continue
		}

		if inDay {
			y, m, d := e.StartTime.Local().Date()
			if y != todayY || m != todayM || d != todayD {
				inDay = false
			}
		}

		dur := e.EndTime.Time.Sub(e.StartTime)
		if inDay {
			stats.TodayTotal += dur
			stats.WeekTotal += dur
			continue
		}

		mon := mostRecentMonday(e.StartTime)
		if mon != lastMon {
			break
		}
		stats.WeekTotal += dur
	}

	return
}

// RenderContractorPanel renders the full-width contractor info panel.
func RenderContractorPanel(c ContractorInfo, contentWidth int, isSelected bool) string {
	style := unselectedBoxStyle
	if isSelected {
		style = selectedBoxStyle
	}

	// Build content: name, label, email on one line separated by dimmed dividers
	dimStyle := lipgloss.NewStyle().Foreground(colorDimmed)
	nameStyle := lipgloss.NewStyle().Bold(true).Foreground(colorFg)

	var parts []string
	if c.name != "" {
		parts = append(parts, nameStyle.Render(c.name))
	}
	if c.label != "" {
		parts = append(parts, dimStyle.Render(c.label))
	}
	if c.email != "" {
		parts = append(parts, dimStyle.Render(c.email))
	}

	var content string
	if len(parts) == 0 {
		content = dimStyle.Render("No contractor info set. Press 'e' to edit.")
	} else {
		sep := dimStyle.Render("  |  ")
		content = ""
		for i, part := range parts {
			if i > 0 {
				content += sep
			}
			content += part
		}
	}

	// Use padding 0 vertically to keep it compact, override the box style padding
	panelStyle := style.
		Width(contentWidth).
		Padding(0, 2)

	return panelStyle.Render(content)
}

func mostRecentMonday(from time.Time) time.Time {
	d := dateOnly(from.Local())
	dayOffset := time.Duration(d.Weekday()-1) % 7
	return d.Add(-time.Hour * 24 * dayOffset)
}