summaryrefslogtreecommitdiff
path: root/internal/actions/timer.go
blob: d5a85e1e32c74c2df625d4369f8b3a26d6fe4974 (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
package actions

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

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

// PunchIn starts a timer for the specified client/project
// Use empty strings for client/project to use most recent entry
func (a *actions) PunchIn(ctx context.Context, client, project, description string, billableRate *float64, autoUnarchive bool) (*TimerSession, error) {
	// If no client specified, delegate to PunchInMostRecent
	if client == "" && project == "" {
		session, err := a.PunchInMostRecent(ctx, description, billableRate, autoUnarchive)
		if err != nil {
			// Convert "no recent entries" error to "client required" for better UX
			if errors.Is(err, ErrNoRecentEntries) {
				return nil, ErrClientRequired
			}
			return nil, err
		}
		return session, nil
	}

	// Check if there's already an active timer
	activeEntry, err := a.queries.GetActiveTimeEntry(ctx)
	var hasActiveTimer bool
	if err != nil && !errors.Is(err, sql.ErrNoRows) {
		return nil, fmt.Errorf("failed to check for active timer: %w", err)
	}
	hasActiveTimer = (err == nil)

	// Resolve project first (if provided) to get its client
	var projectID sql.NullInt64
	var resolvedProject *queries.Project
	if project != "" {
		proj, err := a.FindProject(ctx, project)
		if err != nil {
			return nil, fmt.Errorf("invalid project: %w", err)
		}
		resolvedProject = proj
		projectID = sql.NullInt64{Int64: proj.ID, Valid: true}
	}

	// Resolve client
	var clientID int64
	var resolvedClient *queries.Client
	if client != "" {
		c, err := a.FindClient(ctx, client)
		if err != nil {
			return nil, fmt.Errorf("invalid client: %w", err)
		}
		resolvedClient = c
		clientID = c.ID

		// Verify project belongs to client if both specified
		if resolvedProject != nil && resolvedProject.ClientID != clientID {
			return nil, fmt.Errorf("%w: project %q does not belong to client %q",
				ErrProjectClientMismatch, project, client)
		}
	} else if resolvedProject != nil {
		// Use project's client
		clientID = resolvedProject.ClientID
		c, err := a.FindClient(ctx, fmt.Sprintf("%d", clientID))
		if err != nil {
			return nil, fmt.Errorf("failed to get client for project: %w", err)
		}
		resolvedClient = c
	} else {
		return nil, ErrClientRequired
	}

	// Check if client is archived
	if resolvedClient.Archived != 0 {
		if !autoUnarchive {
			return nil, ErrArchivedClient
		}
		// Auto-unarchive the client
		if err := a.UnarchiveClient(ctx, resolvedClient.ID); err != nil {
			return nil, fmt.Errorf("failed to unarchive client: %w", err)
		}
	}

	// Check if project is archived
	if resolvedProject != nil && resolvedProject.Archived != 0 {
		if !autoUnarchive {
			return nil, ErrArchivedProject
		}
		// Auto-unarchive the project
		if err := a.UnarchiveProject(ctx, resolvedProject.ID); err != nil {
			return nil, fmt.Errorf("failed to unarchive project: %w", err)
		}
	}

	var stoppedEntryID *int64

	// Check for identical timer if one is active
	if hasActiveTimer {
		if timeEntriesMatch(clientID, projectID, description, billableRate, activeEntry) {
			// No-op: identical timer already active
			return &TimerSession{
				ID:          activeEntry.ID,
				ClientName:  resolvedClient.Name,
				ProjectName: getProjectName(resolvedProject),
				Description: description,
				StartTime:   activeEntry.StartTime,
				EndTime:     nil,
				Duration:    0,
				WasNoOp:     true,
			}, nil
		}

		// Stop the active timer before starting new one
		stoppedEntry, err := a.queries.StopTimeEntry(ctx)
		if err != nil {
			return nil, fmt.Errorf("failed to stop active timer: %w", err)
		}
		stoppedEntryID = &stoppedEntry.ID
	}

	// Create the time entry
	timeEntry, err := a.createTimeEntry(ctx, clientID, projectID, description, billableRate)
	if err != nil {
		return nil, err
	}

	return &TimerSession{
		ID:             timeEntry.ID,
		ClientName:     resolvedClient.Name,
		ProjectName:    getProjectName(resolvedProject),
		Description:    description,
		StartTime:      timeEntry.StartTime,
		EndTime:        nil,
		Duration:       0,
		WasNoOp:        false,
		StoppedEntryID: stoppedEntryID,
	}, nil
}

// PunchInMostRecent starts a timer copying the most recent time entry
func (a *actions) PunchInMostRecent(ctx context.Context, description string, billableRate *float64, autoUnarchive bool) (*TimerSession, error) {
	// Get most recent entry
	mostRecent, err := a.queries.GetMostRecentTimeEntry(ctx)
	if err != nil {
		if errors.Is(err, sql.ErrNoRows) {
			return nil, ErrNoRecentEntries
		}
		return nil, fmt.Errorf("failed to get most recent entry: %w", err)
	}

	// Use description from recent entry if none provided
	finalDescription := description
	if finalDescription == "" && mostRecent.Description.Valid {
		finalDescription = mostRecent.Description.String
	}

	// Get client to check if archived
	client, err := a.FindClient(ctx, fmt.Sprintf("%d", mostRecent.ClientID))
	if err != nil {
		return nil, fmt.Errorf("failed to get client: %w", err)
	}

	// Check if client is archived
	if client.Archived != 0 {
		if !autoUnarchive {
			return nil, ErrArchivedClient
		}
		// Auto-unarchive the client
		if err := a.UnarchiveClient(ctx, client.ID); err != nil {
			return nil, fmt.Errorf("failed to unarchive client: %w", err)
		}
	}

	// Check if project is archived (if exists)
	if mostRecent.ProjectID.Valid {
		project, err := a.FindProject(ctx, fmt.Sprintf("%d", mostRecent.ProjectID.Int64))
		if err == nil && project.Archived != 0 {
			if !autoUnarchive {
				return nil, ErrArchivedProject
			}
			// Auto-unarchive the project
			if err := a.UnarchiveProject(ctx, project.ID); err != nil {
				return nil, fmt.Errorf("failed to unarchive project: %w", err)
			}
		}
	}

	// Check if there's already an active timer
	activeEntry, err := a.queries.GetActiveTimeEntry(ctx)
	var hasActiveTimer bool
	if err != nil && !errors.Is(err, sql.ErrNoRows) {
		return nil, fmt.Errorf("failed to check for active timer: %w", err)
	}
	hasActiveTimer = (err == nil)

	var stoppedEntryID *int64

	// Check for identical timer if one is active
	if hasActiveTimer {
		if timeEntriesMatch(mostRecent.ClientID, mostRecent.ProjectID, finalDescription, billableRate, activeEntry) {
			var projectName string
			if mostRecent.ProjectID.Valid {
				project, _ := a.FindProject(ctx, fmt.Sprintf("%d", mostRecent.ProjectID.Int64))
				if project != nil {
					projectName = project.Name
				}
			}

			// No-op: identical timer already active
			return &TimerSession{
				ID:          activeEntry.ID,
				ClientName:  client.Name,
				ProjectName: projectName,
				Description: finalDescription,
				StartTime:   activeEntry.StartTime,
				EndTime:     nil,
				Duration:    0,
				WasNoOp:     true,
			}, nil
		}

		// Stop the active timer before starting new one
		stoppedEntry, err := a.queries.StopTimeEntry(ctx)
		if err != nil {
			return nil, fmt.Errorf("failed to stop active timer: %w", err)
		}
		stoppedEntryID = &stoppedEntry.ID
	}

	// Create new entry copying from most recent
	timeEntry, err := a.createTimeEntry(ctx, mostRecent.ClientID, mostRecent.ProjectID, finalDescription, billableRate)
	if err != nil {
		return nil, err
	}

	// Get project name if exists
	var projectName string
	if mostRecent.ProjectID.Valid {
		project, err := a.FindProject(ctx, fmt.Sprintf("%d", mostRecent.ProjectID.Int64))
		if err == nil {
			projectName = project.Name
		}
	}

	return &TimerSession{
		ID:             timeEntry.ID,
		ClientName:     client.Name,
		ProjectName:    projectName,
		Description:    finalDescription,
		StartTime:      timeEntry.StartTime,
		EndTime:        nil,
		Duration:       0,
		WasNoOp:        false,
		StoppedEntryID: stoppedEntryID,
	}, nil
}

// PunchOut stops the active timer
func (a *actions) PunchOut(ctx context.Context) (*TimerSession, error) {
	stoppedEntry, err := a.queries.StopTimeEntry(ctx)
	if err != nil {
		if errors.Is(err, sql.ErrNoRows) {
			return nil, ErrNoActiveTimer
		}
		return nil, fmt.Errorf("failed to stop timer: %w", err)
	}

	duration := stoppedEntry.EndTime.Time.Sub(stoppedEntry.StartTime)
	endTime := stoppedEntry.EndTime.Time

	// Get client name
	client, err := a.FindClient(ctx, fmt.Sprintf("%d", stoppedEntry.ClientID))
	if err != nil {
		return nil, fmt.Errorf("failed to get client name: %w", err)
	}

	// Get project name if exists
	var projectName string
	if stoppedEntry.ProjectID.Valid {
		project, err := a.FindProject(ctx, fmt.Sprintf("%d", stoppedEntry.ProjectID.Int64))
		if err == nil {
			projectName = project.Name
		}
	}

	description := ""
	if stoppedEntry.Description.Valid {
		description = stoppedEntry.Description.String
	}

	return &TimerSession{
		ID:          stoppedEntry.ID,
		ClientName:  client.Name,
		ProjectName: projectName,
		Description: description,
		StartTime:   stoppedEntry.StartTime,
		EndTime:     &endTime,
		Duration:    duration,
	}, nil
}

func (a *actions) EditEntry(ctx context.Context, entry queries.TimeEntry) error {
	return a.queries.EditTimeEntry(ctx, queries.EditTimeEntryParams{
		StartTime:   entry.StartTime,
		EndTime:     entry.EndTime,
		Description: entry.Description,
		ClientID:    entry.ClientID,
		ProjectID:   entry.ProjectID,
		HourlyRate:  entry.BillableRate,
		EntryID:     entry.ID,
	})
}

// Helper functions

func (a *actions) createTimeEntry(ctx context.Context, clientID int64, projectID sql.NullInt64, description string, billableRate *float64) (*queries.TimeEntry, error) {
	var descParam sql.NullString
	if description != "" {
		descParam = sql.NullString{String: description, Valid: true}
	}

	var billableRateParam sql.NullInt64
	if billableRate != nil && *billableRate > 0 {
		rate := int64(*billableRate * 100) // Convert dollars to cents
		billableRateParam = sql.NullInt64{Int64: rate, Valid: true}
	}

	timeEntry, err := a.queries.CreateTimeEntry(ctx, queries.CreateTimeEntryParams{
		Description:  descParam,
		ClientID:     clientID,
		ProjectID:    projectID,
		BillableRate: billableRateParam,
	})
	if err != nil {
		return nil, err
	}
	return &timeEntry, nil
}

func getProjectName(project *queries.Project) string {
	if project == nil {
		return ""
	}
	return project.Name
}

// timeEntriesMatch checks if a new time entry would be identical to an active one
// by comparing client ID, project ID, description, and billable rate
func timeEntriesMatch(clientID int64, projectID sql.NullInt64, description string, billableRate *float64, activeEntry queries.TimeEntry) bool {
	// Client must match
	if activeEntry.ClientID != clientID {
		return false
	}

	// Check project ID matching
	if projectID.Valid != activeEntry.ProjectID.Valid {
		// One has a project, the other doesn't
		return false
	}
	if projectID.Valid {
		// Both have projects - compare IDs
		if activeEntry.ProjectID.Int64 != projectID.Int64 {
			return false
		}
	}

	// Check description matching
	if (description != "") != activeEntry.Description.Valid {
		// One has description, the other doesn't
		return false
	}
	if activeEntry.Description.Valid {
		// Both have descriptions - compare strings
		if activeEntry.Description.String != description {
			return false
		}
	}

	// Check billable rate matching
	if billableRate != nil {
		// New entry has explicit rate
		expectedRate := int64(*billableRate * 100) // Convert to cents
		if !activeEntry.BillableRate.Valid || activeEntry.BillableRate.Int64 != expectedRate {
			return false
		}
	}
	// New entry has no explicit rate - for simplicity, we consider them matching
	// regardless of what coalesced rate the active entry might have

	return true
}