forked from tonkan/YileTDD
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbudget_service.go
85 lines (70 loc) · 2.07 KB
/
budget_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
79
80
81
82
83
84
85
package YileTDD
import (
"strconv"
"time"
)
type BudgetService struct {
repo IBudgetRepo
}
func (bs BudgetService) Query(start, end time.Time) float64 {
if end.Before(start){
return float64(0)
}
bList := bs.repo.GetAll()
dailyBudgetInMonthList := make(map[string]int, 0)
for _, b := range bList {
d, _ := time.Parse("200601", b.YearMonth())
dailyBudgetInMonthList[b.YearMonth()] = b.Amount()/daysIn(d.Month(),d.Year())
}
validBList := make([]Budget, 0)
startYearMonth := start.Year()*100+int(start.Month())
endYearMonth := end.Year()*100+int(end.Month())
for _, b := range bList {
d, _ := strconv.ParseInt(b.YearMonth(), 10, 0)
if int(d) >= startYearMonth && int(d) <= endYearMonth {
validBList = append(validBList, b)
}
}
budgetAmount := 0
if startYearMonth == endYearMonth{
startDay := start.Day()
endDay := end.Day()
days := endDay-startDay+1
return float64(dailyBudgetInMonthList[start.Format("200601")] * days)
}
for _, b := range validBList {
ym := toYearMonthInt(b.yearMonth)
ymString := strconv.Itoa(ym)
// 起始月份
if startYearMonth == ym {
monthDays := daysIn(start.Month(), start.Year())
days := monthDays - start.Day()+1
monthBudgetDaily := dailyBudgetInMonthList[b.YearMonth()]
budgetStart := days * monthBudgetDaily
budgetAmount += budgetStart
continue
}
// 結束月份
if endYearMonth == ym {
monthBudgetDaily := dailyBudgetInMonthList[b.YearMonth()]
budgetEnd := end.Day() * monthBudgetDaily
budgetAmount += budgetEnd
continue
}
// 完整月份
if b.YearMonth() == ymString {
datetime, _ := time.Parse("200601", b.YearMonth())
monthBudgetDaily := dailyBudgetInMonthList[b.YearMonth()]
budgetInterval := daysIn(datetime.Month(), datetime.Year()) * monthBudgetDaily
budgetAmount += budgetInterval
}
}
return float64(budgetAmount)
}
func toYearMonthInt(yearmonth string) int {
datetime, _ := time.Parse("200601", yearmonth)
return datetime.Year()*100+int(datetime.Month())
}
func daysIn(m time.Month, year int) int {
return time.Date(year, m+1, 0, 0, 0, 0, 0, time.UTC).Day()
}