summaryrefslogtreecommitdiff
path: root/internal/worktime/report.go
blob: 3ffc9838f0d735b928599de37646f8453278f0f3 (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
package worktime

import (
	"fmt"
	"math"
	"sort"
	"strings"
	"time"

	"codeberg.org/snonux/timr/internal/config"
)

const secondsPerHour = int64(3600)

const (
	colorReset = "\033[0m"
	colorCyan  = "\033[36m"
	colorGreen = "\033[32m"
	colorRed   = "\033[31m"
)

// DayReport contains report data for one calendar day.
type DayReport struct {
	Epoch           int64
	DayLabel        string
	Marker          string
	Values          map[string]int64
	RequiredSeconds int64
}

// WeekReport contains report data for one ISO week.
type WeekReport struct {
	WeekLabel                string
	Days                     []DayReport
	Values                   map[string]int64
	RequiredSeconds          int64
	WeeklyBalanceSeconds     int64
	CumulativeBalanceSeconds int64
	BufferSeconds            int64
}

type dayAccumulator struct {
	epoch  int64
	values map[string]int64
}

type weekAccumulator struct {
	weekLabel string
	days      []DayReport
	values    map[string]int64
}

type reportBuildContext struct {
	login             map[string]Entry
	totalBuffer       int64
	cumulativeBalance int64
	reports           []WeekReport
	currentDay        dayAccumulator
	currentWeek       weekAccumulator
	prevDayKey        string
	prevWeekKey       string
}

// BuildReport generates weekly reports from merged worktime entries.
func BuildReport(entries []Entry, cfg config.Config) ([]WeekReport, error) {
	if len(entries) == 0 {
		return []WeekReport{}, nil
	}

	cfg = reportDefaults(cfg)
	sorted := make([]Entry, len(entries))
	copy(sorted, entries)
	sortEntries(sorted)

	bufferFor := stringSet(cfg.BufferFor)
	minusFor := stringSet(cfg.MinusFor)
	weekendDays := stringSet(cfg.WeekendDays)
	plusFor := stringSet(cfg.PlusFor)

	ctx := reportBuildContext{
		login:       map[string]Entry{},
		currentDay:  newDayAccumulator(),
		currentWeek: newWeekAccumulator(),
	}

	for _, entry := range sorted {
		if err := processEntry(&ctx, entry, cfg, plusFor, minusFor, weekendDays, bufferFor); err != nil {
			return nil, err
		}
	}

	finalizeDayIntoWeek(&ctx.currentWeek, ctx.currentDay, minusFor, weekendDays)
	weekReport := finalizeWeek(ctx.currentWeek, cfg, plusFor, minusFor, ctx.totalBuffer, &ctx.cumulativeBalance)
	ctx.reports = append(ctx.reports, weekReport)

	return ctx.reports, nil
}

func processEntry(
	ctx *reportBuildContext,
	entry Entry,
	cfg config.Config,
	plusFor map[string]struct{},
	minusFor map[string]struct{},
	weekendDays map[string]struct{},
	bufferFor map[string]struct{},
) error {
	entryDayKey := dayKey(entry.Epoch)
	entryWeekKey := isoWeekKey(entry.Epoch)

	if ctx.prevDayKey == "" {
		ctx.prevDayKey = entryDayKey
	}
	if ctx.prevWeekKey == "" {
		ctx.prevWeekKey = entryWeekKey
		ctx.currentWeek.weekLabel = weekLabel(entry.Epoch)
	}

	if entryDayKey != ctx.prevDayKey {
		finalizeDayIntoWeek(&ctx.currentWeek, ctx.currentDay, minusFor, weekendDays)
		ctx.currentDay = newDayAccumulator()
		ctx.prevDayKey = entryDayKey
	}

	if entryWeekKey != ctx.prevWeekKey {
		weekReport := finalizeWeek(ctx.currentWeek, cfg, plusFor, minusFor, ctx.totalBuffer, &ctx.cumulativeBalance)
		ctx.reports = append(ctx.reports, weekReport)
		ctx.currentWeek = newWeekAccumulator()
		ctx.currentWeek.weekLabel = weekLabel(entry.Epoch)
		ctx.prevWeekKey = entryWeekKey
	}

	category := normalizeCategory(entry.What)
	if ctx.currentDay.epoch == 0 {
		ctx.currentDay.epoch = entry.Epoch
	}
	if _, ok := ctx.currentDay.values[category]; !ok {
		ctx.currentDay.values[category] = 0
	}

	action := strings.ToLower(strings.TrimSpace(entry.Action))
	switch action {
	case actionAdd:
		ctx.currentDay.values[category] += entry.Value
		if _, ok := bufferFor[category]; ok {
			ctx.totalBuffer += entry.Value
		}
	case actionLogin:
		if _, ok := ctx.login[category]; ok {
			return fmt.Errorf("already logged in for %q at epoch %d", category, entry.Epoch)
		}
		ctx.login[category] = entry
	case actionLogout:
		startEntry, ok := ctx.login[category]
		if !ok {
			return fmt.Errorf("logout without login for %q at epoch %d", category, entry.Epoch)
		}
		ctx.currentDay.values[category] += entry.Epoch - startEntry.Epoch
		delete(ctx.login, category)
	default:
		return fmt.Errorf("unknown action %q at epoch %d", entry.Action, entry.Epoch)
	}

	return nil
}

// FormatReport renders week/day reports as text. Colors can be toggled.
func FormatReport(weeks []WeekReport, verbose, color bool) string {
	var out strings.Builder

	for weekIdx := range weeks {
		week := &weeks[weekIdx]
		for dayIdx := range week.Days {
			day := &week.Days[dayIdx]
			out.WriteString("   ")
			out.WriteString(day.Marker)
			out.WriteString(" ")
			out.WriteString(day.DayLabel)
			out.WriteString(":")
			out.WriteString(formatData(day.Values, 0, day.Epoch, verbose, color))
			out.WriteString("\n")
		}

		out.WriteString("================================================\n")
		weekValues := cloneValueMap(week.Values)
		weekValues["balance"] = week.CumulativeBalanceSeconds
		out.WriteString(formatData(weekValues, week.BufferSeconds, 0, false, color))
		out.WriteString("\n\n\n")
	}

	return out.String()
}

func finalizeDayIntoWeek(week *weekAccumulator, day dayAccumulator, minusFor map[string]struct{}, weekendDays map[string]struct{}) {
	if day.epoch == 0 {
		return
	}

	for key, value := range day.values {
		week.values[key] += value
	}

	dayValues := cloneValueMap(day.values)
	for category := range minusFor {
		if value, ok := dayValues[category]; ok {
			dayValues["work"] -= value
		}
	}

	marker := dayMarker(day.epoch, day.values, weekendDays)
	required := int64(8) * secondsPerHour
	if marker == "*" {
		required = 0
	}

	week.days = append(week.days, DayReport{
		Epoch:           day.epoch,
		DayLabel:        dayLabel(day.epoch),
		Marker:          marker,
		Values:          dayValues,
		RequiredSeconds: required,
	})
}

func finalizeWeek(
	week weekAccumulator,
	cfg config.Config,
	plusFor map[string]struct{},
	minusFor map[string]struct{},
	totalBuffer int64,
	cumulativeBalance *int64,
) WeekReport {
	values := cloneValueMap(week.values)

	required := int64(math.Round(cfg.WeekWorkHours * float64(secondsPerHour)))
	for category := range plusFor {
		required -= values[category]
	}

	work := values["work"]
	for category := range minusFor {
		work -= values[category]
	}
	values["work"] = work

	weeklyBalance := work - required
	*cumulativeBalance += weeklyBalance

	return WeekReport{
		WeekLabel:                week.weekLabel,
		Days:                     week.days,
		Values:                   values,
		RequiredSeconds:          required,
		WeeklyBalanceSeconds:     weeklyBalance,
		CumulativeBalanceSeconds: *cumulativeBalance,
		BufferSeconds:            totalBuffer,
	}
}

func formatData(values map[string]int64, bufferSeconds int64, epoch int64, verbose, color bool) string {
	keys := []string{"balance", "work", "lunch", "off", "sick", "bank", "pet", "selfdevelopment"}
	var out strings.Builder

	for _, key := range keys {
		value, hasValue := values[key]
		if !hasValue && key != "work" {
			continue
		}
		if !hasValue {
			value = 0
		}
		if value == 0 && key != "work" {
			continue
		}

		out.WriteString(" ")
		out.WriteString(colorizeLabel(key, color))
		out.WriteString(":")
		out.WriteString(colorizeValue(formatHours(value), value, color))
		out.WriteString("h")
	}

	if bufferSeconds != 0 {
		out.WriteString(" ")
		out.WriteString(colorizeLabel("buffer", color))
		out.WriteString(":")
		out.WriteString(colorizeValue(formatHours(bufferSeconds), bufferSeconds, color))
		out.WriteString("h")
	}

	if verbose && epoch > 0 {
		out.WriteString(fmt.Sprintf(" epoch:%d(%s)", epoch, time.Unix(epoch, 0)))
	}

	return out.String()
}

func dayMarker(epoch int64, values map[string]int64, weekendDays map[string]struct{}) string {
	if values["off"] >= 8*secondsPerHour {
		return "*"
	}
	if values["bank"] >= 8*secondsPerHour {
		return "*"
	}

	weekday := time.Unix(epoch, 0).Format("Mon")
	if _, ok := weekendDays[weekday]; ok {
		return "*"
	}

	return " "
}

func dayLabel(epoch int64) string {
	t := time.Unix(epoch, 0)
	_, week := t.ISOWeek()
	return fmt.Sprintf("%s %s %02d", t.Format("Mon"), t.Format("20060102"), week)
}

func dayKey(epoch int64) string {
	t := time.Unix(epoch, 0)
	return t.Format("2006-01-02")
}

func weekLabel(epoch int64) string {
	_, week := time.Unix(epoch, 0).ISOWeek()
	return fmt.Sprintf("%02d", week)
}

func isoWeekKey(epoch int64) string {
	year, week := time.Unix(epoch, 0).ISOWeek()
	return fmt.Sprintf("%d-%02d", year, week)
}

func reportDefaults(cfg config.Config) config.Config {
	defaults := config.Default()

	if cfg.WeekWorkHours == 0 {
		cfg.WeekWorkHours = defaults.WeekWorkHours
	}
	if cfg.PlusFor == nil {
		cfg.PlusFor = defaults.PlusFor
	}
	if cfg.WeekendDays == nil {
		cfg.WeekendDays = defaults.WeekendDays
	}
	if cfg.MinusFor == nil {
		cfg.MinusFor = defaults.MinusFor
	}
	if cfg.BufferFor == nil {
		cfg.BufferFor = defaults.BufferFor
	}

	return cfg
}

func formatHours(seconds int64) string {
	return fmt.Sprintf("%0.2f", float64(seconds)/float64(secondsPerHour))
}

func colorizeLabel(label string, color bool) string {
	if !color {
		return label
	}
	return colorCyan + label + colorReset
}

func colorizeValue(value string, raw int64, color bool) string {
	if !color {
		return value
	}

	switch {
	case raw < 0:
		return colorRed + value + colorReset
	case raw > 0:
		return colorGreen + value + colorReset
	default:
		return value
	}
}

func cloneValueMap(values map[string]int64) map[string]int64 {
	cloned := make(map[string]int64, len(values))
	for key, value := range values {
		cloned[key] = value
	}
	return cloned
}

func stringSet(items []string) map[string]struct{} {
	set := make(map[string]struct{}, len(items))
	for _, item := range items {
		trimmed := strings.TrimSpace(item)
		if trimmed == "" {
			continue
		}
		set[trimmed] = struct{}{}
	}
	return set
}

func newDayAccumulator() dayAccumulator {
	return dayAccumulator{
		values: map[string]int64{},
	}
}

func newWeekAccumulator() weekAccumulator {
	return weekAccumulator{
		values: map[string]int64{},
	}
}

func sortedWeekReports(reports []WeekReport) {
	sort.SliceStable(reports, func(i, j int) bool {
		if reports[i].WeekLabel != reports[j].WeekLabel {
			return reports[i].WeekLabel < reports[j].WeekLabel
		}
		if len(reports[i].Days) == 0 || len(reports[j].Days) == 0 {
			return len(reports[i].Days) < len(reports[j].Days)
		}
		return reports[i].Days[0].Epoch < reports[j].Days[0].Epoch
	})
}