forked from coaidev/coai
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinvitation.go
95 lines (85 loc) · 2.05 KB
/
invitation.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
package admin
import (
"chat/globals"
"chat/utils"
"database/sql"
"errors"
"fmt"
"math"
"strings"
)
func GetInvitationPagination(db *sql.DB, page int64) PaginationForm {
var invitations []interface{}
var total int64
if err := globals.QueryRowDb(db, `
SELECT COUNT(*) FROM invitation
`).Scan(&total); err != nil {
return PaginationForm{
Status: false,
Message: err.Error(),
}
}
rows, err := globals.QueryDb(db, `
SELECT code, quota, type, used, updated_at FROM invitation
ORDER BY id DESC LIMIT ? OFFSET ?
`, pagination, page*pagination)
if err != nil {
return PaginationForm{
Status: false,
Message: err.Error(),
}
}
for rows.Next() {
var invitation InvitationData
var date []uint8
if err := rows.Scan(&invitation.Code, &invitation.Quota, &invitation.Type, &invitation.Used, &date); err != nil {
return PaginationForm{
Status: false,
Message: err.Error(),
}
}
invitation.UpdatedAt = utils.ConvertTime(date).Format("2006-01-02 15:04:05")
invitations = append(invitations, invitation)
}
return PaginationForm{
Status: true,
Total: int(math.Ceil(float64(total) / float64(pagination))),
Data: invitations,
}
}
func NewInvitationCode(db *sql.DB, code string, quota float32, t string) error {
_, err := globals.ExecDb(db, `
INSERT INTO invitation (code, quota, type)
VALUES (?, ?, ?)
`, code, quota, t)
return err
}
func GenerateInvitations(db *sql.DB, num int, quota float32, t string) InvitationGenerateResponse {
arr := make([]string, 0)
idx := 0
retry := 0
for idx < num {
code := fmt.Sprintf("%s-%s", t, utils.GenerateChar(24))
if err := NewInvitationCode(db, code, quota, t); err != nil {
// ignore duplicate code
if errors.Is(err, sql.ErrNoRows) {
continue
}
if retry < 100 && strings.Contains(err.Error(), "Duplicate entry") {
retry++
continue
}
retry = 0
return InvitationGenerateResponse{
Status: false,
Message: err.Error(),
}
}
arr = append(arr, code)
idx++
}
return InvitationGenerateResponse{
Status: true,
Data: arr,
}
}