-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathweekly_notification.go
72 lines (59 loc) · 1.56 KB
/
weekly_notification.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
package main
import (
"fmt"
"log"
"strings"
"time"
"github.com/pkg/errors"
"gorm.io/gorm"
)
const (
WeeklyNotificationTemplate = `📢 *LateNightCommits Weekly Notifier* 📊
Stats for commits fetched in the last 7 days:
%s
Total commits fetched: %s
ℹ️ Check out the [stats page](https://latenightcommits.com/api/stats) for more\.`
)
func runWeeklyNotification(db *gorm.DB, notifier Notifier) error {
log.Println("📬 Running Weekly Notification job...")
var stats struct {
Daily []struct {
Date time.Time
Count int64
}
Total int64
}
dbSession := db.Session(&gorm.Session{PrepareStmt: true})
err := dbSession.
Raw(`
SELECT COUNT(id) as 'count', DATE(created_at) as 'date'
FROM commits
WHERE created_at >= (CURRENT_DATE - INTERVAL 7 DAY)
GROUP BY date
ORDER BY date DESC
LIMIT 7;
`).Scan(&stats.Daily).Error
if err != nil {
return errors.Wrap(err, "failed to retrieve stats")
}
err = dbSession.Raw(`SELECT COUNT(id) FROM commits;`).Scan(&stats.Total).Error
if err != nil {
return errors.Wrap(err, "failed to retrieve stats total")
}
var dailyMessageBuilder strings.Builder
for _, s := range stats.Daily {
dailyMessageBuilder.WriteString(
fmt.Sprintf("📅 %s: %s\n", s.Date.Format("2006-01-02"), formatNumber(s.Count)),
)
}
msg := fmt.Sprintf(
WeeklyNotificationTemplate,
dailyMessageBuilder.String(),
formatNumber(stats.Total),
)
if err := notifier.Notify(msg); err != nil {
return errors.Wrap(err, "failed to notify")
}
log.Println("Successfully sent daily notification!")
return nil
}