diff --git a/apier/accounts.go b/apier/accounts.go index a9bc9d5d8..8e9fb4d34 100644 --- a/apier/accounts.go +++ b/apier/accounts.go @@ -51,7 +51,7 @@ func (self *ApierV1) GetAccountActionPlan(attrs AttrAcntAction, reply *[]*Accoun } for _, ats := range allATs { for _, at := range ats { - if utils.IsSliceMember(at.UserBalanceIds, utils.BalanceKey(attrs.Tenant, attrs.Account, attrs.Direction)) { + if utils.IsSliceMember(at.AccountIds, utils.BalanceKey(attrs.Tenant, attrs.Account, attrs.Direction)) { accountATs = append(accountATs, &AccountActionTiming{Id: at.Id, ActionPlanId: at.Tag, ActionsId: at.ActionsId, NextExecTime: at.GetNextStartTime(time.Now())}) } } @@ -108,7 +108,7 @@ func (self *ApierV1) GetAccountActionTriggers(attrs AttrAcntAction, reply *engin if missing := utils.MissingStructFields(&attrs, []string{"Tenant", "Account", "Direction"}); len(missing) != 0 { return fmt.Errorf("%s:%v", utils.ERR_MANDATORY_IE_MISSING, missing) } - if balance, err := self.AccountDb.GetUserBalance(utils.BalanceKey(attrs.Tenant, attrs.Account, attrs.Direction)); err != nil { + if balance, err := self.AccountDb.GetAccount(utils.BalanceKey(attrs.Tenant, attrs.Account, attrs.Direction)); err != nil { return fmt.Errorf("%s:%s", utils.ERR_SERVER_ERROR, err.Error()) } else { *reply = balance.ActionTriggers @@ -130,7 +130,7 @@ func (self *ApierV1) RemAccountActionTriggers(attrs AttrRemAcntActionTriggers, r } balanceId := utils.BalanceKey(attrs.Tenant, attrs.Account, attrs.Direction) _, err := engine.AccLock.Guard(balanceId, func() (float64, error) { - ub, err := self.AccountDb.GetUserBalance(balanceId) + ub, err := self.AccountDb.GetAccount(balanceId) if err != nil { return 0, err } @@ -144,7 +144,7 @@ func (self *ApierV1) RemAccountActionTriggers(attrs AttrRemAcntActionTriggers, r ub.ActionTriggers = make(engine.ActionTriggerPriotityList, 0) } } - if err := self.AccountDb.SetUserBalance(ub); err != nil { + if err := self.AccountDb.SetAccount(ub); err != nil { return 0, err } return 0, nil @@ -170,10 +170,10 @@ func (self *ApierV1) SetAccount(attr AttrSetAccount, reply *string) error { return fmt.Errorf("%s:%v", utils.ERR_MANDATORY_IE_MISSING, missing) } balanceId := utils.BalanceKey(attr.Tenant, attr.Account, attr.Direction) - var ub *engine.UserBalance + var ub *engine.Account var ats engine.ActionPlan _, err := engine.AccLock.Guard(balanceId, func() (float64, error) { - if bal, _ := self.AccountDb.GetUserBalance(balanceId); bal != nil { + if bal, _ := self.AccountDb.GetAccount(balanceId); bal != nil { ub = bal } else { // Not found in db, create it here if len(attr.Type) == 0 { @@ -181,7 +181,7 @@ func (self *ApierV1) SetAccount(attr AttrSetAccount, reply *string) error { } else if !utils.IsSliceMember([]string{engine.UB_TYPE_POSTPAID, engine.UB_TYPE_PREPAID}, attr.Type) { return 0, fmt.Errorf("%s:%s", utils.ERR_MANDATORY_IE_MISSING, "Type") } - ub = &engine.UserBalance{ + ub = &engine.Account{ Id: balanceId, Type: attr.Type, } @@ -194,11 +194,11 @@ func (self *ApierV1) SetAccount(attr AttrSetAccount, reply *string) error { return 0, err } for _, at := range ats { - at.UserBalanceIds = append(at.UserBalanceIds, balanceId) + at.AccountIds = append(at.AccountIds, balanceId) } } // All prepared, save account - if err := self.AccountDb.SetUserBalance(ub); err != nil { + if err := self.AccountDb.SetAccount(ub); err != nil { return 0, err } return 0, nil diff --git a/apier/apier.go b/apier/apier.go index d0c7d41b4..46a5d255e 100644 --- a/apier/apier.go +++ b/apier/apier.go @@ -62,7 +62,7 @@ func (self *ApierV1) GetRatingPlan(rplnId string, reply *engine.RatingPlan) erro return nil } -type AttrGetUserBalance struct { +type AttrGetAccount struct { Tenant string Account string BalanceType string @@ -70,9 +70,9 @@ type AttrGetUserBalance struct { } // Get balance -func (self *ApierV1) GetUserBalance(attr *AttrGetUserBalance, reply *engine.UserBalance) error { +func (self *ApierV1) GetAccount(attr *AttrGetAccount, reply *engine.Account) error { tag := fmt.Sprintf("%s:%s:%s", attr.Direction, attr.Tenant, attr.Account) - userBalance, err := self.AccountDb.GetUserBalance(tag) + userBalance, err := self.AccountDb.GetAccount(tag) if err != nil { return err } @@ -96,18 +96,18 @@ type AttrAddBalance struct { func (self *ApierV1) AddBalance(attr *AttrAddBalance, reply *string) error { tag := fmt.Sprintf("%s:%s:%s", attr.Direction, attr.Tenant, attr.Account) - if _, err := self.AccountDb.GetUserBalance(tag); err != nil { + if _, err := self.AccountDb.GetAccount(tag); err != nil { // create user balance if not exists - ub := &engine.UserBalance{ + ub := &engine.Account{ Id: tag, } - if err := self.AccountDb.SetUserBalance(ub); err != nil { + if err := self.AccountDb.SetAccount(ub); err != nil { *reply = err.Error() return err } } at := &engine.ActionTiming{ - UserBalanceIds: []string{tag}, + AccountIds: []string{tag}, } if attr.Direction == "" { @@ -149,8 +149,8 @@ type AttrExecuteAction struct { func (self *ApierV1) ExecuteAction(attr *AttrExecuteAction, reply *string) error { tag := fmt.Sprintf("%s:%s:%s", attr.Direction, attr.Tenant, attr.Account) at := &engine.ActionTiming{ - UserBalanceIds: []string{tag}, - ActionsId: attr.ActionsId, + AccountIds: []string{tag}, + ActionsId: attr.ActionsId, } if err := at.Execute(); err != nil { @@ -397,14 +397,14 @@ func (self *ApierV1) AddTriggeredAction(attr AttrAddActionTrigger, reply *string tag := utils.BalanceKey(attr.Tenant, attr.Account, attr.Direction) _, err := engine.AccLock.Guard(tag, func() (float64, error) { - userBalance, err := self.AccountDb.GetUserBalance(tag) + userBalance, err := self.AccountDb.GetAccount(tag) if err != nil { return 0, err } userBalance.ActionTriggers = append(userBalance.ActionTriggers, at) - if err = self.AccountDb.SetUserBalance(userBalance); err != nil { + if err = self.AccountDb.SetAccount(userBalance); err != nil { return 0, err } return 0, nil diff --git a/apier/apier_local_test.go b/apier/apier_local_test.go index c28193f7d..fd11c450c 100644 --- a/apier/apier_local_test.go +++ b/apier/apier_local_test.go @@ -1115,42 +1115,42 @@ func TestApierRemActionTiming(t *testing.T) { } } -// Test here GetUserBalance -func TestApierGetUserBalance(t *testing.T) { +// Test here GetAccount +func TestApierGetAccount(t *testing.T) { if !*testLocal { return } - var reply *engine.UserBalance - attrs := &AttrGetUserBalance{Tenant: "cgrates.org", Account: "1001", BalanceType: "*monetary", Direction: "*out"} - if err := rater.Call("ApierV1.GetUserBalance", attrs, &reply); err != nil { - t.Error("Got error on ApierV1.GetUserBalance: ", err.Error()) + var reply *engine.Account + attrs := &AttrGetAccount{Tenant: "cgrates.org", Account: "1001", BalanceType: "*monetary", Direction: "*out"} + if err := rater.Call("ApierV1.GetAccount", attrs, &reply); err != nil { + t.Error("Got error on ApierV1.GetAccount: ", err.Error()) } else if reply.BalanceMap[attrs.BalanceType+attrs.Direction].GetTotalValue() != 11.5 { // We expect 11.5 since we have added in the previous test 1.5 t.Errorf("Calling ApierV1.GetBalance expected: 11.5, received: %f", reply) } - attrs = &AttrGetUserBalance{Tenant: "cgrates.org", Account: "dan", BalanceType: "*monetary", Direction: "*out"} - if err := rater.Call("ApierV1.GetUserBalance", attrs, &reply); err != nil { - t.Error("Got error on ApierV1.GetUserBalance: ", err.Error()) + attrs = &AttrGetAccount{Tenant: "cgrates.org", Account: "dan", BalanceType: "*monetary", Direction: "*out"} + if err := rater.Call("ApierV1.GetAccount", attrs, &reply); err != nil { + t.Error("Got error on ApierV1.GetAccount: ", err.Error()) } else if reply.BalanceMap[attrs.BalanceType+attrs.Direction].GetTotalValue() != 1.5 { - t.Errorf("Calling ApierV1.GetUserBalance expected: 1.5, received: %f", reply) + t.Errorf("Calling ApierV1.GetAccount expected: 1.5, received: %f", reply) } // The one we have topped up though executeAction - attrs = &AttrGetUserBalance{Tenant: "cgrates.org", Account: "dan2", BalanceType: "*monetary", Direction: "*out"} - if err := rater.Call("ApierV1.GetUserBalance", attrs, &reply); err != nil { - t.Error("Got error on ApierV1.GetUserBalance: ", err.Error()) + attrs = &AttrGetAccount{Tenant: "cgrates.org", Account: "dan2", BalanceType: "*monetary", Direction: "*out"} + if err := rater.Call("ApierV1.GetAccount", attrs, &reply); err != nil { + t.Error("Got error on ApierV1.GetAccount: ", err.Error()) } else if reply.BalanceMap[attrs.BalanceType+attrs.Direction].GetTotalValue() != 10 { - t.Errorf("Calling ApierV1.GetUserBalance expected: 10, received: %f", reply) + t.Errorf("Calling ApierV1.GetAccount expected: 10, received: %f", reply) } - attrs = &AttrGetUserBalance{Tenant: "cgrates.org", Account: "dan3", BalanceType: "*monetary", Direction: "*out"} - if err := rater.Call("ApierV1.GetUserBalance", attrs, &reply); err != nil { - t.Error("Got error on ApierV1.GetUserBalance: ", err.Error()) + attrs = &AttrGetAccount{Tenant: "cgrates.org", Account: "dan3", BalanceType: "*monetary", Direction: "*out"} + if err := rater.Call("ApierV1.GetAccount", attrs, &reply); err != nil { + t.Error("Got error on ApierV1.GetAccount: ", err.Error()) } else if reply.BalanceMap[attrs.BalanceType+attrs.Direction].GetTotalValue() != 3.6 { - t.Errorf("Calling ApierV1.GetUserBalance expected: 3.6, received: %f", reply) + t.Errorf("Calling ApierV1.GetAccount expected: 3.6, received: %f", reply) } - attrs = &AttrGetUserBalance{Tenant: "cgrates.org", Account: "dan6", BalanceType: "*monetary", Direction: "*out"} - if err := rater.Call("ApierV1.GetUserBalance", attrs, &reply); err != nil { - t.Error("Got error on ApierV1.GetUserBalance: ", err.Error()) + attrs = &AttrGetAccount{Tenant: "cgrates.org", Account: "dan6", BalanceType: "*monetary", Direction: "*out"} + if err := rater.Call("ApierV1.GetAccount", attrs, &reply); err != nil { + t.Error("Got error on ApierV1.GetAccount: ", err.Error()) } else if reply.BalanceMap[attrs.BalanceType+attrs.Direction].GetTotalValue() != 1 { - t.Errorf("Calling ApierV1.GetUserBalance expected: 1, received: %f", reply) + t.Errorf("Calling ApierV1.GetAccount expected: 1, received: %f", reply) } } diff --git a/console/get_balances.go b/console/get_account.go similarity index 88% rename from console/get_balances.go rename to console/get_account.go index a47256d65..28d05a31e 100644 --- a/console/get_balances.go +++ b/console/get_account.go @@ -26,14 +26,14 @@ import ( ) func init() { - commands["get_balances"] = &CmdGetBalances{} + commands["get_account"] = &CmdGetBalances{} } // Commander implementation type CmdGetBalances struct { rpcMethod string - rpcParams *apier.AttrGetUserBalance - rpcResult *engine.UserBalance + rpcParams *apier.AttrGetAccount + rpcResult *engine.Account } // name should be exec's name @@ -43,8 +43,8 @@ func (self *CmdGetBalances) Usage(name string) string { // set param defaults func (self *CmdGetBalances) defaults() error { - self.rpcMethod = "ApierV1.GetUserBalance" - self.rpcParams = &apier.AttrGetUserBalance{BalanceType: engine.CREDIT} + self.rpcMethod = "ApierV1.GetAccount" + self.rpcParams = &apier.AttrGetAccount{BalanceType: engine.CREDIT} self.rpcParams.Direction = "*out" return nil } diff --git a/engine/userbalance.go b/engine/account.go similarity index 91% rename from engine/userbalance.go rename to engine/account.go index 9ba6d880e..8fb931466 100644 --- a/engine/userbalance.go +++ b/engine/account.go @@ -29,8 +29,8 @@ import ( ) const ( - UB_TYPE_POSTPAID = "*postpaid" - UB_TYPE_PREPAID = "*prepaid" + UB_TYPE_POSTPAID = "*unlimited" + UB_TYPE_PREPAID = "*limited" // Direction type INBOUND = "*in" OUTBOUND = "*out" @@ -58,9 +58,9 @@ var ( Structure containing information about user's credit (minutes, cents, sms...).' This can represent a user or a shared group. */ -type UserBalance struct { +type Account struct { Id string - Type string // prepaid-postpaid + Type string // UB_TYPE_POSTPAID/UB_TYPE_PREPAID BalanceMap map[string]BalanceChain UnitCounters []*UnitsCounter ActionTriggers ActionTriggerPriotityList @@ -71,7 +71,7 @@ type UserBalance struct { } // Returns user's available minutes for the specified destination -func (ub *UserBalance) getCreditForPrefix(cd *CallDescriptor) (duration time.Duration, credit float64, balances BalanceChain) { +func (ub *Account) getCreditForPrefix(cd *CallDescriptor) (duration time.Duration, credit float64, balances BalanceChain) { credit = ub.getBalancesForPrefix(cd.Destination, ub.BalanceMap[CREDIT+cd.Direction]).GetTotalValue() balances = ub.getBalancesForPrefix(cd.Destination, ub.BalanceMap[MINUTES+cd.Direction]) @@ -85,7 +85,7 @@ func (ub *UserBalance) getCreditForPrefix(cd *CallDescriptor) (duration time.Dur // Debits some amount of user's specified balance adding the balance if it does not exists. // Returns the remaining credit in user's balance. -func (ub *UserBalance) debitBalanceAction(a *Action) error { +func (ub *Account) debitBalanceAction(a *Action) error { if a == nil { return errors.New("nil minute action!") } @@ -116,7 +116,7 @@ func (ub *UserBalance) debitBalanceAction(a *Action) error { return nil //ub.BalanceMap[id].GetTotalValue() } -func (ub *UserBalance) getBalancesForPrefix(prefix string, balances BalanceChain) BalanceChain { +func (ub *Account) getBalancesForPrefix(prefix string, balances BalanceChain) BalanceChain { var usefulBalances BalanceChain for _, b := range balances { if b.IsExpired() || (ub.Type != UB_TYPE_POSTPAID && b.Value <= 0) { @@ -147,7 +147,7 @@ func (ub *UserBalance) getBalancesForPrefix(prefix string, balances BalanceChain return usefulBalances } -func (ub *UserBalance) debitCreditBalance(cc *CallCost, count bool) error { +func (ub *Account) debitCreditBalance(cc *CallCost, count bool) error { usefulMinuteBalances := ub.getBalancesForPrefix(cc.Destination, ub.BalanceMap[MINUTES+cc.Direction]) usefulMoneyBalances := ub.getBalancesForPrefix(cc.Destination, ub.BalanceMap[CREDIT+cc.Direction]) // debit minutes @@ -232,7 +232,7 @@ CONNECT_FEE: return returnError } -func (ub *UserBalance) GetDefaultMoneyBalance(direction string) *Balance { +func (ub *Account) GetDefaultMoneyBalance(direction string) *Balance { for _, balance := range ub.BalanceMap[CREDIT+direction] { if balance.IsDefault() { return balance @@ -245,7 +245,7 @@ func (ub *UserBalance) GetDefaultMoneyBalance(direction string) *Balance { return defaultBalance } -func (ub *UserBalance) refundIncrements(increments Increments, direction string, count bool) { +func (ub *Account) refundIncrements(increments Increments, direction string, count bool) { for _, increment := range increments { var balance *Balance if increment.GetMinuteBalance() != "" { @@ -273,7 +273,7 @@ func (ub *UserBalance) refundIncrements(increments Increments, direction string, /* Debits some amount of user's specified balance. Returns the remaining credit in user's balance. */ -func (ub *UserBalance) debitGenericBalance(balanceId string, direction string, amount float64, count bool) float64 { +func (ub *Account) debitGenericBalance(balanceId string, direction string, amount float64, count bool) float64 { if count { ub.countUnits(&Action{BalanceType: balanceId, Direction: direction, Balance: &Balance{Value: amount}}) } @@ -282,7 +282,7 @@ func (ub *UserBalance) debitGenericBalance(balanceId string, direction string, a } // Scans the action trigers and execute the actions for which trigger is met -func (ub *UserBalance) executeActionTriggers(a *Action) { +func (ub *Account) executeActionTriggers(a *Action) { ub.ActionTriggers.Sort() for _, at := range ub.ActionTriggers { if at.Executed { @@ -331,7 +331,7 @@ func (ub *UserBalance) executeActionTriggers(a *Action) { // Mark all action trigers as ready for execution // If the action is not nil it acts like a filter -func (ub *UserBalance) resetActionTriggers(a *Action) { +func (ub *Account) resetActionTriggers(a *Action) { for _, at := range ub.ActionTriggers { if !at.Match(a) { continue @@ -342,7 +342,7 @@ func (ub *UserBalance) resetActionTriggers(a *Action) { } // Returns the unit counter that matches the specified action type -func (ub *UserBalance) getUnitCounter(a *Action) *UnitsCounter { +func (ub *Account) getUnitCounter(a *Action) *UnitsCounter { for _, uc := range ub.UnitCounters { direction := a.Direction if direction == "" { @@ -357,7 +357,7 @@ func (ub *UserBalance) getUnitCounter(a *Action) *UnitsCounter { // Increments the counter for the type specified in the received Action // with the actions values -func (ub *UserBalance) countUnits(a *Action) { +func (ub *Account) countUnits(a *Action) { unitsCounter := ub.getUnitCounter(a) // if not found add the counter if unitsCounter == nil { @@ -374,7 +374,7 @@ func (ub *UserBalance) countUnits(a *Action) { } // Create minute counters for all triggered actions that have actions opertating on balances -func (ub *UserBalance) initCounters() { +func (ub *Account) initCounters() { ucTempMap := make(map[string]*UnitsCounter, 2) for _, at := range ub.ActionTriggers { acs, err := accountingStorage.GetActions(at.ActionsId, false) @@ -403,7 +403,7 @@ func (ub *UserBalance) initCounters() { } } -func (ub *UserBalance) CleanExpiredBalancesAndBuckets() { +func (ub *Account) CleanExpiredBalancesAndBuckets() { for key, _ := range ub.BalanceMap { bm := ub.BalanceMap[key] for i := 0; i < len(bm); i++ { diff --git a/engine/userbalance_test.go b/engine/account_test.go similarity index 87% rename from engine/userbalance_test.go rename to engine/account_test.go index d75d08c16..f5d9644ff 100644 --- a/engine/userbalance_test.go +++ b/engine/account_test.go @@ -28,23 +28,6 @@ var ( RET = &Destination{Id: "RET", Prefixes: []string{"0723", "0724"}} ) -func init() { - populateTestActionsForTriggers() -} - -func populateTestActionsForTriggers() { - ats := []*Action{ - &Action{ActionType: "*topup", BalanceType: CREDIT, Direction: OUTBOUND, Balance: &Balance{Value: 10}}, - &Action{ActionType: "*topup", BalanceType: MINUTES, Direction: OUTBOUND, Balance: &Balance{Weight: 20, Value: 10, DestinationId: "NAT"}}, - } - accountingStorage.SetActions("TEST_ACTIONS", ats) - ats1 := []*Action{ - &Action{ActionType: "*topup", BalanceType: CREDIT, Direction: OUTBOUND, Balance: &Balance{Value: 10}, Weight: 20}, - &Action{ActionType: "*reset_prepaid", Weight: 10}, - } - accountingStorage.SetActions("TEST_ACTIONS_ORDER", ats1) -} - func TestBalanceStoreRestore(t *testing.T) { b := &Balance{Value: 14, Weight: 1, Uuid: "test", ExpirationDate: time.Date(2013, time.July, 15, 17, 48, 0, 0, time.UTC)} marsh := NewCodecMsgpackMarshaler() @@ -95,12 +78,12 @@ func TestBalanceChainStoreRestore(t *testing.T) { } } -func TestUserBalanceStorageStoreRestore(t *testing.T) { +func TestAccountStorageStoreRestore(t *testing.T) { b1 := &Balance{Value: 10, Weight: 10, DestinationId: "NAT"} b2 := &Balance{Value: 100, Weight: 20, DestinationId: "RET"} - rifsBalance := &UserBalance{Id: "other", BalanceMap: map[string]BalanceChain{MINUTES + OUTBOUND: BalanceChain{b1, b2}, CREDIT + OUTBOUND: BalanceChain{&Balance{Value: 21}}}} - accountingStorage.SetUserBalance(rifsBalance) - ub1, err := accountingStorage.GetUserBalance("other") + rifsBalance := &Account{Id: "other", BalanceMap: map[string]BalanceChain{MINUTES + OUTBOUND: BalanceChain{b1, b2}, CREDIT + OUTBOUND: BalanceChain{&Balance{Value: 21}}}} + accountingStorage.SetAccount(rifsBalance) + ub1, err := accountingStorage.GetAccount("other") if err != nil || !ub1.BalanceMap[CREDIT+OUTBOUND].Equal(rifsBalance.BalanceMap[CREDIT+OUTBOUND]) { t.Log("UB: ", ub1) t.Errorf("Expected %v was %v", rifsBalance.BalanceMap[CREDIT+OUTBOUND], ub1.BalanceMap[CREDIT+OUTBOUND]) @@ -110,7 +93,7 @@ func TestUserBalanceStorageStoreRestore(t *testing.T) { func TestGetSecondsForPrefix(t *testing.T) { b1 := &Balance{Value: 10, Weight: 10, DestinationId: "NAT"} b2 := &Balance{Value: 100, Weight: 20, DestinationId: "RET"} - ub1 := &UserBalance{Id: "OUT:CUSTOMER_1:rif", BalanceMap: map[string]BalanceChain{MINUTES + OUTBOUND: BalanceChain{b1, b2}, CREDIT + OUTBOUND: BalanceChain{&Balance{Value: 200}}}} + ub1 := &Account{Id: "OUT:CUSTOMER_1:rif", BalanceMap: map[string]BalanceChain{MINUTES + OUTBOUND: BalanceChain{b1, b2}, CREDIT + OUTBOUND: BalanceChain{&Balance{Value: 200}}}} cd := &CallDescriptor{ TOR: "0", Tenant: "vdf", @@ -133,7 +116,7 @@ func TestGetSpecialPricedSeconds(t *testing.T) { b1 := &Balance{Value: 10, Weight: 10, DestinationId: "NAT", RateSubject: "minu"} b2 := &Balance{Value: 100, Weight: 20, DestinationId: "RET", RateSubject: "minu"} - ub1 := &UserBalance{ + ub1 := &Account{ Id: "OUT:CUSTOMER_1:rif", BalanceMap: map[string]BalanceChain{ MINUTES + OUTBOUND: BalanceChain{b1, b2}, @@ -157,12 +140,12 @@ func TestGetSpecialPricedSeconds(t *testing.T) { } } -func TestUserBalanceStorageStore(t *testing.T) { +func TestAccountStorageStore(t *testing.T) { b1 := &Balance{Value: 10, Weight: 10, DestinationId: "NAT"} b2 := &Balance{Value: 100, Weight: 20, DestinationId: "RET"} - rifsBalance := &UserBalance{Id: "other", BalanceMap: map[string]BalanceChain{MINUTES + OUTBOUND: BalanceChain{b1, b2}, CREDIT + OUTBOUND: BalanceChain{&Balance{Value: 21}}}} - accountingStorage.SetUserBalance(rifsBalance) - result, err := accountingStorage.GetUserBalance(rifsBalance.Id) + rifsBalance := &Account{Id: "other", BalanceMap: map[string]BalanceChain{MINUTES + OUTBOUND: BalanceChain{b1, b2}, CREDIT + OUTBOUND: BalanceChain{&Balance{Value: 21}}}} + accountingStorage.SetAccount(rifsBalance) + result, err := accountingStorage.GetAccount(rifsBalance.Id) if err != nil || rifsBalance.Id != result.Id || len(rifsBalance.BalanceMap[MINUTES+OUTBOUND]) < 2 || len(result.BalanceMap[MINUTES+OUTBOUND]) < 2 || !(rifsBalance.BalanceMap[MINUTES+OUTBOUND][0].Equal(result.BalanceMap[MINUTES+OUTBOUND][0])) || @@ -175,7 +158,7 @@ func TestUserBalanceStorageStore(t *testing.T) { func TestDebitMoneyBalance(t *testing.T) { b1 := &Balance{Value: 10, Weight: 10, DestinationId: "NAT"} b2 := &Balance{Value: 100, Weight: 20, DestinationId: "RET"} - rifsBalance := &UserBalance{Id: "other", BalanceMap: map[string]BalanceChain{MINUTES + OUTBOUND: BalanceChain{b1, b2}, CREDIT + OUTBOUND: BalanceChain{&Balance{Value: 21}}}} + rifsBalance := &Account{Id: "other", BalanceMap: map[string]BalanceChain{MINUTES + OUTBOUND: BalanceChain{b1, b2}, CREDIT + OUTBOUND: BalanceChain{&Balance{Value: 21}}}} result := rifsBalance.debitGenericBalance(CREDIT, OUTBOUND, 6, false) if rifsBalance.BalanceMap[CREDIT+OUTBOUND][0].Value != 15 || result != rifsBalance.BalanceMap[CREDIT+OUTBOUND][0].Value { t.Errorf("Expected %v was %v", 15, rifsBalance.BalanceMap[CREDIT+OUTBOUND][0].Value) @@ -185,7 +168,7 @@ func TestDebitMoneyBalance(t *testing.T) { func TestDebitAllMoneyBalance(t *testing.T) { b1 := &Balance{Value: 10, Weight: 10, DestinationId: "NAT"} b2 := &Balance{Value: 100, Weight: 20, DestinationId: "RET"} - rifsBalance := &UserBalance{Id: "other", BalanceMap: map[string]BalanceChain{MINUTES + OUTBOUND: BalanceChain{b1, b2}, CREDIT + OUTBOUND: BalanceChain{&Balance{Value: 21}}}} + rifsBalance := &Account{Id: "other", BalanceMap: map[string]BalanceChain{MINUTES + OUTBOUND: BalanceChain{b1, b2}, CREDIT + OUTBOUND: BalanceChain{&Balance{Value: 21}}}} rifsBalance.debitGenericBalance(CREDIT, OUTBOUND, 21, false) result := rifsBalance.debitGenericBalance(CREDIT, OUTBOUND, 0, false) if rifsBalance.BalanceMap[CREDIT+OUTBOUND][0].Value != 0 || result != rifsBalance.BalanceMap[CREDIT+OUTBOUND][0].Value { @@ -196,7 +179,7 @@ func TestDebitAllMoneyBalance(t *testing.T) { func TestDebitMoreMoneyBalance(t *testing.T) { b1 := &Balance{Value: 10, Weight: 10, DestinationId: "NAT"} b2 := &Balance{Value: 100, Weight: 20, DestinationId: "RET"} - rifsBalance := &UserBalance{Id: "other", BalanceMap: map[string]BalanceChain{MINUTES + OUTBOUND: BalanceChain{b1, b2}, CREDIT + OUTBOUND: BalanceChain{&Balance{Value: 21}}}} + rifsBalance := &Account{Id: "other", BalanceMap: map[string]BalanceChain{MINUTES + OUTBOUND: BalanceChain{b1, b2}, CREDIT + OUTBOUND: BalanceChain{&Balance{Value: 21}}}} result := rifsBalance.debitGenericBalance(CREDIT, OUTBOUND, 22, false) if rifsBalance.BalanceMap[CREDIT+OUTBOUND][0].Value != -1 || result != rifsBalance.BalanceMap[CREDIT+OUTBOUND][0].Value { t.Errorf("Expected %v was %v", -1, rifsBalance.BalanceMap[CREDIT+OUTBOUND][0].Value) @@ -206,7 +189,7 @@ func TestDebitMoreMoneyBalance(t *testing.T) { func TestDebitNegativeMoneyBalance(t *testing.T) { b1 := &Balance{Value: 10, Weight: 10, DestinationId: "NAT"} b2 := &Balance{Value: 100, Weight: 20, DestinationId: "RET"} - rifsBalance := &UserBalance{Id: "other", BalanceMap: map[string]BalanceChain{MINUTES + OUTBOUND: BalanceChain{b1, b2}, CREDIT + OUTBOUND: BalanceChain{&Balance{Value: 21}}}} + rifsBalance := &Account{Id: "other", BalanceMap: map[string]BalanceChain{MINUTES + OUTBOUND: BalanceChain{b1, b2}, CREDIT + OUTBOUND: BalanceChain{&Balance{Value: 21}}}} result := rifsBalance.debitGenericBalance(CREDIT, OUTBOUND, -15, false) if rifsBalance.BalanceMap[CREDIT+OUTBOUND][0].Value != 36 || result != rifsBalance.BalanceMap[CREDIT+OUTBOUND][0].Value { t.Errorf("Expected %v was %v", 36, rifsBalance.BalanceMap[CREDIT+OUTBOUND][0].Value) @@ -227,7 +210,7 @@ func TestDebitCreditZeroSecond(t *testing.T) { }, }, } - rifsBalance := &UserBalance{Id: "other", BalanceMap: map[string]BalanceChain{MINUTES + OUTBOUND: BalanceChain{b1}, CREDIT + OUTBOUND: BalanceChain{&Balance{Value: 21}}}} + rifsBalance := &Account{Id: "other", BalanceMap: map[string]BalanceChain{MINUTES + OUTBOUND: BalanceChain{b1}, CREDIT + OUTBOUND: BalanceChain{&Balance{Value: 21}}}} err := rifsBalance.debitCreditBalance(cc, false) if err != nil { t.Error("Error debiting balance: ", err) @@ -256,7 +239,7 @@ func TestDebitCreditZeroMinute(t *testing.T) { }, }, } - rifsBalance := &UserBalance{Id: "other", BalanceMap: map[string]BalanceChain{ + rifsBalance := &Account{Id: "other", BalanceMap: map[string]BalanceChain{ MINUTES + OUTBOUND: BalanceChain{b1}, CREDIT + OUTBOUND: BalanceChain{&Balance{Value: 21}}, }} @@ -291,7 +274,7 @@ func TestDebitCreditZeroMixedMinute(t *testing.T) { }, }, } - rifsBalance := &UserBalance{Id: "other", BalanceMap: map[string]BalanceChain{ + rifsBalance := &Account{Id: "other", BalanceMap: map[string]BalanceChain{ MINUTES + OUTBOUND: BalanceChain{b1, b2}, CREDIT + OUTBOUND: BalanceChain{&Balance{Value: 21}}, }} @@ -330,7 +313,7 @@ func TestDebitCreditNoCredit(t *testing.T) { }, }, } - rifsBalance := &UserBalance{Id: "other", BalanceMap: map[string]BalanceChain{ + rifsBalance := &Account{Id: "other", BalanceMap: map[string]BalanceChain{ MINUTES + OUTBOUND: BalanceChain{b1}, }} err := rifsBalance.debitCreditBalance(cc, false) @@ -370,7 +353,7 @@ func TestDebitCreditHasCredit(t *testing.T) { }, }, } - rifsBalance := &UserBalance{Id: "other", BalanceMap: map[string]BalanceChain{ + rifsBalance := &Account{Id: "other", BalanceMap: map[string]BalanceChain{ MINUTES + OUTBOUND: BalanceChain{b1}, CREDIT + OUTBOUND: BalanceChain{&Balance{Uuid: "moneya", Value: 50}}, }} @@ -407,7 +390,7 @@ func TestDebitCreditSplitMinutesMoney(t *testing.T) { }, }, } - rifsBalance := &UserBalance{Id: "other", BalanceMap: map[string]BalanceChain{ + rifsBalance := &Account{Id: "other", BalanceMap: map[string]BalanceChain{ MINUTES + OUTBOUND: BalanceChain{b1}, CREDIT + OUTBOUND: BalanceChain{&Balance{Uuid: "moneya", Value: 50}}, }} @@ -449,7 +432,7 @@ func TestDebitCreditMoreTimespans(t *testing.T) { }, }, } - rifsBalance := &UserBalance{Id: "other", BalanceMap: map[string]BalanceChain{ + rifsBalance := &Account{Id: "other", BalanceMap: map[string]BalanceChain{ MINUTES + OUTBOUND: BalanceChain{b1}, }} err := rifsBalance.debitCreditBalance(cc, false) @@ -487,7 +470,7 @@ func TestDebitCreditMoreTimespansMixed(t *testing.T) { }, }, } - rifsBalance := &UserBalance{Id: "other", BalanceMap: map[string]BalanceChain{ + rifsBalance := &Account{Id: "other", BalanceMap: map[string]BalanceChain{ MINUTES + OUTBOUND: BalanceChain{b1, b2}, }} err := rifsBalance.debitCreditBalance(cc, false) @@ -525,7 +508,7 @@ func TestDebitCreditNoConectFeeCredit(t *testing.T) { }, }, } - rifsBalance := &UserBalance{Id: "other", BalanceMap: map[string]BalanceChain{ + rifsBalance := &Account{Id: "other", BalanceMap: map[string]BalanceChain{ MINUTES + OUTBOUND: BalanceChain{b1}, }} err := rifsBalance.debitCreditBalance(cc, false) @@ -558,7 +541,7 @@ func TestDebitCreditMoneyOnly(t *testing.T) { }, }, } - rifsBalance := &UserBalance{Id: "other", BalanceMap: map[string]BalanceChain{ + rifsBalance := &Account{Id: "other", BalanceMap: map[string]BalanceChain{ CREDIT + OUTBOUND: BalanceChain{&Balance{Uuid: "money", Value: 50}}, }} err := rifsBalance.debitCreditBalance(cc, false) @@ -599,7 +582,7 @@ func TestDebitCreditSubjectMinutes(t *testing.T) { }, deductConnectFee: true, } - rifsBalance := &UserBalance{Id: "other", BalanceMap: map[string]BalanceChain{ + rifsBalance := &Account{Id: "other", BalanceMap: map[string]BalanceChain{ MINUTES + OUTBOUND: BalanceChain{b1}, CREDIT + OUTBOUND: BalanceChain{&Balance{Uuid: "moneya", Value: 350}}, }} @@ -641,7 +624,7 @@ func TestDebitCreditSubjectMoney(t *testing.T) { }, deductConnectFee: true, } - rifsBalance := &UserBalance{Id: "other", BalanceMap: map[string]BalanceChain{ + rifsBalance := &Account{Id: "other", BalanceMap: map[string]BalanceChain{ CREDIT + OUTBOUND: BalanceChain{&Balance{Uuid: "moneya", Value: 75, DestinationId: "NAT", RateSubject: "minu"}}, }} err := rifsBalance.debitCreditBalance(cc, false) @@ -678,7 +661,7 @@ func TestDebitCreditSubjectMixed(t *testing.T) { }, deductConnectFee: true, } - rifsBalance := &UserBalance{Id: "other", BalanceMap: map[string]BalanceChain{ + rifsBalance := &Account{Id: "other", BalanceMap: map[string]BalanceChain{ MINUTES + OUTBOUND: BalanceChain{b1}, CREDIT + OUTBOUND: BalanceChain{&Balance{Uuid: "moneya", Value: 150, RateSubject: "minu"}}, }} @@ -727,7 +710,7 @@ func TestDebitCreditSubjectMixedMoreTS(t *testing.T) { }, deductConnectFee: true, } - rifsBalance := &UserBalance{Id: "other", BalanceMap: map[string]BalanceChain{ + rifsBalance := &Account{Id: "other", BalanceMap: map[string]BalanceChain{ MINUTES + OUTBOUND: BalanceChain{b1}, CREDIT + OUTBOUND: BalanceChain{&Balance{Uuid: "moneya", Value: 50, RateSubject: "minu"}}, }} @@ -778,7 +761,7 @@ func TestDebitCreditSubjectMixedPartPay(t *testing.T) { }, deductConnectFee: true, } - rifsBalance := &UserBalance{Id: "other", BalanceMap: map[string]BalanceChain{ + rifsBalance := &Account{Id: "other", BalanceMap: map[string]BalanceChain{ MINUTES + OUTBOUND: BalanceChain{b1}, CREDIT + OUTBOUND: BalanceChain{&Balance{Uuid: "moneya", Value: 75, RateSubject: "minu"}}, }} @@ -809,7 +792,7 @@ func TestDebitCreditSubjectMixedPartPay(t *testing.T) { func TestDebitSMSBalance(t *testing.T) { b1 := &Balance{Value: 10, Weight: 10, DestinationId: "NAT"} b2 := &Balance{Value: 100, Weight: 20, DestinationId: "RET"} - rifsBalance := &UserBalance{Id: "other", BalanceMap: map[string]BalanceChain{MINUTES + OUTBOUND: BalanceChain{b1, b2}, CREDIT + OUTBOUND: BalanceChain{&Balance{Value: 21}}, SMS + OUTBOUND: BalanceChain{&Balance{Value: 100}}}} + rifsBalance := &Account{Id: "other", BalanceMap: map[string]BalanceChain{MINUTES + OUTBOUND: BalanceChain{b1, b2}, CREDIT + OUTBOUND: BalanceChain{&Balance{Value: 21}}, SMS + OUTBOUND: BalanceChain{&Balance{Value: 100}}}} result := rifsBalance.debitGenericBalance(SMS, OUTBOUND, 12, false) if rifsBalance.BalanceMap[SMS+OUTBOUND][0].Value != 88 || result != rifsBalance.BalanceMap[SMS+OUTBOUND][0].Value { t.Errorf("Expected %v was %v", 88, rifsBalance.BalanceMap[SMS+OUTBOUND]) @@ -819,7 +802,7 @@ func TestDebitSMSBalance(t *testing.T) { func TestDebitAllSMSBalance(t *testing.T) { b1 := &Balance{Value: 10, Weight: 10, DestinationId: "NAT"} b2 := &Balance{Value: 100, Weight: 20, DestinationId: "RET"} - rifsBalance := &UserBalance{Id: "other", BalanceMap: map[string]BalanceChain{MINUTES + OUTBOUND: BalanceChain{b1, b2}, CREDIT + OUTBOUND: BalanceChain{&Balance{Value: 21}}, SMS + OUTBOUND: BalanceChain{&Balance{Value: 100}}}} + rifsBalance := &Account{Id: "other", BalanceMap: map[string]BalanceChain{MINUTES + OUTBOUND: BalanceChain{b1, b2}, CREDIT + OUTBOUND: BalanceChain{&Balance{Value: 21}}, SMS + OUTBOUND: BalanceChain{&Balance{Value: 100}}}} result := rifsBalance.debitGenericBalance(SMS, OUTBOUND, 100, false) if rifsBalance.BalanceMap[SMS+OUTBOUND][0].Value != 0 || result != rifsBalance.BalanceMap[SMS+OUTBOUND][0].Value { t.Errorf("Expected %v was %v", 0, rifsBalance.BalanceMap[SMS+OUTBOUND]) @@ -829,7 +812,7 @@ func TestDebitAllSMSBalance(t *testing.T) { func TestDebitMoreSMSBalance(t *testing.T) { b1 := &Balance{Value: 10, Weight: 10, DestinationId: "NAT"} b2 := &Balance{Value: 100, Weight: 20, DestinationId: "RET"} - rifsBalance := &UserBalance{Id: "other", BalanceMap: map[string]BalanceChain{MINUTES + OUTBOUND: BalanceChain{b1, b2}, CREDIT + OUTBOUND: BalanceChain{&Balance{Value: 21}}, SMS + OUTBOUND: BalanceChain{&Balance{Value: 100}}}} + rifsBalance := &Account{Id: "other", BalanceMap: map[string]BalanceChain{MINUTES + OUTBOUND: BalanceChain{b1, b2}, CREDIT + OUTBOUND: BalanceChain{&Balance{Value: 21}}, SMS + OUTBOUND: BalanceChain{&Balance{Value: 100}}}} result := rifsBalance.debitGenericBalance(SMS, OUTBOUND, 110, false) if rifsBalance.BalanceMap[SMS+OUTBOUND][0].Value != -10 || result != rifsBalance.BalanceMap[SMS+OUTBOUND][0].Value { t.Errorf("Expected %v was %v", -10, rifsBalance.BalanceMap[SMS+OUTBOUND][0].Value) @@ -839,15 +822,15 @@ func TestDebitMoreSMSBalance(t *testing.T) { func TestDebitNegativeSMSBalance(t *testing.T) { b1 := &Balance{Value: 10, Weight: 10, DestinationId: "NAT"} b2 := &Balance{Value: 100, Weight: 20, DestinationId: "RET"} - rifsBalance := &UserBalance{Id: "other", BalanceMap: map[string]BalanceChain{MINUTES + OUTBOUND: BalanceChain{b1, b2}, CREDIT + OUTBOUND: BalanceChain{&Balance{Value: 21}}, SMS + OUTBOUND: BalanceChain{&Balance{Value: 100}}}} + rifsBalance := &Account{Id: "other", BalanceMap: map[string]BalanceChain{MINUTES + OUTBOUND: BalanceChain{b1, b2}, CREDIT + OUTBOUND: BalanceChain{&Balance{Value: 21}}, SMS + OUTBOUND: BalanceChain{&Balance{Value: 100}}}} result := rifsBalance.debitGenericBalance(SMS, OUTBOUND, -15, false) if rifsBalance.BalanceMap[SMS+OUTBOUND][0].Value != 115 || result != rifsBalance.BalanceMap[SMS+OUTBOUND][0].Value { t.Errorf("Expected %v was %v", 115, rifsBalance.BalanceMap[SMS+OUTBOUND]) } } -func TestUserBalancedebitBalance(t *testing.T) { - ub := &UserBalance{ +func TestAccountdebitBalance(t *testing.T) { + ub := &Account{ Id: "rif", Type: UB_TYPE_POSTPAID, BalanceMap: map[string]BalanceChain{SMS: BalanceChain{&Balance{Value: 14}}, TRAFFIC: BalanceChain{&Balance{Value: 1204}}, MINUTES + OUTBOUND: BalanceChain{&Balance{Weight: 20, DestinationId: "NAT"}, &Balance{Weight: 10, DestinationId: "RET"}}}, @@ -860,9 +843,9 @@ func TestUserBalancedebitBalance(t *testing.T) { } } -func TestUserBalancedebitBalanceExists(t *testing.T) { +func TestAccountdebitBalanceExists(t *testing.T) { - ub := &UserBalance{ + ub := &Account{ Id: "rif", Type: UB_TYPE_POSTPAID, BalanceMap: map[string]BalanceChain{SMS + OUTBOUND: BalanceChain{&Balance{Value: 14}}, TRAFFIC + OUTBOUND: BalanceChain{&Balance{Value: 1024}}, MINUTES + OUTBOUND: BalanceChain{&Balance{Value: 15, Weight: 20, DestinationId: "NAT"}, &Balance{Weight: 10, DestinationId: "RET"}}}, @@ -875,8 +858,8 @@ func TestUserBalancedebitBalanceExists(t *testing.T) { } } -func TestUserBalanceAddMinuteNil(t *testing.T) { - ub := &UserBalance{ +func TestAccountAddMinuteNil(t *testing.T) { + ub := &Account{ Id: "rif", Type: UB_TYPE_POSTPAID, BalanceMap: map[string]BalanceChain{SMS + OUTBOUND: BalanceChain{&Balance{Value: 14}}, TRAFFIC + OUTBOUND: BalanceChain{&Balance{Value: 1024}}, MINUTES + OUTBOUND: BalanceChain{&Balance{Weight: 20, DestinationId: "NAT"}, &Balance{Weight: 10, DestinationId: "RET"}}}, @@ -887,11 +870,11 @@ func TestUserBalanceAddMinuteNil(t *testing.T) { } } -func TestUserBalanceAddMinutBucketEmpty(t *testing.T) { +func TestAccountAddMinutBucketEmpty(t *testing.T) { mb1 := &Balance{Value: -10, DestinationId: "NAT"} mb2 := &Balance{Value: -10, DestinationId: "NAT"} mb3 := &Balance{Value: -10, DestinationId: "OTHER"} - ub := &UserBalance{} + ub := &Account{} a := &Action{BalanceType: MINUTES, Direction: OUTBOUND, Balance: mb1} ub.debitBalanceAction(a) if len(ub.BalanceMap[MINUTES+OUTBOUND]) != 1 { @@ -909,8 +892,8 @@ func TestUserBalanceAddMinutBucketEmpty(t *testing.T) { } } -func TestUserBalanceExecuteTriggeredActions(t *testing.T) { - ub := &UserBalance{ +func TestAccountExecuteTriggeredActions(t *testing.T) { + ub := &Account{ Id: "TEST_UB", BalanceMap: map[string]BalanceChain{CREDIT + OUTBOUND: BalanceChain{&Balance{Value: 100}}, MINUTES + OUTBOUND: BalanceChain{&Balance{Value: 10, Weight: 20, DestinationId: "NAT"}, &Balance{Weight: 10, DestinationId: "RET"}}}, UnitCounters: []*UnitsCounter{&UnitsCounter{BalanceType: CREDIT, Direction: OUTBOUND, Balances: BalanceChain{&Balance{Value: 1}}}}, @@ -933,8 +916,8 @@ func TestUserBalanceExecuteTriggeredActions(t *testing.T) { } } -func TestUserBalanceExecuteTriggeredActionsBalance(t *testing.T) { - ub := &UserBalance{ +func TestAccountExecuteTriggeredActionsBalance(t *testing.T) { + ub := &Account{ Id: "TEST_UB", BalanceMap: map[string]BalanceChain{CREDIT + OUTBOUND: BalanceChain{&Balance{Value: 100}}, MINUTES + OUTBOUND: BalanceChain{&Balance{Value: 10, Weight: 20, DestinationId: "NAT"}, &Balance{Weight: 10, DestinationId: "RET"}}}, UnitCounters: []*UnitsCounter{&UnitsCounter{BalanceType: CREDIT, Direction: OUTBOUND, Balances: BalanceChain{&Balance{Value: 1}}}}, @@ -946,8 +929,8 @@ func TestUserBalanceExecuteTriggeredActionsBalance(t *testing.T) { } } -func TestUserBalanceExecuteTriggeredActionsOrder(t *testing.T) { - ub := &UserBalance{ +func TestAccountExecuteTriggeredActionsOrder(t *testing.T) { + ub := &Account{ Id: "TEST_UB_OREDER", BalanceMap: map[string]BalanceChain{CREDIT + OUTBOUND: BalanceChain{&Balance{Value: 100}}}, UnitCounters: []*UnitsCounter{&UnitsCounter{BalanceType: CREDIT, Direction: OUTBOUND, Balances: BalanceChain{&Balance{Value: 1}}}}, @@ -960,7 +943,7 @@ func TestUserBalanceExecuteTriggeredActionsOrder(t *testing.T) { } func TestCleanExpired(t *testing.T) { - ub := &UserBalance{ + ub := &Account{ Id: "TEST_UB_OREDER", BalanceMap: map[string]BalanceChain{CREDIT + OUTBOUND: BalanceChain{ &Balance{ExpirationDate: time.Now().Add(10 * time.Second)}, @@ -979,8 +962,8 @@ func TestCleanExpired(t *testing.T) { } } -func TestUserBalanceUnitCounting(t *testing.T) { - ub := &UserBalance{} +func TestAccountUnitCounting(t *testing.T) { + ub := &Account{} ub.countUnits(&Action{BalanceType: CREDIT, Direction: OUTBOUND, Balance: &Balance{Value: 10}}) if len(ub.UnitCounters) != 1 && ub.UnitCounters[0].BalanceType != CREDIT || ub.UnitCounters[0].Balances[0].Value != 10 { t.Error("Error counting units") @@ -991,8 +974,8 @@ func TestUserBalanceUnitCounting(t *testing.T) { } } -func TestUserBalanceUnitCountingOutbound(t *testing.T) { - ub := &UserBalance{} +func TestAccountUnitCountingOutbound(t *testing.T) { + ub := &Account{} ub.countUnits(&Action{BalanceType: CREDIT, Direction: OUTBOUND, Balance: &Balance{Value: 10}}) if len(ub.UnitCounters) != 1 && ub.UnitCounters[0].BalanceType != CREDIT || ub.UnitCounters[0].Balances[0].Value != 10 { t.Error("Error counting units") @@ -1007,8 +990,8 @@ func TestUserBalanceUnitCountingOutbound(t *testing.T) { } } -func TestUserBalanceUnitCountingOutboundInbound(t *testing.T) { - ub := &UserBalance{} +func TestAccountUnitCountingOutboundInbound(t *testing.T) { + ub := &Account{} ub.countUnits(&Action{BalanceType: CREDIT, Balance: &Balance{Value: 10}}) if len(ub.UnitCounters) != 1 && ub.UnitCounters[0].BalanceType != CREDIT || ub.UnitCounters[0].Balances[0].Value != 10 { t.Errorf("Error counting units: %+v", ub.UnitCounters[0]) @@ -1023,8 +1006,8 @@ func TestUserBalanceUnitCountingOutboundInbound(t *testing.T) { } } -func TestUserBalanceRefund(t *testing.T) { - ub := &UserBalance{ +func TestAccountRefund(t *testing.T) { + ub := &Account{ BalanceMap: map[string]BalanceChain{ CREDIT + OUTBOUND: BalanceChain{ &Balance{Uuid: "moneya", Value: 100}, @@ -1050,7 +1033,7 @@ func TestUserBalanceRefund(t *testing.T) { } func TestTopupAction(t *testing.T) { - initialUb, _ := accountingStorage.GetUserBalance("*out:vdf:minu") + initialUb, _ := accountingStorage.GetAccount("*out:vdf:minu") a := &Action{ ActionType: "*topup", BalanceType: CREDIT, @@ -1059,12 +1042,12 @@ func TestTopupAction(t *testing.T) { } at := &ActionTiming{ - UserBalanceIds: []string{"*out:vdf:minu"}, - actions: Actions{a}, + AccountIds: []string{"*out:vdf:minu"}, + actions: Actions{a}, } at.Execute() - afterUb, _ := accountingStorage.GetUserBalance("*out:vdf:minu") + afterUb, _ := accountingStorage.GetAccount("*out:vdf:minu") initialValue := initialUb.BalanceMap[CREDIT+OUTBOUND].GetTotalValue() afterValue := afterUb.BalanceMap[CREDIT+OUTBOUND].GetTotalValue() if initialValue != 50 || afterValue != 75 { @@ -1079,7 +1062,7 @@ func BenchmarkGetSecondForPrefix(b *testing.B) { b1 := &Balance{Value: 10, Weight: 10, DestinationId: "NAT"} b2 := &Balance{Value: 100, Weight: 20, DestinationId: "RET"} - ub1 := &UserBalance{Id: "other", BalanceMap: map[string]BalanceChain{MINUTES + OUTBOUND: BalanceChain{b1, b2}, CREDIT + OUTBOUND: BalanceChain{&Balance{Value: 21}}}} + ub1 := &Account{Id: "other", BalanceMap: map[string]BalanceChain{MINUTES + OUTBOUND: BalanceChain{b1, b2}, CREDIT + OUTBOUND: BalanceChain{&Balance{Value: 21}}}} cd := &CallDescriptor{ Destination: "0723", } @@ -1089,20 +1072,20 @@ func BenchmarkGetSecondForPrefix(b *testing.B) { } } -func BenchmarkUserBalanceStorageStoreRestore(b *testing.B) { +func BenchmarkAccountStorageStoreRestore(b *testing.B) { b1 := &Balance{Value: 10, Weight: 10, DestinationId: "NAT"} b2 := &Balance{Value: 100, Weight: 20, DestinationId: "RET"} - rifsBalance := &UserBalance{Id: "other", BalanceMap: map[string]BalanceChain{MINUTES + OUTBOUND: BalanceChain{b1, b2}, CREDIT + OUTBOUND: BalanceChain{&Balance{Value: 21}}}} + rifsBalance := &Account{Id: "other", BalanceMap: map[string]BalanceChain{MINUTES + OUTBOUND: BalanceChain{b1, b2}, CREDIT + OUTBOUND: BalanceChain{&Balance{Value: 21}}}} for i := 0; i < b.N; i++ { - accountingStorage.SetUserBalance(rifsBalance) - accountingStorage.GetUserBalance(rifsBalance.Id) + accountingStorage.SetAccount(rifsBalance) + accountingStorage.GetAccount(rifsBalance.Id) } } func BenchmarkGetSecondsForPrefix(b *testing.B) { b1 := &Balance{Value: 10, Weight: 10, DestinationId: "NAT"} b2 := &Balance{Value: 100, Weight: 20, DestinationId: "RET"} - ub1 := &UserBalance{Id: "OUT:CUSTOMER_1:rif", BalanceMap: map[string]BalanceChain{MINUTES + OUTBOUND: BalanceChain{b1, b2}, CREDIT + OUTBOUND: BalanceChain{&Balance{Value: 21}}}} + ub1 := &Account{Id: "OUT:CUSTOMER_1:rif", BalanceMap: map[string]BalanceChain{MINUTES + OUTBOUND: BalanceChain{b1, b2}, CREDIT + OUTBOUND: BalanceChain{&Balance{Value: 21}}}} cd := &CallDescriptor{ Destination: "0723", } diff --git a/engine/action.go b/engine/action.go index cd50eb4ed..26ece309c 100644 --- a/engine/action.go +++ b/engine/action.go @@ -67,7 +67,7 @@ const ( UNLIMITED = "*unlimited" ) -type actionTypeFunc func(*UserBalance, *Action) error +type actionTypeFunc func(*Account, *Action) error func getActionFunc(typ string) (actionTypeFunc, bool) { switch typ { @@ -107,38 +107,38 @@ func getActionFunc(typ string) (actionTypeFunc, bool) { return nil, false } -func logAction(ub *UserBalance, a *Action) (err error) { +func logAction(ub *Account, a *Action) (err error) { ubMarshal, _ := json.Marshal(ub) Logger.Info(fmt.Sprintf("Threshold reached, balance: %s", ubMarshal)) return } -func resetTriggersAction(ub *UserBalance, a *Action) (err error) { +func resetTriggersAction(ub *Account, a *Action) (err error) { ub.resetActionTriggers(a) return } -func setPostpaidAction(ub *UserBalance, a *Action) (err error) { +func setPostpaidAction(ub *Account, a *Action) (err error) { ub.Type = UB_TYPE_POSTPAID return } -func resetPostpaidAction(ub *UserBalance, a *Action) (err error) { +func resetPostpaidAction(ub *Account, a *Action) (err error) { genericReset(ub) return setPostpaidAction(ub, a) } -func setPrepaidAction(ub *UserBalance, a *Action) (err error) { +func setPrepaidAction(ub *Account, a *Action) (err error) { ub.Type = UB_TYPE_PREPAID return } -func resetPrepaidAction(ub *UserBalance, a *Action) (err error) { +func resetPrepaidAction(ub *Account, a *Action) (err error) { genericReset(ub) return setPrepaidAction(ub, a) } -func topupResetAction(ub *UserBalance, a *Action) (err error) { +func topupResetAction(ub *Account, a *Action) (err error) { if ub.BalanceMap == nil { // Init the map since otherwise will get error if nil ub.BalanceMap = make(map[string]BalanceChain, 0) } @@ -148,17 +148,17 @@ func topupResetAction(ub *UserBalance, a *Action) (err error) { return } -func topupAction(ub *UserBalance, a *Action) (err error) { +func topupAction(ub *Account, a *Action) (err error) { genericMakeNegative(a) genericDebit(ub, a) return } -func debitAction(ub *UserBalance, a *Action) (err error) { +func debitAction(ub *Account, a *Action) (err error) { return genericDebit(ub, a) } -func resetCounterAction(ub *UserBalance, a *Action) (err error) { +func resetCounterAction(ub *Account, a *Action) (err error) { uc := ub.getUnitCounter(a) if uc == nil { uc = &UnitsCounter{BalanceType: a.BalanceType, Direction: a.Direction} @@ -168,7 +168,7 @@ func resetCounterAction(ub *UserBalance, a *Action) (err error) { return } -func resetCountersAction(ub *UserBalance, a *Action) (err error) { +func resetCountersAction(ub *Account, a *Action) (err error) { ub.UnitCounters = make([]*UnitsCounter, 0) ub.initCounters() return @@ -180,7 +180,7 @@ func genericMakeNegative(a *Action) { } } -func genericDebit(ub *UserBalance, a *Action) (err error) { +func genericDebit(ub *Account, a *Action) (err error) { if ub.BalanceMap == nil { ub.BalanceMap = make(map[string]BalanceChain) } @@ -188,17 +188,17 @@ func genericDebit(ub *UserBalance, a *Action) (err error) { return } -func enableUserAction(ub *UserBalance, a *Action) (err error) { +func enableUserAction(ub *Account, a *Action) (err error) { ub.Disabled = false return } -func disableUserAction(ub *UserBalance, a *Action) (err error) { +func disableUserAction(ub *Account, a *Action) (err error) { ub.Disabled = true return } -func genericReset(ub *UserBalance) { +func genericReset(ub *Account) { for k, _ := range ub.BalanceMap { ub.BalanceMap[k] = BalanceChain{&Balance{Value: 0}} } @@ -206,7 +206,7 @@ func genericReset(ub *UserBalance) { ub.resetActionTriggers(nil) } -func callUrl(ub *UserBalance, a *Action) error { +func callUrl(ub *Account, a *Action) error { body, err := json.Marshal(ub) if err != nil { return err @@ -216,7 +216,7 @@ func callUrl(ub *UserBalance, a *Action) error { } // Does not block for posts, no error reports -func callUrlAsync(ub *UserBalance, a *Action) error { +func callUrlAsync(ub *Account, a *Action) error { body, err := json.Marshal(ub) if err != nil { return err @@ -237,7 +237,7 @@ func callUrlAsync(ub *UserBalance, a *Action) error { } // Mails the balance hitting the threshold towards predefined list of addresses -func mailAsync(ub *UserBalance, a *Action) error { +func mailAsync(ub *Account, a *Action) error { ubJson, err := json.Marshal(ub) if err != nil { return err diff --git a/engine/action_timing.go b/engine/action_timing.go index b2743039b..652541540 100644 --- a/engine/action_timing.go +++ b/engine/action_timing.go @@ -35,14 +35,14 @@ const ( ) type ActionTiming struct { - Id string // uniquely identify the timing - Tag string // informative purpose only - UserBalanceIds []string - Timing *RateInterval - Weight float64 - ActionsId string - actions Actions - stCache time.Time // cached time of the next start + Id string // uniquely identify the timing + Tag string // informative purpose only + AccountIds []string + Timing *RateInterval + Weight float64 + ActionsId string + actions Actions + stCache time.Time // cached time of the next start } type ActionPlan []*ActionTiming @@ -232,9 +232,9 @@ func (at *ActionTiming) Execute() (err error) { Logger.Crit(fmt.Sprintf("Function type %v not available, aborting execution!", a.ActionType)) return } - for _, ubId := range at.UserBalanceIds { + for _, ubId := range at.AccountIds { _, err := AccLock.Guard(ubId, func() (float64, error) { - ub, err := accountingStorage.GetUserBalance(ubId) + ub, err := accountingStorage.GetAccount(ubId) if ub.Disabled { return 0, fmt.Errorf("User %s is disabled", ubId) } @@ -245,7 +245,7 @@ func (at *ActionTiming) Execute() (err error) { Logger.Info(fmt.Sprintf("Executing %v on %v", a.ActionType, ub.Id)) err = actionFunction(ub, a) - accountingStorage.SetUserBalance(ub) + accountingStorage.SetAccount(ub) return 0, nil }) if err != nil { @@ -317,15 +317,15 @@ func RemActionTiming(ats ActionPlan, actionTimingId, balanceId string) ActionPla ats[idx], ats = ats[len(ats)-1], ats[:len(ats)-1] continue } - for iBlnc, blncId := range at.UserBalanceIds { + for iBlnc, blncId := range at.AccountIds { if blncId == balanceId { - if len(at.UserBalanceIds) == 1 { // Only one balance, remove complete at + if len(at.AccountIds) == 1 { // Only one balance, remove complete at if len(ats) == 1 { // Removing last item, by init empty return make([]*ActionTiming, 0) } ats[idx], ats = ats[len(ats)-1], ats[:len(ats)-1] } else { - at.UserBalanceIds[iBlnc], at.UserBalanceIds = at.UserBalanceIds[len(at.UserBalanceIds)-1], at.UserBalanceIds[:len(at.UserBalanceIds)-1] + at.AccountIds[iBlnc], at.AccountIds = at.AccountIds[len(at.AccountIds)-1], at.AccountIds[:len(at.AccountIds)-1] } } } diff --git a/engine/action_trigger.go b/engine/action_trigger.go index 23f8e6dee..676b08a02 100644 --- a/engine/action_trigger.go +++ b/engine/action_trigger.go @@ -38,7 +38,7 @@ type ActionTrigger struct { Executed bool } -func (at *ActionTrigger) Execute(ub *UserBalance) (err error) { +func (at *ActionTrigger) Execute(ub *Account) (err error) { if ub.Disabled { return fmt.Errorf("User %s is disabled", ub.Id) } @@ -72,7 +72,7 @@ func (at *ActionTrigger) Execute(ub *UserBalance) (err error) { at.Executed = false } storageLogger.LogActionTrigger(ub.Id, RATER_SOURCE, at, aac) - accountingStorage.SetUserBalance(ub) + accountingStorage.SetAccount(ub) return } diff --git a/engine/actions_test.go b/engine/actions_test.go index b01b68359..aee09f8ed 100644 --- a/engine/actions_test.go +++ b/engine/actions_test.go @@ -431,20 +431,20 @@ func TestActionTimingPriotityListWeight(t *testing.T) { func TestActionTimingsRemoveMember(t *testing.T) { at1 := &ActionTiming{ - Id: "some uuid", - Tag: "test", - UserBalanceIds: []string{"one", "two", "three"}, - ActionsId: "TEST_ACTIONS", + Id: "some uuid", + Tag: "test", + AccountIds: []string{"one", "two", "three"}, + ActionsId: "TEST_ACTIONS", } at2 := &ActionTiming{ - Id: "some uuid22", - Tag: "test2", - UserBalanceIds: []string{"three", "four"}, - ActionsId: "TEST_ACTIONS2", + Id: "some uuid22", + Tag: "test2", + AccountIds: []string{"three", "four"}, + ActionsId: "TEST_ACTIONS2", } ats := ActionPlan{at1, at2} - if outAts := RemActionTiming(ats, "", "four"); len(outAts[1].UserBalanceIds) != 1 { - t.Error("Expecting fewer balance ids", outAts[1].UserBalanceIds) + if outAts := RemActionTiming(ats, "", "four"); len(outAts[1].AccountIds) != 1 { + t.Error("Expecting fewer balance ids", outAts[1].AccountIds) } if ats = RemActionTiming(ats, "", "three"); len(ats) != 1 { t.Error("Expecting fewer actionTimings", ats) @@ -575,7 +575,7 @@ func TestActionTriggerPriotityList(t *testing.T) { } func TestActionResetTriggres(t *testing.T) { - ub := &UserBalance{ + ub := &Account{ Id: "TEST_UB", BalanceMap: map[string]BalanceChain{CREDIT: BalanceChain{&Balance{Value: 10}}, MINUTES + OUTBOUND: BalanceChain{&Balance{Value: 10, Weight: 20, DestinationId: "NAT"}, &Balance{Weight: 10, DestinationId: "RET"}}}, UnitCounters: []*UnitsCounter{&UnitsCounter{BalanceType: CREDIT, Balances: BalanceChain{&Balance{Value: 1}}}}, @@ -588,7 +588,7 @@ func TestActionResetTriggres(t *testing.T) { } func TestActionResetTriggresExecutesThem(t *testing.T) { - ub := &UserBalance{ + ub := &Account{ Id: "TEST_UB", BalanceMap: map[string]BalanceChain{CREDIT: BalanceChain{&Balance{Value: 10}}}, UnitCounters: []*UnitsCounter{&UnitsCounter{BalanceType: CREDIT, Balances: BalanceChain{&Balance{Value: 1}}}}, @@ -601,7 +601,7 @@ func TestActionResetTriggresExecutesThem(t *testing.T) { } func TestActionResetTriggresActionFilter(t *testing.T) { - ub := &UserBalance{ + ub := &Account{ Id: "TEST_UB", BalanceMap: map[string]BalanceChain{CREDIT: BalanceChain{&Balance{Value: 10}}, MINUTES + OUTBOUND: BalanceChain{&Balance{Value: 10, Weight: 20, DestinationId: "NAT"}, &Balance{Weight: 10, DestinationId: "RET"}}}, UnitCounters: []*UnitsCounter{&UnitsCounter{BalanceType: CREDIT, Balances: BalanceChain{&Balance{Value: 1}}}}, @@ -614,7 +614,7 @@ func TestActionResetTriggresActionFilter(t *testing.T) { } func TestActionSetPostpaid(t *testing.T) { - ub := &UserBalance{ + ub := &Account{ Id: "TEST_UB", Type: UB_TYPE_PREPAID, BalanceMap: map[string]BalanceChain{CREDIT: BalanceChain{&Balance{Value: 100}}, MINUTES + OUTBOUND: BalanceChain{&Balance{Value: 10, Weight: 20, DestinationId: "NAT"}, &Balance{Weight: 10, DestinationId: "RET"}}}, @@ -628,7 +628,7 @@ func TestActionSetPostpaid(t *testing.T) { } func TestActionSetPrepaid(t *testing.T) { - ub := &UserBalance{ + ub := &Account{ Id: "TEST_UB", Type: UB_TYPE_POSTPAID, BalanceMap: map[string]BalanceChain{CREDIT: BalanceChain{&Balance{Value: 100}}, MINUTES + OUTBOUND: BalanceChain{&Balance{Value: 10, Weight: 20, DestinationId: "NAT"}, &Balance{Weight: 10, DestinationId: "RET"}}}, @@ -642,7 +642,7 @@ func TestActionSetPrepaid(t *testing.T) { } func TestActionResetPrepaid(t *testing.T) { - ub := &UserBalance{ + ub := &Account{ Id: "TEST_UB", Type: UB_TYPE_POSTPAID, BalanceMap: map[string]BalanceChain{CREDIT: BalanceChain{&Balance{Value: 100}}, MINUTES + OUTBOUND: BalanceChain{&Balance{Value: 10, Weight: 20, DestinationId: "NAT"}, &Balance{Weight: 10, DestinationId: "RET"}}}, @@ -661,7 +661,7 @@ func TestActionResetPrepaid(t *testing.T) { } func TestActionResetPostpaid(t *testing.T) { - ub := &UserBalance{ + ub := &Account{ Id: "TEST_UB", Type: UB_TYPE_PREPAID, BalanceMap: map[string]BalanceChain{CREDIT: BalanceChain{&Balance{Value: 100}}, MINUTES + OUTBOUND: BalanceChain{&Balance{Value: 10, Weight: 20, DestinationId: "NAT"}, &Balance{Weight: 10, DestinationId: "RET"}}}, @@ -679,7 +679,7 @@ func TestActionResetPostpaid(t *testing.T) { } func TestActionTopupResetCredit(t *testing.T) { - ub := &UserBalance{ + ub := &Account{ Id: "TEST_UB", Type: UB_TYPE_PREPAID, BalanceMap: map[string]BalanceChain{CREDIT + OUTBOUND: BalanceChain{&Balance{Value: 100}}, MINUTES + OUTBOUND: BalanceChain{&Balance{Value: 10, Weight: 20, DestinationId: "NAT"}, &Balance{Weight: 10, DestinationId: "RET"}}}, @@ -698,7 +698,7 @@ func TestActionTopupResetCredit(t *testing.T) { } func TestActionTopupResetMinutes(t *testing.T) { - ub := &UserBalance{ + ub := &Account{ Id: "TEST_UB", Type: UB_TYPE_PREPAID, BalanceMap: map[string]BalanceChain{ @@ -720,7 +720,7 @@ func TestActionTopupResetMinutes(t *testing.T) { } func TestActionTopupCredit(t *testing.T) { - ub := &UserBalance{ + ub := &Account{ Id: "TEST_UB", Type: UB_TYPE_PREPAID, BalanceMap: map[string]BalanceChain{CREDIT + OUTBOUND: BalanceChain{&Balance{Value: 100}}, MINUTES + OUTBOUND: BalanceChain{&Balance{Value: 10, Weight: 20, DestinationId: "NAT"}, &Balance{Weight: 10, DestinationId: "RET"}}}, @@ -739,7 +739,7 @@ func TestActionTopupCredit(t *testing.T) { } func TestActionTopupMinutes(t *testing.T) { - ub := &UserBalance{ + ub := &Account{ Id: "TEST_UB", Type: UB_TYPE_PREPAID, BalanceMap: map[string]BalanceChain{CREDIT: BalanceChain{&Balance{Value: 100}}, MINUTES + OUTBOUND: BalanceChain{&Balance{Value: 10, Weight: 20, DestinationId: "NAT"}, &Balance{Weight: 10, DestinationId: "RET"}}}, @@ -759,7 +759,7 @@ func TestActionTopupMinutes(t *testing.T) { } func TestActionDebitCredit(t *testing.T) { - ub := &UserBalance{ + ub := &Account{ Id: "TEST_UB", Type: UB_TYPE_PREPAID, BalanceMap: map[string]BalanceChain{CREDIT + OUTBOUND: BalanceChain{&Balance{Value: 100}}, MINUTES + OUTBOUND: BalanceChain{&Balance{Value: 10, Weight: 20, DestinationId: "NAT"}, &Balance{Weight: 10, DestinationId: "RET"}}}, @@ -778,7 +778,7 @@ func TestActionDebitCredit(t *testing.T) { } func TestActionDebitMinutes(t *testing.T) { - ub := &UserBalance{ + ub := &Account{ Id: "TEST_UB", Type: UB_TYPE_PREPAID, BalanceMap: map[string]BalanceChain{CREDIT: BalanceChain{&Balance{Value: 100}}, MINUTES + OUTBOUND: BalanceChain{&Balance{Value: 10, Weight: 20, DestinationId: "NAT"}, &Balance{Weight: 10, DestinationId: "RET"}}}, @@ -798,7 +798,7 @@ func TestActionDebitMinutes(t *testing.T) { } func TestActionResetAllCounters(t *testing.T) { - ub := &UserBalance{ + ub := &Account{ Id: "TEST_UB", Type: UB_TYPE_POSTPAID, BalanceMap: map[string]BalanceChain{ @@ -828,7 +828,7 @@ func TestActionResetAllCounters(t *testing.T) { } func TestActionResetCounterMinutes(t *testing.T) { - ub := &UserBalance{ + ub := &Account{ Id: "TEST_UB", Type: UB_TYPE_POSTPAID, BalanceMap: map[string]BalanceChain{ @@ -860,7 +860,7 @@ func TestActionResetCounterMinutes(t *testing.T) { } func TestActionResetCounterCREDIT(t *testing.T) { - ub := &UserBalance{ + ub := &Account{ Id: "TEST_UB", Type: UB_TYPE_POSTPAID, BalanceMap: map[string]BalanceChain{CREDIT: BalanceChain{&Balance{Value: 100}}, MINUTES + OUTBOUND: BalanceChain{&Balance{Value: 10, Weight: 20, DestinationId: "NAT"}, &Balance{Weight: 10, DestinationId: "RET"}}}, @@ -925,12 +925,12 @@ func TestActionTimingLogging(t *testing.T) { }, } at := &ActionTiming{ - Id: "some uuid", - Tag: "test", - UserBalanceIds: []string{"one", "two", "three"}, - Timing: i, - Weight: 10.0, - ActionsId: "TEST_ACTIONS", + Id: "some uuid", + Tag: "test", + AccountIds: []string{"one", "two", "three"}, + Timing: i, + Weight: 10.0, + ActionsId: "TEST_ACTIONS", } as, err := accountingStorage.GetActions(at.ActionsId, false) if err != nil { @@ -965,7 +965,7 @@ func TestActionMakeNegative(t *testing.T) { } func TestMinBalanceTriggerSimple(t *testing.T) { - //ub := &UserBalance{} + //ub := &Account{} } /********************************** Benchmarks ********************************/ diff --git a/engine/balances.go b/engine/balances.go index 90c9eb5b0..fa5e1ac50 100644 --- a/engine/balances.go +++ b/engine/balances.go @@ -116,7 +116,7 @@ func (b *Balance) GetCost(cd *CallDescriptor) (*CallCost, error) { return cc, nil } -func (b *Balance) DebitMinutes(cc *CallCost, count bool, ub *UserBalance, moneyBalances BalanceChain) error { +func (b *Balance) DebitMinutes(cc *CallCost, count bool, ub *Account, moneyBalances BalanceChain) error { for tsIndex := 0; tsIndex < len(cc.Timespans); tsIndex++ { if b.Value <= 0 { return nil @@ -257,7 +257,7 @@ func (b *Balance) DebitMinutes(cc *CallCost, count bool, ub *UserBalance, moneyB return nil } -func (b *Balance) DebitMoney(cc *CallCost, count bool, ub *UserBalance) error { +func (b *Balance) DebitMoney(cc *CallCost, count bool, ub *Account) error { for tsIndex := 0; tsIndex < len(cc.Timespans); tsIndex++ { if b.Value <= 0 { return nil diff --git a/engine/calldesc.go b/engine/calldesc.go index 8be71b04d..e597691fb 100644 --- a/engine/calldesc.go +++ b/engine/calldesc.go @@ -116,7 +116,7 @@ type CallDescriptor struct { FallbackSubject string // the subject to check for destination if not found on primary subject RatingInfos RatingInfos Increments Increments - userBalance *UserBalance + userBalance *Account } func (cd *CallDescriptor) ValidateCallData() error { @@ -135,7 +135,7 @@ func (cd *CallDescriptor) AddRatingInfo(ris ...*RatingInfo) { } // Returns the key used to retrive the user balance involved in this call -func (cd *CallDescriptor) GetUserBalanceKey() string { +func (cd *CallDescriptor) GetAccountKey() string { subj := cd.Subject if cd.Account != "" { subj = cd.Account @@ -144,9 +144,9 @@ func (cd *CallDescriptor) GetUserBalanceKey() string { } // Gets and caches the user balance information. -func (cd *CallDescriptor) getUserBalance() (ub *UserBalance, err error) { +func (cd *CallDescriptor) getAccount() (ub *Account, err error) { if cd.userBalance == nil { - cd.userBalance, err = accountingStorage.GetUserBalance(cd.GetUserBalanceKey()) + cd.userBalance, err = accountingStorage.GetAccount(cd.GetAccountKey()) } if cd.userBalance != nil && cd.userBalance.Disabled { return nil, fmt.Errorf("User %s is disabled", ub.Id) @@ -388,7 +388,7 @@ func (cd *CallDescriptor) GetCost() (*CallCost, error) { } err := cd.LoadRatingPlans() if err != nil { - Logger.Err(fmt.Sprintf("error getting cost for key %v: %v", cd.GetUserBalanceKey(), err)) + Logger.Err(fmt.Sprintf("error getting cost for key %v: %v", cd.GetAccountKey(), err)) return &CallCost{Cost: -1}, err } timespans := cd.splitInTimeSpans(nil) @@ -432,12 +432,12 @@ func (origCd *CallDescriptor) GetMaxSessionDuration() (time.Duration, error) { //Logger.Debug(fmt.Sprintf("MAX SESSION cd: %+v", cd)) err := cd.LoadRatingPlans() if err != nil { - Logger.Err(fmt.Sprintf("error getting cost for key %v: %v", cd.GetUserBalanceKey(), err)) + Logger.Err(fmt.Sprintf("error getting cost for key %v: %v", cd.GetAccountKey(), err)) return 0, err } var availableDuration time.Duration availableCredit := 0.0 - if userBalance, err := cd.getUserBalance(); err == nil && userBalance != nil { + if userBalance, err := cd.getAccount(); err == nil && userBalance != nil { if userBalance.Type == UB_TYPE_POSTPAID { return -1, nil } else { @@ -445,7 +445,7 @@ func (origCd *CallDescriptor) GetMaxSessionDuration() (time.Duration, error) { // Logger.Debug(fmt.Sprintf("available sec: %v credit: %v", availableSeconds, availableCredit)) } } else { - Logger.Err(fmt.Sprintf("Could not get user balance for %s: %s.", cd.GetUserBalanceKey(), err.Error())) + Logger.Err(fmt.Sprintf("Could not get user balance for %s: %s.", cd.GetAccountKey(), err.Error())) return 0, err } //Logger.Debug(fmt.Sprintf("availableDuration: %v, availableCredit: %v", availableDuration, availableCredit)) @@ -494,18 +494,18 @@ func (origCd *CallDescriptor) GetMaxSessionDuration() (time.Duration, error) { func (cd *CallDescriptor) Debit() (cc *CallCost, err error) { cc, err = cd.GetCost() if err != nil { - Logger.Err(fmt.Sprintf(" Error getting cost for account key %v: %v", cd.GetUserBalanceKey(), err)) + Logger.Err(fmt.Sprintf(" Error getting cost for account key %v: %v", cd.GetAccountKey(), err)) return } - if userBalance, err := cd.getUserBalance(); err != nil { + if userBalance, err := cd.getAccount(); err != nil { Logger.Err(fmt.Sprintf(" Error retrieving user balance: %v", err)) } else if userBalance == nil { - // Logger.Debug(fmt.Sprintf(" No user balance defined: %v", cd.GetUserBalanceKey())) + // Logger.Debug(fmt.Sprintf(" No user balance defined: %v", cd.GetAccountKey())) } else { - //Logger.Debug(fmt.Sprintf(" Attempting to debit from %v, value: %v", cd.GetUserBalanceKey(), cc.Cost+cc.ConnectFee)) - defer accountingStorage.SetUserBalance(userBalance) + //Logger.Debug(fmt.Sprintf(" Attempting to debit from %v, value: %v", cd.GetAccountKey(), cc.Cost+cc.ConnectFee)) + defer accountingStorage.SetAccount(userBalance) //ub, _ := json.Marshal(userBalance) - //Logger.Debug(fmt.Sprintf("UserBalance: %s", ub)) + //Logger.Debug(fmt.Sprintf("Account: %s", ub)) //cCost, _ := json.Marshal(cc) //Logger.Debug(fmt.Sprintf("CallCost: %s", cCost)) if cc.Cost != 0 || cc.GetConnectFee() != 0 { @@ -538,8 +538,8 @@ func (cd *CallDescriptor) MaxDebit() (cc *CallCost, err error) { } func (cd *CallDescriptor) RefundIncrements() (left float64, err error) { - if userBalance, err := cd.getUserBalance(); err == nil && userBalance != nil { - defer accountingStorage.SetUserBalance(userBalance) + if userBalance, err := cd.getAccount(); err == nil && userBalance != nil { + defer accountingStorage.SetAccount(userBalance) userBalance.refundIncrements(cd.Increments, cd.Direction, true) } return 0.0, err @@ -550,8 +550,8 @@ Interface method used to add/substract an amount of cents from user's money bala The amount filed has to be filled in call descriptor. */ func (cd *CallDescriptor) DebitCents() (left float64, err error) { - if userBalance, err := cd.getUserBalance(); err == nil && userBalance != nil { - defer accountingStorage.SetUserBalance(userBalance) + if userBalance, err := cd.getAccount(); err == nil && userBalance != nil { + defer accountingStorage.SetAccount(userBalance) return userBalance.debitGenericBalance(CREDIT, cd.Direction, cd.Amount, true), nil } return 0.0, err @@ -562,8 +562,8 @@ Interface method used to add/substract an amount of units from user's sms balanc The amount filed has to be filled in call descriptor. */ func (cd *CallDescriptor) DebitSMS() (left float64, err error) { - if userBalance, err := cd.getUserBalance(); err == nil && userBalance != nil { - defer accountingStorage.SetUserBalance(userBalance) + if userBalance, err := cd.getAccount(); err == nil && userBalance != nil { + defer accountingStorage.SetAccount(userBalance) return userBalance.debitGenericBalance(SMS, cd.Direction, cd.Amount, true), nil } return 0, err @@ -574,8 +574,8 @@ Interface method used to add/substract an amount of seconds from user's minutes The amount filed has to be filled in call descriptor. */ func (cd *CallDescriptor) DebitSeconds() (err error) { - if userBalance, err := cd.getUserBalance(); err == nil && userBalance != nil { - defer accountingStorage.SetUserBalance(userBalance) + if userBalance, err := cd.getAccount(); err == nil && userBalance != nil { + defer accountingStorage.SetAccount(userBalance) return userBalance.debitCreditBalance(cd.CreateCallCost(), true) } return err @@ -588,7 +588,7 @@ specified in the tariff plan is applied. The amount filed has to be filled in call descriptor. */ func (cd *CallDescriptor) AddRecievedCallSeconds() (err error) { - if userBalance, err := cd.getUserBalance(); err == nil && userBalance != nil { + if userBalance, err := cd.getAccount(); err == nil && userBalance != nil { a := &Action{ Direction: INBOUND, Balance: &Balance{Value: cd.Amount, DestinationId: cd.Destination}, diff --git a/engine/calldesc_test.go b/engine/calldesc_test.go index 75d242f60..5fcaef362 100644 --- a/engine/calldesc_test.go +++ b/engine/calldesc_test.go @@ -37,7 +37,15 @@ func init() { } func populateDB() { - minu := &UserBalance{ + ats := []*Action{ + &Action{ActionType: "*topup", BalanceType: CREDIT, Direction: OUTBOUND, Balance: &Balance{Value: 10}}, + &Action{ActionType: "*topup", BalanceType: MINUTES, Direction: OUTBOUND, Balance: &Balance{Weight: 20, Value: 10, DestinationId: "NAT"}}, + } + ats1 := []*Action{ + &Action{ActionType: "*topup", BalanceType: CREDIT, Direction: OUTBOUND, Balance: &Balance{Value: 10}, Weight: 20}, + &Action{ActionType: "*reset_prepaid", Weight: 10}, + } + minu := &Account{ Id: "*out:vdf:minu", Type: UB_TYPE_PREPAID, BalanceMap: map[string]BalanceChain{ @@ -47,7 +55,7 @@ func populateDB() { &Balance{Value: 100, DestinationId: "RET", Weight: 20}, }}, } - broker := &UserBalance{ + broker := &Account{ Id: "*out:vdf:broker", Type: UB_TYPE_PREPAID, BalanceMap: map[string]BalanceChain{ @@ -57,9 +65,10 @@ func populateDB() { }}, } if accountingStorage != nil { - accountingStorage.(Storage).Flush() - accountingStorage.SetUserBalance(broker) - accountingStorage.SetUserBalance(minu) + accountingStorage.SetActions("TEST_ACTIONS", ats) + accountingStorage.SetActions("TEST_ACTIONS_ORDER", ats1) + accountingStorage.SetAccount(broker) + accountingStorage.SetAccount(minu) } else { log.Fatal("Could not connect to db!") } @@ -270,7 +279,7 @@ func TestMinutesCost(t *testing.T) { } } -func TestMaxSessionTimeNoUserBalance(t *testing.T) { +func TestMaxSessionTimeNoAccount(t *testing.T) { cd := &CallDescriptor{ TimeStart: time.Date(2013, 10, 21, 18, 34, 0, 0, time.UTC), TimeEnd: time.Date(2013, 10, 21, 18, 35, 0, 0, time.UTC), @@ -285,7 +294,7 @@ func TestMaxSessionTimeNoUserBalance(t *testing.T) { } } -func TestMaxSessionTimeWithUserBalance(t *testing.T) { +func TestMaxSessionTimeWithAccount(t *testing.T) { cd := &CallDescriptor{ TimeStart: time.Date(2013, 10, 21, 18, 34, 0, 0, time.UTC), TimeEnd: time.Date(2013, 10, 21, 18, 35, 0, 0, time.UTC), @@ -302,7 +311,7 @@ func TestMaxSessionTimeWithUserBalance(t *testing.T) { } } -func TestMaxSessionTimeWithUserBalanceAccount(t *testing.T) { +func TestMaxSessionTimeWithAccountAccount(t *testing.T) { cd := &CallDescriptor{ TimeStart: time.Date(2013, 10, 21, 18, 34, 0, 0, time.UTC), TimeEnd: time.Date(2013, 10, 21, 18, 35, 0, 0, time.UTC), diff --git a/engine/loader_csv.go b/engine/loader_csv.go index 185783e95..4f5d783d5 100644 --- a/engine/loader_csv.go +++ b/engine/loader_csv.go @@ -38,7 +38,7 @@ type CSVReader struct { actions map[string][]*Action actionsTimings map[string][]*ActionTiming actionsTriggers map[string][]*ActionTrigger - accountActions []*UserBalance + accountActions []*Account destinations []*Destination timings map[string]*utils.TPTiming rates map[string]*utils.TPRate @@ -222,7 +222,7 @@ func (csvr *CSVReader) WriteToDatabase(flush, verbose bool) (err error) { log.Print("Account actions") } for _, ub := range csvr.accountActions { - err = accountingStorage.SetUserBalance(ub) + err = accountingStorage.SetAccount(ub) if err != nil { return err } @@ -595,7 +595,7 @@ func (csvr *CSVReader) LoadAccountActions() (err error) { // only return error if there was something ther for the tag return errors.New(fmt.Sprintf("Could not get action triggers for tag %v", record[4])) } - ub := &UserBalance{ + ub := &Account{ Type: UB_TYPE_PREPAID, Id: tag, ActionTriggers: aTriggers, @@ -607,7 +607,7 @@ func (csvr *CSVReader) LoadAccountActions() (err error) { // must not continue here } for _, at := range aTimings { - at.UserBalanceIds = append(at.UserBalanceIds, tag) + at.AccountIds = append(at.AccountIds, tag) } } return nil diff --git a/engine/loader_csv_test.go b/engine/loader_csv_test.go index 79c0b162a..d458dd6a2 100644 --- a/engine/loader_csv_test.go +++ b/engine/loader_csv_test.go @@ -142,6 +142,7 @@ func init() { csvr.LoadAccountActions() csvr.WriteToDatabase(false, false) dataStorage.CacheRating(nil, nil, nil) + accountingStorage.CacheAccounting(nil) } func TestLoadDestinations(t *testing.T) { @@ -610,9 +611,9 @@ func TestLoadActionTimings(t *testing.T) { } atm := csvr.actionsTimings["MORE_MINUTES"][0] expected := &ActionTiming{ - Id: atm.Id, - Tag: "MORE_MINUTES", - UserBalanceIds: []string{"*out:vdf:minitsboy"}, + Id: atm.Id, + Tag: "MORE_MINUTES", + AccountIds: []string{"*out:vdf:minitsboy"}, Timing: &RateInterval{ Timing: &RITiming{ Years: utils.Years{2012}, @@ -671,7 +672,7 @@ func TestLoadAccountActions(t *testing.T) { t.Error("Failed to load account actions: ", csvr.accountActions) } aa := csvr.accountActions[0] - expected := &UserBalance{ + expected := &Account{ Id: "*out:vdf:minitsboy", Type: UB_TYPE_PREPAID, ActionTriggers: csvr.actionsTriggers["STANDARD_TRIGGER"], diff --git a/engine/loader_db.go b/engine/loader_db.go index fd632c2cb..5332e00c2 100644 --- a/engine/loader_db.go +++ b/engine/loader_db.go @@ -34,7 +34,7 @@ type DbReader struct { actions map[string][]*Action actionsTimings map[string][]*ActionTiming actionsTriggers map[string][]*ActionTrigger - accountActions []*UserBalance + accountActions []*Account destinations []*Destination timings map[string]*utils.TPTiming rates map[string]*utils.TPRate @@ -178,7 +178,7 @@ func (dbr *DbReader) WriteToDatabase(flush, verbose bool) (err error) { log.Print("Account actions") } for _, ub := range dbr.accountActions { - err = accountingStorage.SetUserBalance(ub) + err = accountingStorage.SetAccount(ub) if err != nil { return err } @@ -486,7 +486,7 @@ func (dbr *DbReader) LoadAccountActions() (err error) { if !exists { return errors.New(fmt.Sprintf("Could not get action triggers for tag %v", aa.ActionTriggersId)) } - ub := &UserBalance{ + ub := &Account{ Type: UB_TYPE_PREPAID, Id: aa.KeyId(), ActionTriggers: aTriggers, @@ -498,7 +498,7 @@ func (dbr *DbReader) LoadAccountActions() (err error) { // must not continue here } for _, at := range aTimings { - at.UserBalanceIds = append(at.UserBalanceIds, aa.KeyId()) + at.AccountIds = append(at.AccountIds, aa.KeyId()) } } return nil @@ -515,11 +515,11 @@ func (dbr *DbReader) LoadAccountActionsFiltered(qriedAA *utils.TPAccountActions) // action timings if accountAction.ActionPlanId != "" { // get old userBalanceIds - var exitingUserBalanceIds []string + var exitingAccountIds []string existingActionTimings, err := dbr.accountDb.GetActionTimings(accountAction.ActionPlanId) if err == nil && len(existingActionTimings) > 0 { // all action timings from a specific tag shuld have the same list of user balances from the first one - exitingUserBalanceIds = existingActionTimings[0].UserBalanceIds + exitingAccountIds = existingActionTimings[0].AccountIds } actionTimingsMap, err := dbr.storDb.GetTPActionTimings(dbr.tpid, accountAction.ActionPlanId) @@ -563,14 +563,14 @@ func (dbr *DbReader) LoadAccountActionsFiltered(qriedAA *utils.TPAccountActions) actionsIds = append(actionsIds, actTmg.ActionsId) //add user balance id if no already in found := false - for _, ubId := range exitingUserBalanceIds { + for _, ubId := range exitingAccountIds { if ubId == id { found = true break } } if !found { - actTmg.UserBalanceIds = append(exitingUserBalanceIds, id) + actTmg.AccountIds = append(exitingAccountIds, id) } actionTimings = append(actionTimings, actTmg) } @@ -649,16 +649,16 @@ func (dbr *DbReader) LoadAccountActionsFiltered(qriedAA *utils.TPAccountActions) return err } } - ub, err := dbr.accountDb.GetUserBalance(id) + ub, err := dbr.accountDb.GetAccount(id) if err != nil { - ub = &UserBalance{ + ub = &Account{ Type: UB_TYPE_PREPAID, Id: id, } } ub.ActionTriggers = actionTriggers - if err := dbr.accountDb.SetUserBalance(ub); err != nil { + if err := dbr.accountDb.SetAccount(ub); err != nil { return err } } diff --git a/engine/realcalls_test.go b/engine/realcalls_test.go index c62c7ff9d..cf459464b 100644 --- a/engine/realcalls_test.go +++ b/engine/realcalls_test.go @@ -28,7 +28,7 @@ var balance1 string = `{"Id":"*out:192.168.56.66:dan","Type":"*prepaid","Balance var callCost1 string = `{"Direction":"*out","TOR":"call","Tenant":"192.168.56.66","Subject":"dan","Account":"dan","Destination":"+4986517174963","Cost":0.6,"ConnectFee":0,"Timespans":[{"TimeStart":"2013-12-03T14:36:48+01:00","TimeEnd":"2013-12-03T14:37:48+01:00","Cost":0.6,"RateInterval":{"Timing":{"Years":[],"Months":[],"MonthDays":[],"WeekDays":[],"StartTime":"00:00:00","EndTime":""},"Rating":{"ConnectFee":0,"Rates":[{"GroupIntervalStart":0,"Value":0.6,"RateIncrement":60000000000,"RateUnit":60000000000}],"RoundingMethod":"*up","RoundingDecimals":2},"Weight":10},"CallDuration":60000000000,"Increments":null,"MatchedSubject":"*out:192.168.56.66:call:*any","MatchedPrefix":"+49"}]}` func TestDebitBalanceForCall1(t *testing.T) { - b1 := new(UserBalance) + b1 := new(Account) if err := json.Unmarshal([]byte(balance1), b1); err != nil { t.Error("Error restoring balance1: ", err) } @@ -50,7 +50,7 @@ var balanceInsufficient = `{"Id":"*out:192.168.56.66:dan","Type":"*prepaid","Bal var costInsufficient = `{"Direction":"*out","TOR":"call","Tenant":"192.168.56.66","Subject":"dan","Account":"dan","Destination":"+4986517174963","Cost":1,"ConnectFee":3,"Timespans":[{"TimeStart":"2013-12-05T09:52:17+01:00","TimeEnd":"2013-12-05T09:53:17+01:00","Cost":1,"RateInterval":{"Timing":{"Years":[],"Months":[],"MonthDays":[],"WeekDays":[],"StartTime":"00:00:00","EndTime":""},"Rating":{"ConnectFee":3,"Rates":[{"GroupIntervalStart":0,"Value":1,"RateIncrement":60000000000,"RateUnit":60000000000}],"RoundingMethod":"*up","RoundingDecimals":2},"Weight":10},"CallDuration":60000000000,"Increments":null,"MatchedSubject":"*out:192.168.56.66:call:*any","MatchedPrefix":"+49"}]}` func TestDebitInsufficientBalance(t *testing.T) { - b1 := new(UserBalance) + b1 := new(Account) if err := json.Unmarshal([]byte(balanceInsufficient), b1); err != nil { t.Error("Error restoring balance1: ", err) } diff --git a/engine/responder.go b/engine/responder.go index 548be6c21..f135b8378 100644 --- a/engine/responder.go +++ b/engine/responder.go @@ -43,7 +43,7 @@ func (rs *Responder) GetCost(arg CallDescriptor, reply *CallCost) (err error) { r, e := rs.getCallCost(&arg, "Responder.GetCost") *reply, err = *r, e } else { - r, e := AccLock.GuardGetCost(arg.GetUserBalanceKey(), func() (*CallCost, error) { + r, e := AccLock.GuardGetCost(arg.GetAccountKey(), func() (*CallCost, error) { return arg.GetCost() }) *reply, err = *r, e @@ -56,7 +56,7 @@ func (rs *Responder) Debit(arg CallDescriptor, reply *CallCost) (err error) { r, e := rs.getCallCost(&arg, "Responder.Debit") *reply, err = *r, e } else { - r, e := AccLock.GuardGetCost(arg.GetUserBalanceKey(), func() (*CallCost, error) { + r, e := AccLock.GuardGetCost(arg.GetAccountKey(), func() (*CallCost, error) { return arg.Debit() }) *reply, err = *r, e @@ -69,7 +69,7 @@ func (rs *Responder) MaxDebit(arg CallDescriptor, reply *CallCost) (err error) { r, e := rs.getCallCost(&arg, "Responder.MaxDebit") *reply, err = *r, e } else { - r, e := AccLock.GuardGetCost(arg.GetUserBalanceKey(), func() (*CallCost, error) { + r, e := AccLock.GuardGetCost(arg.GetAccountKey(), func() (*CallCost, error) { return arg.MaxDebit() }) *reply, err = *r, e @@ -81,7 +81,7 @@ func (rs *Responder) RefundIncrements(arg CallDescriptor, reply *float64) (err e if rs.Bal != nil { *reply, err = rs.callMethod(&arg, "Responder.RefundIncrements") } else { - r, e := AccLock.Guard(arg.GetUserBalanceKey(), func() (float64, error) { + r, e := AccLock.Guard(arg.GetAccountKey(), func() (float64, error) { return arg.RefundIncrements() }) *reply, err = r, e @@ -93,7 +93,7 @@ func (rs *Responder) DebitCents(arg CallDescriptor, reply *float64) (err error) if rs.Bal != nil { *reply, err = rs.callMethod(&arg, "Responder.DebitCents") } else { - r, e := AccLock.Guard(arg.GetUserBalanceKey(), func() (float64, error) { + r, e := AccLock.Guard(arg.GetAccountKey(), func() (float64, error) { return arg.DebitCents() }) *reply, err = r, e @@ -105,7 +105,7 @@ func (rs *Responder) DebitSMS(arg CallDescriptor, reply *float64) (err error) { if rs.Bal != nil { *reply, err = rs.callMethod(&arg, "Responder.DebitSMS") } else { - r, e := AccLock.Guard(arg.GetUserBalanceKey(), func() (float64, error) { + r, e := AccLock.Guard(arg.GetAccountKey(), func() (float64, error) { return arg.DebitSMS() }) *reply, err = r, e @@ -117,7 +117,7 @@ func (rs *Responder) DebitSeconds(arg CallDescriptor, reply *float64) (err error if rs.Bal != nil { *reply, err = rs.callMethod(&arg, "Responder.DebitSeconds") } else { - r, e := AccLock.Guard(arg.GetUserBalanceKey(), func() (float64, error) { + r, e := AccLock.Guard(arg.GetAccountKey(), func() (float64, error) { return 0, arg.DebitSeconds() }) *reply, err = r, e @@ -129,7 +129,7 @@ func (rs *Responder) GetMaxSessionTime(arg CallDescriptor, reply *float64) (err if rs.Bal != nil { *reply, err = rs.callMethod(&arg, "Responder.GetMaxSessionTime") } else { - r, e := AccLock.Guard(arg.GetUserBalanceKey(), func() (float64, error) { + r, e := AccLock.Guard(arg.GetAccountKey(), func() (float64, error) { d, err := arg.GetMaxSessionDuration() return float64(d), err }) @@ -143,7 +143,7 @@ func (rs *Responder) AddRecievedCallSeconds(arg CallDescriptor, reply *float64) *reply, err = rs.callMethod(&arg, "Responder.AddRecievedCallSeconds") } else { - r, e := AccLock.Guard(arg.GetUserBalanceKey(), func() (float64, error) { + r, e := AccLock.Guard(arg.GetAccountKey(), func() (float64, error) { return 0, arg.AddRecievedCallSeconds() }) *reply, err = r, e @@ -155,7 +155,7 @@ func (rs *Responder) FlushCache(arg CallDescriptor, reply *float64) (err error) if rs.Bal != nil { *reply, err = rs.callMethod(&arg, "Responder.FlushCache") } else { - r, e := AccLock.Guard(arg.GetUserBalanceKey(), func() (float64, error) { + r, e := AccLock.Guard(arg.GetAccountKey(), func() (float64, error) { return 0, arg.FlushCache() }) *reply, err = r, e @@ -220,7 +220,7 @@ func (rs *Responder) getBalance(arg *CallDescriptor, balanceId string, reply *Ca return errors.New("No balancer supported for this command right now") } ubKey := arg.Direction + ":" + arg.Tenant + ":" + arg.Account - userBalance, err := accountingStorage.GetUserBalance(ubKey) + userBalance, err := accountingStorage.GetAccount(ubKey) if err != nil { return err } @@ -248,7 +248,7 @@ func (rs *Responder) getCallCost(key *CallDescriptor, method string) (reply *Cal time.Sleep(1 * time.Second) // wait one second and retry } else { reply = &CallCost{} - reply, err = AccLock.GuardGetCost(key.GetUserBalanceKey(), func() (*CallCost, error) { + reply, err = AccLock.GuardGetCost(key.GetAccountKey(), func() (*CallCost, error) { err = client.Call(method, *key, reply) return reply, err }) @@ -271,7 +271,7 @@ func (rs *Responder) callMethod(key *CallDescriptor, method string) (reply float Logger.Info("Waiting for raters to register...") time.Sleep(1 * time.Second) // wait one second and retry } else { - reply, err = AccLock.Guard(key.GetUserBalanceKey(), func() (float64, error) { + reply, err = AccLock.Guard(key.GetAccountKey(), func() (float64, error) { err = client.Call(method, *key, &reply) return reply, err }) diff --git a/engine/storage_interface.go b/engine/storage_interface.go index e2ddc0558..c2acda973 100644 --- a/engine/storage_interface.go +++ b/engine/storage_interface.go @@ -36,7 +36,7 @@ const ( RATING_PLAN_PREFIX = "rpl_" RATING_PROFILE_PREFIX = "rpf_" ACTION_PREFIX = "act_" - USER_BALANCE_PREFIX = "ubl_" + ACCOUNT_PREFIX = "ubl_" DESTINATION_PREFIX = "dst_" TEMP_DESTINATION_PREFIX = "tmp_" LOG_CALL_COST_PREFIX = "cco_" @@ -84,8 +84,8 @@ type AccountingStorage interface { CacheAccounting([]string) error GetActions(string, bool) (Actions, error) SetActions(string, Actions) error - GetUserBalance(string) (*UserBalance, error) - SetUserBalance(*UserBalance) error + GetAccount(string) (*Account, error) + SetAccount(*Account) error GetActionTimings(string) (ActionPlan, error) SetActionTimings(string, ActionPlan) error GetAllActionTimings() (map[string]ActionPlan, error) diff --git a/engine/storage_map.go b/engine/storage_map.go index 02378749b..05630783e 100644 --- a/engine/storage_map.go +++ b/engine/storage_map.go @@ -22,10 +22,11 @@ import ( "errors" "fmt" - "github.com/cgrates/cgrates/cache2go" - "github.com/cgrates/cgrates/utils" "strings" "time" + + "github.com/cgrates/cgrates/cache2go" + "github.com/cgrates/cgrates/utils" ) type MapStorage struct { @@ -215,9 +216,9 @@ func (ms *MapStorage) SetActions(key string, as Actions) (err error) { return } -func (ms *MapStorage) GetUserBalance(key string) (ub *UserBalance, err error) { - if values, ok := ms.dict[USER_BALANCE_PREFIX+key]; ok { - ub = &UserBalance{Id: key} +func (ms *MapStorage) GetAccount(key string) (ub *Account, err error) { + if values, ok := ms.dict[ACCOUNT_PREFIX+key]; ok { + ub = &Account{Id: key} err = ms.ms.Unmarshal(values, ub) } else { return nil, errors.New("not found") @@ -225,9 +226,9 @@ func (ms *MapStorage) GetUserBalance(key string) (ub *UserBalance, err error) { return } -func (ms *MapStorage) SetUserBalance(ub *UserBalance) (err error) { +func (ms *MapStorage) SetAccount(ub *Account) (err error) { result, err := ms.ms.Marshal(ub) - ms.dict[USER_BALANCE_PREFIX+ub.Id] = result + ms.dict[ACCOUNT_PREFIX+ub.Id] = result return } diff --git a/engine/storage_mongo.go b/engine/storage_mongo.go index f136ad71b..92b387f2b 100644 --- a/engine/storage_mongo.go +++ b/engine/storage_mongo.go @@ -183,13 +183,13 @@ func (ms *MongoStorage) SetActions(key string, as Actions) error { return ms.db.C("actions").Insert(&AcKeyValue{Key: key, Value: as}) } -func (ms *MongoStorage) GetUserBalance(key string) (result *UserBalance, err error) { - result = new(UserBalance) +func (ms *MongoStorage) GetAccount(key string) (result *Account, err error) { + result = new(Account) err = ms.db.C("userbalances").Find(bson.M{"id": key}).One(result) return } -func (ms *MongoStorage) SetUserBalance(ub *UserBalance) error { +func (ms *MongoStorage) SetAccount(ub *Account) error { return ms.db.C("userbalances").Insert(ub) } diff --git a/engine/storage_redis.go b/engine/storage_redis.go index 807d75e17..3ef5d30c3 100644 --- a/engine/storage_redis.go +++ b/engine/storage_redis.go @@ -152,7 +152,7 @@ func (rs *RedisStorage) CacheAccounting(actKeys []string) (err error) { // Used to check if specific subject is stored using prefix key attached to entity func (rs *RedisStorage) ExistsData(category, subject string) (bool, error) { switch category { - case DESTINATION_PREFIX, RATING_PLAN_PREFIX, RATING_PROFILE_PREFIX, ACTION_PREFIX, ACTION_TIMING_PREFIX, USER_BALANCE_PREFIX: + case DESTINATION_PREFIX, RATING_PLAN_PREFIX, RATING_PROFILE_PREFIX, ACTION_PREFIX, ACTION_TIMING_PREFIX, ACCOUNT_PREFIX: return rs.db.Exists(category + subject) } return false, errors.New("Unsupported category in ExistsData") @@ -300,19 +300,19 @@ func (rs *RedisStorage) SetActions(key string, as Actions) (err error) { return } -func (rs *RedisStorage) GetUserBalance(key string) (ub *UserBalance, err error) { +func (rs *RedisStorage) GetAccount(key string) (ub *Account, err error) { var values []byte - if values, err = rs.db.Get(USER_BALANCE_PREFIX + key); err == nil { - ub = &UserBalance{Id: key} + if values, err = rs.db.Get(ACCOUNT_PREFIX + key); err == nil { + ub = &Account{Id: key} err = rs.ms.Unmarshal(values, ub) } return } -func (rs *RedisStorage) SetUserBalance(ub *UserBalance) (err error) { +func (rs *RedisStorage) SetAccount(ub *Account) (err error) { result, err := rs.ms.Marshal(ub) - err = rs.db.Set(USER_BALANCE_PREFIX+ub.Id, result) + err = rs.db.Set(ACCOUNT_PREFIX+ub.Id, result) return } diff --git a/engine/storage_test.go b/engine/storage_test.go index 098307300..df2dcef51 100644 --- a/engine/storage_test.go +++ b/engine/storage_test.go @@ -119,7 +119,7 @@ func TestStoreInterfaces(t *testing.T) { /************************** Benchmarks *****************************/ -func GetUB() *UserBalance { +func GetUB() *Account { uc := &UnitsCounter{ Direction: OUTBOUND, BalanceType: SMS, @@ -136,7 +136,7 @@ func GetUB() *UserBalance { } var zeroTime time.Time zeroTime = zeroTime.UTC() // for deep equal to find location - ub := &UserBalance{ + ub := &Account{ Id: "rif", Type: UB_TYPE_POSTPAID, BalanceMap: map[string]BalanceChain{SMS + OUTBOUND: BalanceChain{&Balance{Value: 14, ExpirationDate: zeroTime}}, TRAFFIC + OUTBOUND: BalanceChain{&Balance{Value: 1024, ExpirationDate: zeroTime}}, MINUTES: BalanceChain{&Balance{Weight: 20, DestinationId: "NAT"}, &Balance{Weight: 10, DestinationId: "RET"}}}, @@ -160,7 +160,7 @@ func BenchmarkMarshallerJSONStoreRestore(b *testing.B) { ub := GetUB() ap1 := RatingPlan{} - ub1 := &UserBalance{} + ub1 := &Account{} b.StartTimer() ms := new(JSONMarshaler) for i := 0; i < b.N; i++ { @@ -185,7 +185,7 @@ func BenchmarkMarshallerBSONStoreRestore(b *testing.B) { ub := GetUB() ap1 := RatingPlan{} - ub1 := &UserBalance{} + ub1 := &Account{} b.StartTimer() ms := new(BSONMarshaler) for i := 0; i < b.N; i++ { @@ -209,7 +209,7 @@ func BenchmarkMarshallerJSONBufStoreRestore(b *testing.B) { ub := GetUB() ap1 := RatingPlan{} - ub1 := &UserBalance{} + ub1 := &Account{} b.StartTimer() ms := new(JSONBufMarshaler) for i := 0; i < b.N; i++ { @@ -233,7 +233,7 @@ func BenchmarkMarshallerGOBStoreRestore(b *testing.B) { ub := GetUB() ap1 := RatingPlan{} - ub1 := &UserBalance{} + ub1 := &Account{} b.StartTimer() ms := new(GOBMarshaler) for i := 0; i < b.N; i++ { @@ -258,7 +258,7 @@ func BenchmarkMarshallerCodecMsgpackStoreRestore(b *testing.B) { ub := GetUB() ap1 := RatingPlan{} - ub1 := &UserBalance{} + ub1 := &Account{} b.StartTimer() ms := NewCodecMsgpackMarshaler() for i := 0; i < b.N; i++ { @@ -283,7 +283,7 @@ func BenchmarkMarshallerBincStoreRestore(b *testing.B) { ub := GetUB() ap1 := RatingPlan{} - ub1 := &UserBalance{} + ub1 := &Account{} b.StartTimer() ms := NewBincMarshaler() for i := 0; i < b.N; i++ {