-
Notifications
You must be signed in to change notification settings - Fork 0
/
report_window.go
345 lines (327 loc) · 9.64 KB
/
report_window.go
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
package windows
import (
"encoding/csv"
"fmt"
"reflect"
"time"
"fyne.io/fyne/v2"
"fyne.io/fyne/v2/container"
"fyne.io/fyne/v2/data/binding"
"fyne.io/fyne/v2/dialog"
"fyne.io/fyne/v2/theme"
"fyne.io/fyne/v2/widget"
"github.com/neflyte/timetracker/lib/constants"
tterrors "github.com/neflyte/timetracker/lib/errors"
"github.com/neflyte/timetracker/lib/logger"
"github.com/neflyte/timetracker/lib/models"
"github.com/neflyte/timetracker/lib/ui/gui/widgets"
"github.com/neflyte/timetracker/lib/ui/icons"
"github.com/rs/zerolog"
)
const (
dateEntryMinWidth = 120.0
columnTaskID = 0
columnTaskSynopsis = 1
columnStartDate = 2
columnDuration = 3
)
var (
tableColumnWidths = []float32{75, 250, 100, 100}
tableHeader = []string{"Task ID", "Synopsis", "Started On", "Duration"}
csvTableHeader = []string{"task_id", "synopsis", "started_on", "duration"}
)
type reportWindow interface {
windowBase
Hide()
Show()
}
type reportWindowData struct {
log zerolog.Logger
startDateBinding binding.String
endDateBinding binding.String
fyne.Window
container *fyne.Container
endDateLabel *widget.Label
startDateEntry *widgets.MinWidthEntry
headerContainer *fyne.Container
startDateLabel *widget.Label
runReportButton *widget.Button
exportButton *widget.Button
resultTable *widget.Table
endDateEntry *widgets.MinWidthEntry
taskReport models.TaskReport
tableColumns int
tableRows int
}
func newReportWindow(app fyne.App) reportWindow {
log := logger.GetLogger("newReportWindow")
newWindow := &reportWindowData{
Window: app.NewWindow("Task Report"), // i18n
log: logger.GetStructLogger("reportWindowData"),
startDateBinding: binding.NewString(),
endDateBinding: binding.NewString(),
tableRows: 0,
tableColumns: 0,
taskReport: make([]models.TaskReportData, 0),
}
err := newWindow.Init()
if err != nil {
log.Err(err).
Msg("error initializing window")
}
return newWindow
}
// Init initializes the window
func (w *reportWindowData) Init() error {
// Header container
w.startDateEntry = widgets.NewMinWidthEntry(dateEntryMinWidth, "YYYY-MM-DD") // l10n
w.startDateEntry.Bind(w.startDateBinding)
w.startDateEntry.Validator = w.dateValidator
w.endDateEntry = widgets.NewMinWidthEntry(dateEntryMinWidth, "YYYY-MM-DD") // l10n
w.endDateEntry.Bind(w.endDateBinding)
w.endDateEntry.Validator = w.dateValidator
w.startDateLabel = widget.NewLabel("Start date:") // i18n
w.endDateLabel = widget.NewLabel("End date:") // i18n
w.runReportButton = widget.NewButtonWithIcon("RUN", theme.MediaPlayIcon(), w.doRunReport) // i18n
w.exportButton = widget.NewButtonWithIcon("EXPORT", theme.DownloadIcon(), w.doExport) // i18n
w.exportButton.Disable() // Initialize the export button in a disabled state
w.headerContainer = container.NewBorder(
nil, nil,
container.NewHBox(
w.startDateLabel, w.startDateEntry,
w.endDateLabel, w.endDateEntry,
),
container.NewHBox(
w.runReportButton, w.exportButton,
),
)
// Result table
w.resultTable = widget.NewTable(w.resultTableLength, w.resultTableCreate, w.resultTableUpdate)
// Set table column widths
for idx, colWidth := range tableColumnWidths {
w.resultTable.SetColumnWidth(idx, colWidth)
}
w.container = container.NewPadded(
container.NewBorder(
w.headerContainer, nil, nil, nil,
w.resultTable,
),
)
w.Window.SetContent(w.container)
w.Window.SetIcon(icons.IconV2)
w.Window.SetCloseIntercept(w.Window.Hide)
w.Window.Resize(minimumWindowSize)
w.Window.Canvas().Focus(w.startDateEntry)
return nil
}
// Show displays the window and focuses the start date entry widget
func (w *reportWindowData) Show() {
w.Window.Canvas().Focus(w.startDateEntry)
w.Window.Show()
}
func (w *reportWindowData) Hide() {
w.Window.Hide()
}
func (w *reportWindowData) resultTableLength() (int, int) {
return w.tableRows, w.tableColumns
}
func (w *reportWindowData) resultTableCreate() fyne.CanvasObject {
return widget.NewLabel("")
}
func (w *reportWindowData) resultTableUpdate(cell widget.TableCellID, object fyne.CanvasObject) {
var (
log = logger.GetFuncLogger(w.log, "resultTableUpdate")
labelText string
)
label, isLabel := object.(*widget.Label)
if !isLabel {
log.Error().
Str("unexpectedType", reflect.TypeOf(object).String()).
Msg("expected *widget.Label but got unexpected type")
return
}
if cell.Row == 0 {
labelText = tableHeader[cell.Col]
label.TextStyle.Bold = true
} else {
taskReportData := w.taskReport[cell.Row-1]
switch cell.Col {
case columnTaskID:
labelText = fmt.Sprintf("%d", taskReportData.TaskID)
case columnTaskSynopsis:
labelText = taskReportData.TaskSynopsis
case columnStartDate:
labelText = taskReportData.StartDate.Time.Format(constants.TimestampDateLayout)
case columnDuration:
labelText = taskReportData.Duration().String()
default:
labelText = ""
}
label.TextStyle.Bold = false
}
label.SetText(labelText)
}
func (w *reportWindowData) dateValidator(entry string) error {
if len(entry) == 0 {
return nil
}
_, err := time.Parse(constants.TimestampDateLayout, entry)
return err
}
func (w *reportWindowData) doRunReport() {
log := logger.GetFuncLogger(w.log, "doRunReport")
// Validate date range
dStart, dEnd, err := w.validateDateRange()
if err != nil {
log.Err(err).
Msg("unable to validate date range")
// TODO: Show a more informative error
dialog.NewError(err, w).Show()
return
}
// Disable run button and enable when this function is done
w.exportButton.Disable()
w.runReportButton.Disable()
defer func() {
w.runReportButton.Enable()
if len(w.taskReport) > 0 {
w.exportButton.Enable()
}
w.Window.Content().Refresh()
}()
// Clear table
// - set tableRows to zero
w.tableRows = 0
// - set taskReport to empty
w.taskReport = make(models.TaskReport, 0)
// Run query
timesheet := models.NewTimesheet()
// TODO: Add option to include deleted tasks
reportData, err := timesheet.TaskReport(dStart, dEnd, false)
if err != nil {
// TODO: Show a more informative error
dialog.NewError(err, w).Show()
log.Err(err).
Str("startDate", dStart.Format(constants.TimestampDateLayout)).
Str("endDate", dEnd.Format(constants.TimestampDateLayout)).
Msg("error running task report")
return
}
log.Debug().
Int("count", len(reportData)).
Msgf("loaded records for report")
// Populate table
w.taskReport = reportData.Clone()
w.tableColumns = len(tableHeader)
w.tableRows = len(w.taskReport) + 1
}
func (w *reportWindowData) doExport() {
// Sanity check that there is data to export
if len(w.taskReport) == 0 {
dialog.NewError(
fmt.Errorf("there is no data to export"),
w,
).Show()
return
}
// Show file save dialog
dialog.ShowFileSave(w.exportReportAsCSV, w)
}
func (w *reportWindowData) exportReportAsCSV(writeCloser fyne.URIWriteCloser, dialogErr error) {
log := logger.GetFuncLogger(w.log, "exportReportAsCSV")
if dialogErr != nil {
log.Err(dialogErr).
Msg("error opening CSV file for writing")
return
}
// Write data to file
if writeCloser != nil {
// Collect data
csvData := make([][]string, 0)
csvData = append(csvData, csvTableHeader)
for _, taskReportData := range w.taskReport {
csvData = append(csvData, []string{
fmt.Sprintf("%d", taskReportData.TaskID),
taskReportData.TaskSynopsis,
taskReportData.StartDate.Time.Format(constants.TimestampDateLayout),
taskReportData.Duration().String(),
})
}
csvOut := csv.NewWriter(writeCloser)
defer func() {
csvOut.Flush()
err := writeCloser.Close()
if err != nil {
log.Err(err).
Msg("error closing CSV file")
}
}()
err := csvOut.WriteAll(csvData)
if err != nil {
log.Err(err).
Msg("error exporting data to CSV")
dialog.ShowError(err, w)
return
}
dialog.ShowInformation("Export Successful", "The report data was exported successfully.", w)
}
}
func (w *reportWindowData) validateDateRange() (startDate time.Time, endDate time.Time, err error) {
log := logger.GetFuncLogger(w.log, "validateDateRange")
// Parse the start date
startDateString, err := w.startDateBinding.Get()
if err != nil {
log.Err(err).
Msg("error getting start date from binding")
return
}
startDate, err = time.Parse(constants.TimestampDateLayout, startDateString)
if err != nil {
log.Err(err).
Str("startDate", startDateString).
Str("timestampFormat", constants.TimestampDateLayout).
Msg("error parsing start date timestamp")
err = tterrors.InvalidTaskReportStartDate{
StartDate: startDateString,
Wrapped: err,
}
return
}
// Parse the end date
endDateString, err := w.endDateBinding.Get()
if err != nil {
log.Err(err).
Msg("error getting end date from binding")
return
}
endDate, err = time.Parse(constants.TimestampDateLayout, endDateString)
if err != nil {
log.Err(err).
Str("endDate", endDateString).
Str("timestampFormat", constants.TimestampDateLayout).
Msg("error parsing end date timestamp")
err = tterrors.InvalidTaskReportEndDate{
EndDate: endDateString,
Wrapped: err,
}
return
}
// Check if end date happens before start date
if endDate.Before(startDate) {
log.Error().
Str("startDate", startDate.String()).
Str("endDate", endDate.String()).
Msg("end date cannot happen before start date")
err = tterrors.InvalidTaskReportEndDate{
EndDate: endDateString,
Wrapped: fmt.Errorf(
"end date (%s) cannot happen before start date (%s)",
endDate.Format(constants.TimestampDateLayout),
startDate.Format(constants.TimestampDateLayout),
),
}
return
}
// Date range is valid
return
}