-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmain.go
82 lines (68 loc) · 1.97 KB
/
main.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
package main
import (
"fmt"
"log"
"net/http"
"time"
)
func main() {
err := restorePaymentsTimers()
if err != nil {
log.Fatal(err)
}
archiveOldUsers()
r := newRouter()
log.Fatal(http.ListenAndServe(":8081", r))
}
func restorePaymentsTimers() error {
mysql := MySQL{db: initializeDB()}
users, err := mysql.GetAllUsers()
if err != nil {
return fmt.Errorf("cannot get all users: %v", err)
}
for _, user := range users {
if user.IsDeactivated || user.IsArchived {
continue
}
if user.ExpiredDate.After(time.Now()) {
paymentFunc := createTryToRenewPaymentFunc(mysql, user)
time.AfterFunc(time.Until(user.ExpiredDate), paymentFunc)
// Если оказались внутри периода из трех дней, то ничего страшного не произойдет
// Until вернет отрицательное число и функция выполниться в этот же момент
notificationDate := user.ExpiredDate.AddDate(0, 0, -3)
notificationFunc := createSendNotificationFunc(mysql, user)
time.AfterFunc(time.Until(notificationDate), notificationFunc)
continue
}
tryToRenewPayment(mysql, int(user.ID))
}
return nil
}
func archiveOldUsers() {
mysql := MySQL{db: initializeDB()}
users, err := mysql.GetAllUsers()
if err != nil {
log.Println("cannot get all users: ", err)
return
}
threeMonthsAgo := time.Now().AddDate(0, -3, 0)
for _, user := range users {
payments, err := mysql.GetPaymentsByID(int(user.ID))
if err != nil {
log.Printf("cannot get payments with id=%v: %v", int(user.ID), err)
continue
}
user.Payments = payments
if user.IsArchived || len(user.Payments) <= 0 || user.Paid || user.IsEmployee {
continue
}
if user.Payments[len(user.Payments)-1].Date.Before(threeMonthsAgo) {
err = mysql.ArchiveUserByID(int(user.ID))
if err != nil {
log.Println(err)
}
}
}
nextCheck := time.Now().AddDate(0, 1, 0)
time.AfterFunc(time.Until(nextCheck), archiveOldUsers)
}