-
Notifications
You must be signed in to change notification settings - Fork 0
/
service.go
78 lines (68 loc) · 1.73 KB
/
service.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
package workinghours
import (
"context"
"fmt"
"github.com/ervitis/freelancetools/common"
"github.com/ervitis/freelancetools/credentials"
"google.golang.org/api/calendar/v3"
"google.golang.org/api/option"
"log"
"time"
)
type (
workingHours struct {
calendar *calendar.Service
}
WorkingData struct {
Month string
TotalHours float64
}
IWorkingHours interface {
GetWorkingHoursActualMonth() (*WorkingData, error)
}
)
func New(ctx context.Context, credManager *credentials.Manager) (IWorkingHours, error) {
srv, err := calendar.NewService(ctx, option.WithHTTPClient(credManager.GetClient()))
if err != nil {
return nil, fmt.Errorf("error creating client: %w", err)
}
return &workingHours{
calendar: srv,
}, nil
}
func (w *workingHours) GetWorkingHoursActualMonth() (*WorkingData, error) {
dateSrv := common.NewDateTool()
firstDayMonth, lastDayMonth := dateSrv.GetFirstDayAndLastDayCurrentMonth()
events, err := w.calendar.
Events.
List("primary").
ShowDeleted(false).
SingleEvents(true).
Q("Work hours").
TimeMin(firstDayMonth.Format(time.RFC3339)).
TimeMax(lastDayMonth.AddDate(0, 0, 1).Format(time.RFC3339)).
Do()
if err != nil {
log.Fatalf("Unable to retrieve next ten of the user's events: %v", err)
}
if len(events.Items) == 0 {
log.Println("No upcoming events found.")
return &WorkingData{}, nil
}
totalHours := 0.0
for _, item := range events.Items {
tStart, err := time.Parse(time.RFC3339, item.Start.DateTime)
if err != nil {
panic(err)
}
tEnd, err := time.Parse(time.RFC3339, item.End.DateTime)
if err != nil {
panic(err)
}
totalHours += tEnd.Sub(tStart).Hours()
}
return &WorkingData{
Month: lastDayMonth.Month().String(),
TotalHours: totalHours,
}, nil
}