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

import (
	"context"
	"fmt"
	"time"

	"punchcard/internal/queries"

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

// BoxType represents the different boxes that can be selected
type BoxType int

const (
	TimerBox BoxType = iota
	ProjectsBox
	HistoryBox
)

func (b BoxType) String() string {
	switch b {
	case TimerBox:
		return "Timer"
	case ProjectsBox:
		return "Clients & Projects"
	case HistoryBox:
		return "History"
	default:
		return "Unknown"
	}
}

func (b BoxType) Next() BoxType {
	switch b {
	case TimerBox:
		return ProjectsBox
	case ProjectsBox:
		return HistoryBox
	case HistoryBox:
		return TimerBox
	}
	return 0
}

func (b BoxType) Prev() BoxType {
	switch b {
	case TimerBox:
		return HistoryBox
	case HistoryBox:
		return ProjectsBox
	case ProjectsBox:
		return TimerBox
	}
	return 0
}

// AppModel is the main model for the TUI application
type AppModel struct {
	ctx     context.Context
	queries *queries.Queries

	selectedBox BoxType
	timerBox    TimerBoxModel
	projectsBox ClientsProjectsModel
	historyBox  HistoryBoxModel
	modalBox    ModalBoxModel

	width  int
	height int

	timeStats TimeStats
	err       error
}

// TimeStats holds time statistics for display (excluding the currently running timer, if any)
type TimeStats struct {
	TodayTotal time.Duration
	WeekTotal  time.Duration
}

// NewApp creates a new TUI application
func NewApp(ctx context.Context, q *queries.Queries) *AppModel {
	return &AppModel{
		ctx:         ctx,
		queries:     q,
		selectedBox: TimerBox,
		timerBox:    NewTimerBoxModel(),
		projectsBox: NewClientsProjectsModel(),
		historyBox:  NewHistoryBoxModel(),
		timeStats:   TimeStats{},
	}
}

// Init initializes the app
func (m AppModel) Init() tea.Cmd {
	return tea.Batch(
		m.refreshCmd,
		doTick(),
	)
}

// TickMsg is sent every second to update timers
type TickMsg time.Time

// doTick returns a command that sends a tick message in a second
func doTick() tea.Cmd {
	return tea.Tick(time.Second, func(t time.Time) tea.Msg {
		return TickMsg(t)
	})
}

// Update handles messages for the app
func (m AppModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
	var cmds []tea.Cmd

	switch msg := msg.(type) {
	case tea.WindowSizeMsg:
		m.width = msg.Width
		m.height = msg.Height

	case tea.KeyMsg:
		cmds = append(cmds, HandleKeyPress(msg, &m))

	case TickMsg:
		m.timerBox.currentTime = time.Time(msg)
		cmds = append(cmds, doTick())

	case dataUpdatedMsg:
		m.timerBox.timerInfo = msg.timerInfo
		m.timerBox.timerInfo.setNames(msg.clients, msg.projects)
		m.timeStats = msg.stats
		m.projectsBox.clients = msg.clients
		m.projectsBox.projects = msg.projects
		m.historyBox.entries = nil
		m.historyBox.regenerateSummaries(msg.clients, msg.projects, msg.entries, m.timerBox.timerInfo)
		m.err = msg.err

	case navigationMsg:
		if msg.Forward {
			m.selectedBox = m.selectedBox.Next()
		} else {
			m.selectedBox = m.selectedBox.Prev()
		}

	case selectionMsg:
		switch m.selectedBox {
		case ProjectsBox:
			m.projectsBox.changeSelection(msg.Forward)
		case HistoryBox:
			m.historyBox.changeSelection(msg.Forward)
		}

	case drillDownMsg:
		if m.selectedBox == HistoryBox {
			m.historyBox.drillDown()
		}

	case drillUpMsg:
		if m.selectedBox == HistoryBox {
			m.historyBox.drillUp()
		}

	case modalClosed:
		m.modalBox.deactivate()

	case openTimeEntryEditor:
		if m.selectedBox == HistoryBox && m.historyBox.viewLevel == HistoryLevelDetails {
			m.openEntryEditor()
		}

	case openModalUnchanged:
		m.modalBox.Active = true

	case openDeleteConfirmation:
		if m.selectedBox == HistoryBox && m.historyBox.viewLevel == HistoryLevelDetails {
			m.modalBox.activate(ModalTypeDeleteConfirmation, m.historyBox.selectedEntry().ID)
		}

	case recheckBounds:
		switch m.selectedBox {
		case HistoryBox:
			m.historyBox.recheckBounds()
		}

	case openCreateClientModal:
		m.modalBox.activate(ModalTypeClient, 0)
		m.modalBox.form.fields[0].Focus()

	case openCreateProjectModal:
		m.modalBox.activateCreateProjectModal(m)

	case openHistoryFilterModal:
		m.openHistoryFilterModal()

	case updateHistoryFilter:
		m.historyBox.filter = HistoryFilter(msg)
		cmds = append(cmds, m.refreshCmd)

	}

	return m, tea.Batch(cmds...)
}

func (m *AppModel) openEntryEditor() {
	m.modalBox.activate(ModalTypeEntry, m.historyBox.selectedEntry().ID)
	m.modalBox.form.fields[0].Focus()

	entry := m.historyBox.selectedEntry()
	m.modalBox.form.fields[0].SetValue(entry.StartTime.Local().Format(time.DateTime))
	if entry.EndTime.Valid {
		m.modalBox.form.fields[1].SetValue(entry.EndTime.Time.Local().Format(time.DateTime))
	}
	for _, client := range m.projectsBox.clients {
		if client.ID == entry.ClientID {
			m.modalBox.form.fields[2].SetValue(client.Name)
			break
		}
	}
	if entry.ProjectID.Valid {
		for _, project := range m.projectsBox.projects[entry.ClientID] {
			if project.ID == entry.ProjectID.Int64 {
				m.modalBox.form.fields[3].SetValue(project.Name)
				break
			}
		}
	}
	if entry.Description.Valid {
		m.modalBox.form.fields[4].SetValue(entry.Description.String)
	}
	if entry.BillableRate.Valid {
		m.modalBox.form.fields[5].SetValue(fmt.Sprintf("%.2f", float64(entry.BillableRate.Int64)/100))
	}
}

func (m *AppModel) openHistoryFilterModal() {
	m.modalBox.activate(ModalTypeHistoryFilter, 0)
	m.modalBox.form.fields[0].Focus()

	// Pre-populate form with current filter values
	filter := m.historyBox.filter

	// Set date range based on current filter
	var dateRangeStr string
	if filter.EndDate == nil {
		// Use "since <date>" format for open-ended ranges
		dateRangeStr = fmt.Sprintf("since %s", filter.StartDate.Format("2006-01-02"))
	} else {
		// Use "YYYY-MM-DD to YYYY-MM-DD" format for bounded ranges
		dateRangeStr = fmt.Sprintf("%s to %s", filter.StartDate.Format("2006-01-02"), filter.EndDate.Format("2006-01-02"))
	}
	m.modalBox.form.fields[0].SetValue(dateRangeStr)

	// Set client filter if present
	if filter.ClientID != nil {
		for _, client := range m.projectsBox.clients {
			if client.ID == *filter.ClientID {
				m.modalBox.form.fields[1].SetValue(client.Name)
				break
			}
		}
	}

	// Set project filter if present
	if filter.ProjectID != nil {
		for _, clientProjects := range m.projectsBox.projects {
			for _, project := range clientProjects {
				if project.ID == *filter.ProjectID {
					m.modalBox.form.fields[2].SetValue(project.Name)
					break
				}
			}
		}
	}
}

// View renders the app
func (m AppModel) View() string {
	if m.width == 0 || m.height == 0 {
		return "Loading..."
	}

	topBarHeight := 1
	bottomBarHeight := 2
	contentHeight := m.height - topBarHeight - bottomBarHeight

	// Timer box top-left
	timerBoxWidth := (m.width / 3)
	timerBoxHeight := (contentHeight / 2)
	if timerBoxWidth < 30 {
		timerBoxWidth = 30
	}

	// Projects box bottom-left
	projectsBoxWidth := timerBoxWidth
	projectsBoxHeight := contentHeight - timerBoxHeight

	// History box right side full height
	historyBoxWidth := m.width - projectsBoxWidth
	historyBoxHeight := contentHeight

	activeDur := m.timerBox.activeTime()
	stats := m.timeStats
	stats.TodayTotal += activeDur
	stats.WeekTotal += activeDur

	topBar := RenderTopBar(m)

	timerBox := m.timerBox.View(timerBoxWidth, timerBoxHeight, m.selectedBox == TimerBox)
	projectsBox := m.projectsBox.View(projectsBoxWidth, projectsBoxHeight, m.selectedBox == ProjectsBox)
	historyBox := m.historyBox.View(historyBoxWidth, historyBoxHeight, m.selectedBox == HistoryBox, m.timerBox)

	leftColumn := lipgloss.JoinVertical(lipgloss.Left, timerBox, projectsBox)
	mainContent := lipgloss.JoinHorizontal(lipgloss.Top, leftColumn, historyBox)

	keyBindings := activeBindings(m.selectedBox, m.historyBox.viewLevel, m.modalBox)
	bottomBar := RenderBottomBar(m, keyBindings, m.err)

	return m.modalBox.RenderCenteredOver(topBar+"\n"+mainContent+"\n"+bottomBar, m)
}

// dataUpdatedMsg is sent when data is updated from the database
type dataUpdatedMsg struct {
	timerInfo TimerInfo
	stats     TimeStats
	clients   []queries.Client
	projects  map[int64][]queries.Project
	entries   []queries.TimeEntry
	err       error
}

// refreshCmd is a command to update all app data
func (m AppModel) refreshCmd() tea.Msg {
	timerInfo, stats, clients, projects, entries, err := getAppData(m.ctx, m.queries, m.historyBox.filter)
	if err != nil {
		msg := dataUpdatedMsg{}
		msg.err = err
		return msg
	}

	return dataUpdatedMsg{
		timerInfo: timerInfo,
		stats:     stats,
		clients:   clients,
		projects:  projects,
		entries:   entries,
		err:       nil,
	}
}

// Run starts the TUI application
func Run(ctx context.Context, q *queries.Queries) error {
	app := NewApp(ctx, q)
	p := tea.NewProgram(app, tea.WithAltScreen())
	_, err := p.Run()
	return err
}