forked from cgrates/cgrates
/
units_counter.go
97 lines (87 loc) · 2.57 KB
/
units_counter.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
96
97
/*
Rating system designed to be used in VoIP Carriers World
Copyright (C) 2013 ITsysCOM
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>
*/
package engine
import (
"github.com/cgrates/cgrates/cache2go"
"github.com/cgrates/cgrates/utils"
)
// Amount of a trafic of a certain type
type UnitsCounter struct {
Direction string
BalanceId string
// Units float64
Balances BalanceChain // first balance is the general one (no destination)
}
func (uc *UnitsCounter) initBalances(ats []*ActionTrigger) {
uc.Balances = BalanceChain{&Balance{}} // general balance
for _, at := range ats {
acs, err := accountingStorage.GetActions(at.ActionsId, false)
if err != nil {
continue
}
for _, a := range acs {
if a.Balance != nil {
b := a.Balance.Clone()
b.Value = 0
if !uc.Balances.HasBalance(b) {
uc.Balances = append(uc.Balances, b)
}
}
}
}
uc.Balances.Sort()
}
// returns the first balance that has no destination attached
func (uc *UnitsCounter) GetGeneralBalance() *Balance {
if len(uc.Balances) == 0 { // general balance not present for some reson
uc.Balances = append(uc.Balances, &Balance{})
}
return uc.Balances[0]
}
// Adds the units from the received balance to an existing balance if the destination
// is the same or ads the balance to the list if none matches.
func (uc *UnitsCounter) addUnits(amount float64, prefix string) {
counted := false
if prefix != "" {
for _, mb := range uc.Balances {
if !mb.HasDestination() {
continue
}
for _, p := range utils.SplitPrefix(prefix) {
if x, err := cache2go.GetCached(DESTINATION_PREFIX + p); err == nil {
destIds := x.([]string)
for _, dId := range destIds {
if dId == mb.DestinationId {
mb.Value += amount
counted = true
break
}
}
}
if counted {
break
}
}
}
}
if !counted {
// use general balance
b := uc.GetGeneralBalance()
b.Value += amount
}
}
/*func (uc *UnitsCounter) String() string {
return fmt.Sprintf("%s %s %v", uc.BalanceId, uc.Direction, uc.Units)
}*/