get_budget_usage.go raw
1 package queries
2
3 import (
4 "time"
5
6 "github.com/getAlby/hub/constants"
7 "github.com/getAlby/hub/db"
8 "gorm.io/gorm"
9 )
10
11 func GetBudgetUsageMsat(tx *gorm.DB, appPermission *db.AppPermission) (uint64, error) {
12 var result struct {
13 Sum uint64
14 }
15 err := tx.
16 Table("transactions").
17 Select("SUM(amount_msat + fee_msat + fee_reserve_msat) as sum").
18 Where("app_id = ? AND type = ? AND (state = ? OR state = ?) AND created_at > ?", appPermission.AppId, constants.TRANSACTION_TYPE_OUTGOING, constants.TRANSACTION_STATE_SETTLED, constants.TRANSACTION_STATE_PENDING, getStartOfBudget(appPermission.BudgetRenewal)).Scan(&result).Error
19 if err != nil {
20 return 0, err
21 }
22 return result.Sum, nil
23 }
24
25 func getStartOfBudget(budget_type string) time.Time {
26 now := time.Now()
27 switch budget_type {
28 case constants.BUDGET_RENEWAL_DAILY:
29 // TODO: Use the location of the user, instead of the server
30 return time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location())
31 case constants.BUDGET_RENEWAL_WEEKLY:
32 weekday := now.Weekday()
33 var startOfWeek time.Time
34 if weekday == 0 {
35 startOfWeek = now.AddDate(0, 0, -6)
36 } else {
37 startOfWeek = now.AddDate(0, 0, -int(weekday)+1)
38 }
39 return time.Date(startOfWeek.Year(), startOfWeek.Month(), startOfWeek.Day(), 0, 0, 0, 0, startOfWeek.Location())
40 case constants.BUDGET_RENEWAL_MONTHLY:
41 return time.Date(now.Year(), now.Month(), 1, 0, 0, 0, 0, now.Location())
42 case constants.BUDGET_RENEWAL_YEARLY:
43 return time.Date(now.Year(), time.January, 1, 0, 0, 0, 0, now.Location())
44 default: //"never"
45 return time.Time{}
46 }
47 }
48
49 func GetBudgetRenewsAt(budgetRenewal string) *uint64 {
50 budgetStart := getStartOfBudget(budgetRenewal)
51 switch budgetRenewal {
52 case constants.BUDGET_RENEWAL_DAILY:
53 renewal := uint64(budgetStart.AddDate(0, 0, 1).Unix())
54 return &renewal
55 case constants.BUDGET_RENEWAL_WEEKLY:
56 renewal := uint64(budgetStart.AddDate(0, 0, 7).Unix())
57 return &renewal
58
59 case constants.BUDGET_RENEWAL_MONTHLY:
60 renewal := uint64(budgetStart.AddDate(0, 1, 0).Unix())
61 return &renewal
62
63 case constants.BUDGET_RENEWAL_YEARLY:
64 renewal := uint64(budgetStart.AddDate(1, 0, 0).Unix())
65 return &renewal
66
67 default: //"never"
68 return nil
69 }
70 }
71