• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Golang utils.ParseDate函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Golang中github.com/cgrates/cgrates/utils.ParseDate函数的典型用法代码示例。如果您正苦于以下问题:Golang ParseDate函数的具体用法?Golang ParseDate怎么用?Golang ParseDate使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了ParseDate函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。

示例1: TestTutLocalLcrHighestCost

func TestTutLocalLcrHighestCost(t *testing.T) {
	if !*testLocal {
		return
	}
	tStart, _ := utils.ParseDate("2014-08-04T13:00:00Z")
	tEnd, _ := utils.ParseDate("2014-08-04T13:01:00Z")
	cd := engine.CallDescriptor{
		Direction:   "*out",
		Category:    "call",
		Tenant:      "cgrates.org",
		Subject:     "1002",
		Account:     "1002",
		Destination: "1002",
		TimeStart:   tStart,
		TimeEnd:     tEnd,
	}
	eStLcr := &engine.LCRCost{
		Entry: &engine.LCREntry{DestinationId: "DST_1002", RPCategory: "lcr_profile1", Strategy: engine.LCR_STRATEGY_HIGHEST, StrategyParams: "", Weight: 10.0},
		SupplierCosts: []*engine.LCRSupplierCost{
			&engine.LCRSupplierCost{Supplier: "*out:cgrates.org:lcr_profile1:suppl1", Cost: 1.2, Duration: 60 * time.Second},
			&engine.LCRSupplierCost{Supplier: "*out:cgrates.org:lcr_profile1:suppl2", Cost: 0.6, Duration: 60 * time.Second},
		},
	}
	var lcr engine.LCRCost
	if err := tutLocalRpc.Call("Responder.GetLCR", cd, &lcr); err != nil {
		t.Error(err)
	} else if !reflect.DeepEqual(eStLcr.Entry, lcr.Entry) {
		t.Errorf("Expecting: %+v, received: %+v", eStLcr.Entry, lcr.Entry)
	} else if !reflect.DeepEqual(eStLcr.SupplierCosts, lcr.SupplierCosts) {
		t.Errorf("Expecting: %+v, received: %+v", eStLcr.SupplierCosts[0], lcr.SupplierCosts[0])
	}
}
开发者ID:nikbyte,项目名称:cgrates,代码行数:32,代码来源:tutorial_local_test.go


示例2: LoadRatingProfileFiltered

func (dbr *DbReader) LoadRatingProfileFiltered(qriedRpf *utils.TPRatingProfile) error {
	var resultRatingProfile *RatingProfile
	mpTpRpfs, err := dbr.storDb.GetTpRatingProfiles(qriedRpf) //map[string]*utils.TPRatingProfile
	if err != nil {
		return fmt.Errorf("No RateProfile for filter %v, error: %v", qriedRpf, err)
	}
	for _, tpRpf := range mpTpRpfs {
		// Logger.Debug(fmt.Sprintf("Rating profile: %v", tpRpf))
		resultRatingProfile = &RatingProfile{Id: tpRpf.KeyId()}
		for _, tpRa := range tpRpf.RatingPlanActivations {
			at, err := utils.ParseDate(tpRa.ActivationTime)
			if err != nil {
				return fmt.Errorf("Cannot parse activation time from %v", tpRa.ActivationTime)
			}
			_, exists := dbr.ratingPlans[tpRa.RatingPlanId]
			if !exists {
				if dbExists, err := dbr.dataDb.HasData(RATING_PLAN_PREFIX, tpRa.RatingPlanId); err != nil {
					return err
				} else if !dbExists {
					return fmt.Errorf("Could not load rating plans for tag: %v", tpRa.RatingPlanId)
				}
			}
			resultRatingProfile.RatingPlanActivations = append(resultRatingProfile.RatingPlanActivations,
				&RatingPlanActivation{at, tpRa.RatingPlanId,
					utils.FallbackSubjKeys(tpRpf.Direction, tpRpf.Tenant, tpRpf.Category, tpRa.FallbackSubjects)})
		}
		if err := dbr.dataDb.SetRatingProfile(resultRatingProfile); err != nil {
			return err
		}
	}
	return nil
}
开发者ID:intralanman,项目名称:cgrates,代码行数:32,代码来源:loader_db.go


示例3: Execute

func (at *ActionPlan) Execute() (err error) {
	if len(at.AccountIds) == 0 { // nothing to do if no accounts set
		return
	}
	at.resetStartTimeCache()
	aac, err := at.getActions()
	if err != nil {
		utils.Logger.Err(fmt.Sprintf("Failed to get actions for %s: %s", at.ActionsId, err))
		return
	}
	for _, a := range aac {
		if expDate, parseErr := utils.ParseDate(a.ExpirationString); (a.Balance == nil || a.Balance.ExpirationDate.IsZero()) && parseErr == nil && !expDate.IsZero() {
			a.Balance.ExpirationDate = expDate
		}
		// handle remove action
		if a.ActionType == REMOVE_ACCOUNT {
			for _, accId := range at.AccountIds {
				_, err := Guardian.Guard(func() (interface{}, error) {
					if err := accountingStorage.RemoveAccount(accId); err != nil {
						utils.Logger.Warning(fmt.Sprintf("Could not remove account Id: %s: %d", accId, err))
					}
					return 0, nil
				}, 0, accId)
				if err != nil {
					utils.Logger.Warning(fmt.Sprintf("Error executing action plan: %v", err))
				}
			}
			continue // do not go to getActionFunc
		}

		actionFunction, exists := getActionFunc(a.ActionType)
		if !exists {
			// do not allow the action plan to be rescheduled
			at.Timing = nil
			utils.Logger.Crit(fmt.Sprintf("Function type %v not available, aborting execution!", a.ActionType))
			return
		}
		for _, accId := range at.AccountIds {
			_, err := Guardian.Guard(func() (interface{}, error) {
				ub, err := accountingStorage.GetAccount(accId)
				if err != nil {
					utils.Logger.Warning(fmt.Sprintf("Could not get user balances for this id: %s. Skipping!", 0, accId))
					return 0, err
				} else if ub.Disabled && a.ActionType != ENABLE_ACCOUNT {
					return 0, fmt.Errorf("Account %s is disabled", accId)
				}
				//utils.Logger.Info(fmt.Sprintf("Executing %v on %+v", a.ActionType, ub))
				err = actionFunction(ub, nil, a, aac)
				//utils.Logger.Info(fmt.Sprintf("After execute, account: %+v", ub))
				accountingStorage.SetAccount(ub)
				return 0, nil
			}, 0, accId)
			if err != nil {
				utils.Logger.Warning(fmt.Sprintf("Error executing action plan: %v", err))
			}
		}
	}
	storageLogger.LogActionPlan(utils.SCHED_SOURCE, at, aac)
	return
}
开发者ID:foehn,项目名称:cgrates,代码行数:60,代码来源:action_plan.go


示例4: LoadActions

func (csvr *CSVReader) LoadActions() (err error) {
	csvReader, fp, err := csvr.readerFunc(csvr.actionsFn, csvr.sep, utils.ACTIONS_NRCOLS)
	if err != nil {
		log.Print("Could not load action file: ", err)
		// allow writing of the other values
		return nil
	}
	if fp != nil {
		defer fp.Close()
	}
	for record, err := csvReader.Read(); err == nil; record, err = csvReader.Read() {
		tag := record[0]
		var units float64
		if len(record[4]) == 0 { // Not defined
			units = 0.0
		} else {
			units, err = strconv.ParseFloat(record[4], 64)
			if err != nil {
				return fmt.Errorf("Could not parse action units: %v", err)
			}
		}
		var balanceWeight float64
		if len(record[9]) == 0 { // Not defined
			balanceWeight = 0.0
		} else {
			balanceWeight, err = strconv.ParseFloat(record[9], 64)
			if err != nil {
				return fmt.Errorf("Could not parse action balance weight: %v", err)
			}
		}
		weight, err := strconv.ParseFloat(record[12], 64)
		if err != nil {
			return fmt.Errorf("Could not parse action weight: %v", err)
		}
		a := &Action{
			Id:               utils.GenUUID(),
			ActionType:       record[1],
			BalanceType:      record[2],
			Direction:        record[3],
			Weight:           weight,
			ExpirationString: record[5],
			ExtraParameters:  record[11],
			Balance: &Balance{
				Uuid:          utils.GenUUID(),
				Value:         units,
				Weight:        balanceWeight,
				DestinationId: record[6],
				RatingSubject: record[7],
				Category:      record[8],
				SharedGroup:   record[10],
			},
		}
		if _, err := utils.ParseDate(a.ExpirationString); err != nil {
			return fmt.Errorf("Could not parse expiration time: %v", err)
		}
		csvr.actions[tag] = append(csvr.actions[tag], a)
	}
	return
}
开发者ID:intralanman,项目名称:cgrates,代码行数:59,代码来源:loader_csv.go


示例5: importRatingProfiles

func (self *TPCSVImporter) importRatingProfiles(fn string) error {
	if self.Verbose {
		log.Printf("Processing file: <%s> ", fn)
	}
	fParser, err := NewTPCSVFileParser(self.DirPath, fn)
	if err != nil {
		return err
	}
	lineNr := 0
	rpfs := make(map[string]*utils.TPRatingProfile)
	for {
		lineNr++
		record, err := fParser.ParseNextLine()
		if err == io.EOF { // Reached end of file
			break
		} else if err != nil {
			if self.Verbose {
				log.Printf("Ignoring line %d, warning: <%s> ", lineNr, err.Error())
			}
			continue
		}
		direction, tenant, tor, subject, ratingPlanTag, fallbacksubject := record[0], record[1], record[2], record[3], record[5], record[6]
		_, err = utils.ParseDate(record[4])
		if err != nil {
			if self.Verbose {
				log.Printf("Ignoring line %d, warning: <%s> ", lineNr, err.Error())
			}
			continue
		}
		loadId := utils.CSV_LOAD //Autogenerate rating profile id
		if self.ImportId != "" {
			loadId += "_" + self.ImportId
		}
		newRp := &utils.TPRatingProfile{
			TPid:      self.TPid,
			LoadId:    loadId,
			Tenant:    tenant,
			Category:  tor,
			Direction: direction,
			Subject:   subject,
			RatingPlanActivations: []*utils.TPRatingActivation{
				&utils.TPRatingActivation{ActivationTime: record[4], RatingPlanId: ratingPlanTag, FallbackSubjects: fallbacksubject}},
		}
		if rp, hasIt := rpfs[newRp.KeyId()]; hasIt {
			rp.RatingPlanActivations = append(rp.RatingPlanActivations, newRp.RatingPlanActivations...)
		} else {
			rpfs[newRp.KeyId()] = newRp
		}
	}
	if err := self.StorDb.SetTPRatingProfiles(self.TPid, rpfs); err != nil {
		if self.Verbose {
			log.Printf("Ignoring line %d, storDb operational error: <%s> ", lineNr, err.Error())
		}
	}

	return nil
}
开发者ID:intralanman,项目名称:cgrates,代码行数:57,代码来源:tpimporter_csv.go


示例6: AddBalance

func (self *ApierV1) AddBalance(attr *AttrAddBalance, reply *string) error {
	expTime, err := utils.ParseDate(attr.ExpiryTime)
	if err != nil {
		*reply = err.Error()
		return err
	}
	tag := utils.ConcatenatedKey(attr.Direction, attr.Tenant, attr.Account)
	if _, err := self.AccountDb.GetAccount(tag); err != nil {
		// create user balance if not exists
		account := &engine.Account{
			Id: tag,
		}
		if err := self.AccountDb.SetAccount(account); err != nil {
			*reply = err.Error()
			return err
		}
	}
	at := &engine.ActionPlan{
		AccountIds: []string{tag},
	}
	if attr.Direction == "" {
		attr.Direction = engine.OUTBOUND
	}
	aType := engine.DEBIT
	// reverse the sign as it is a debit
	attr.Value = -attr.Value

	if attr.Overwrite {
		aType = engine.DEBIT_RESET
	}
	at.SetActions(engine.Actions{
		&engine.Action{
			ActionType:  aType,
			BalanceType: attr.BalanceType,
			Direction:   attr.Direction,
			Balance: &engine.Balance{
				Uuid:           attr.BalanceUuid,
				Id:             attr.BalanceId,
				Value:          attr.Value,
				ExpirationDate: expTime,
				RatingSubject:  attr.RatingSubject,
				DestinationIds: attr.DestinationId,
				Weight:         attr.Weight,
				SharedGroup:    attr.SharedGroup,
				Disabled:       attr.Disabled,
			},
		},
	})
	if err := at.Execute(); err != nil {
		*reply = err.Error()
		return err
	}
	*reply = OK
	return nil
}
开发者ID:nikbyte,项目名称:cgrates,代码行数:55,代码来源:apier.go


示例7: LoadRatingProfiles

func (csvr *CSVReader) LoadRatingProfiles() (err error) {
	csvReader, fp, err := csvr.readerFunc(csvr.ratingprofilesFn, csvr.sep, utils.RATE_PROFILES_NRCOLS)
	if err != nil {
		log.Print("Could not load rating profiles file: ", err)
		// allow writing of the other values
		return nil
	}
	if fp != nil {
		defer fp.Close()
	}
	for record, err := csvReader.Read(); err == nil; record, err = csvReader.Read() {
		direction, tenant, tor, subject, fallbacksubject := record[0], record[1], record[2], record[3], record[6]
		at, err := utils.ParseDate(record[4])
		if err != nil {
			return fmt.Errorf("Cannot parse activation time from %v", record[4])
		}
		// extract aliases from subject
		aliases := strings.Split(subject, ";")
		csvr.dirtyRpAliases = append(csvr.dirtyRpAliases, &TenantRatingSubject{Tenant: tenant, Subject: aliases[0]})
		if len(aliases) > 1 {
			subject = aliases[0]
			for _, alias := range aliases[1:] {
				csvr.rpAliases[utils.RatingSubjectAliasKey(tenant, alias)] = subject
			}
		}
		key := fmt.Sprintf("%s:%s:%s:%s", direction, tenant, tor, subject)
		rp, ok := csvr.ratingProfiles[key]
		if !ok {
			rp = &RatingProfile{Id: key}
			csvr.ratingProfiles[key] = rp
		}
		_, exists := csvr.ratingPlans[record[5]]
		if !exists && csvr.dataStorage != nil {
			if exists, err = csvr.dataStorage.HasData(RATING_PLAN_PREFIX, record[5]); err != nil {
				return err
			}
		}
		if !exists {
			return fmt.Errorf("Could not load rating plans for tag: %v", record[5])
		}
		rpa := &RatingPlanActivation{
			ActivationTime: at,
			RatingPlanId:   record[5],
			FallbackKeys:   utils.FallbackSubjKeys(direction, tenant, tor, fallbacksubject),
		}
		rp.RatingPlanActivations = append(rp.RatingPlanActivations, rpa)
		csvr.ratingProfiles[rp.Id] = rp
	}
	return
}
开发者ID:intralanman,项目名称:cgrates,代码行数:50,代码来源:loader_csv.go


示例8: SetRatingProfile

// Sets a specific rating profile working with data directly in the RatingDb without involving storDb
func (self *ApierV1) SetRatingProfile(attrs AttrSetRatingProfile, reply *string) error {
	if missing := utils.MissingStructFields(&attrs, []string{"Tenant", "TOR", "Direction", "Subject", "RatingPlanActivations"}); len(missing) != 0 {
		return utils.NewErrMandatoryIeMissing(missing...)
	}
	for _, rpa := range attrs.RatingPlanActivations {
		if missing := utils.MissingStructFields(rpa, []string{"ActivationTime", "RatingPlanId"}); len(missing) != 0 {
			return fmt.Errorf("%s:RatingPlanActivation:%v", utils.ErrMandatoryIeMissing.Error(), missing)
		}
	}
	tpRpf := utils.TPRatingProfile{Tenant: attrs.Tenant, Category: attrs.Category, Direction: attrs.Direction, Subject: attrs.Subject}
	keyId := tpRpf.KeyId()
	if !attrs.Overwrite {
		if exists, err := self.RatingDb.HasData(utils.RATING_PROFILE_PREFIX, keyId); err != nil {
			return utils.NewErrServerError(err)
		} else if exists {
			return utils.ErrExists
		}
	}
	rpfl := &engine.RatingProfile{Id: keyId, RatingPlanActivations: make(engine.RatingPlanActivations, len(attrs.RatingPlanActivations))}
	for idx, ra := range attrs.RatingPlanActivations {
		at, err := utils.ParseDate(ra.ActivationTime)
		if err != nil {
			return fmt.Errorf(fmt.Sprintf("%s:Cannot parse activation time from %v", utils.ErrServerError.Error(), ra.ActivationTime))
		}
		if exists, err := self.RatingDb.HasData(utils.RATING_PLAN_PREFIX, ra.RatingPlanId); err != nil {
			return utils.NewErrServerError(err)
		} else if !exists {
			return fmt.Errorf(fmt.Sprintf("%s:RatingPlanId:%s", utils.ErrNotFound.Error(), ra.RatingPlanId))
		}
		rpfl.RatingPlanActivations[idx] = &engine.RatingPlanActivation{ActivationTime: at, RatingPlanId: ra.RatingPlanId,
			FallbackKeys: utils.FallbackSubjKeys(tpRpf.Direction, tpRpf.Tenant, tpRpf.Category, ra.FallbackSubjects)}
	}
	if err := self.RatingDb.SetRatingProfile(rpfl); err != nil {
		return utils.NewErrServerError(err)
	}
	//Automatic cache of the newly inserted rating profile
	if err := self.RatingDb.CacheRatingPrefixValues(map[string][]string{
		utils.RATING_PROFILE_PREFIX: []string{utils.RATING_PROFILE_PREFIX + keyId},
	}); err != nil {
		return err
	}
	*reply = OK
	return nil
}
开发者ID:nikbyte,项目名称:cgrates,代码行数:45,代码来源:apier.go


示例9: Execute

func (at *ActionTrigger) Execute(ub *Account, sq *StatsQueueTriggered) (err error) {
	// check for min sleep time
	if at.Recurrent && !at.lastExecutionTime.IsZero() && time.Since(at.lastExecutionTime) < at.MinSleep {
		return
	}
	at.lastExecutionTime = time.Now()
	if ub != nil && ub.Disabled {
		return fmt.Errorf("User %s is disabled and there are triggers in action!", ub.Id)
	}
	// does NOT need to Lock() because it is triggered from a method that took the Lock
	var aac Actions
	aac, err = accountingStorage.GetActions(at.ActionsId, false)
	aac.Sort()
	if err != nil {
		Logger.Err(fmt.Sprintf("Failed to get actions: %v", err))
		return
	}
	at.Executed = true
	atLeastOneActionExecuted := false
	for _, a := range aac {
		if a.Balance == nil {
			a.Balance = &Balance{}
		}
		a.Balance.ExpirationDate, _ = utils.ParseDate(a.ExpirationString)
		actionFunction, exists := getActionFunc(a.ActionType)
		if !exists {
			Logger.Warning(fmt.Sprintf("Function type %v not available, aborting execution!", a.ActionType))
			return
		}
		//go Logger.Info(fmt.Sprintf("Executing %v, %v: %v", ub, sq, a))
		err = actionFunction(ub, sq, a)
		if err == nil {
			atLeastOneActionExecuted = true
		}
	}
	if !atLeastOneActionExecuted || at.Recurrent {
		at.Executed = false
	}
	if ub != nil {
		storageLogger.LogActionTrigger(ub.Id, RATER_SOURCE, at, aac)
		accountingStorage.SetAccount(ub)
	}
	return
}
开发者ID:intralanman,项目名称:cgrates,代码行数:44,代码来源:action_trigger.go


示例10: SetRatingProfile

// Sets a specific rating profile working with data directly in the RatingDb without involving storDb
func (self *ApierV1) SetRatingProfile(attrs AttrSetRatingProfile, reply *string) error {
	if missing := utils.MissingStructFields(&attrs, []string{"Tenant", "TOR", "Direction", "Subject", "RatingPlanActivations"}); len(missing) != 0 {
		return fmt.Errorf("%s:%v", utils.ERR_MANDATORY_IE_MISSING, missing)
	}
	for _, rpa := range attrs.RatingPlanActivations {
		if missing := utils.MissingStructFields(rpa, []string{"ActivationTime", "RatingPlanId"}); len(missing) != 0 {
			return fmt.Errorf("%s:RatingPlanActivation:%v", utils.ERR_MANDATORY_IE_MISSING, missing)
		}
	}
	tpRpf := utils.TPRatingProfile{Tenant: attrs.Tenant, Category: attrs.Category, Direction: attrs.Direction, Subject: attrs.Subject}
	keyId := tpRpf.KeyId()
	if !attrs.Overwrite {
		if exists, err := self.RatingDb.HasData(engine.RATING_PROFILE_PREFIX, keyId); err != nil {
			return fmt.Errorf("%s:%s", utils.ERR_SERVER_ERROR, err.Error())
		} else if exists {
			return errors.New(utils.ERR_EXISTS)
		}
	}
	rpfl := &engine.RatingProfile{Id: keyId, RatingPlanActivations: make(engine.RatingPlanActivations, len(attrs.RatingPlanActivations))}
	for idx, ra := range attrs.RatingPlanActivations {
		at, err := utils.ParseDate(ra.ActivationTime)
		if err != nil {
			return fmt.Errorf(fmt.Sprintf("%s:Cannot parse activation time from %v", utils.ERR_SERVER_ERROR, ra.ActivationTime))
		}
		if exists, err := self.RatingDb.HasData(engine.RATING_PLAN_PREFIX, ra.RatingPlanId); err != nil {
			return fmt.Errorf("%s:%s", utils.ERR_SERVER_ERROR, err.Error())
		} else if !exists {
			return fmt.Errorf(fmt.Sprintf("%s:RatingPlanId:%s", utils.ERR_NOT_FOUND, ra.RatingPlanId))
		}
		rpfl.RatingPlanActivations[idx] = &engine.RatingPlanActivation{ActivationTime: at, RatingPlanId: ra.RatingPlanId,
			FallbackKeys: utils.FallbackSubjKeys(tpRpf.Direction, tpRpf.Tenant, tpRpf.Category, ra.FallbackSubjects)}
	}
	if err := self.RatingDb.SetRatingProfile(rpfl); err != nil {
		return fmt.Errorf("%s:%s", utils.ERR_SERVER_ERROR, err.Error())
	}
	//Automatic cache of the newly inserted rating profile
	didNotChange := []string{}
	if err := self.RatingDb.CacheRating(didNotChange, didNotChange, []string{engine.RATING_PROFILE_PREFIX + keyId}, didNotChange, didNotChange); err != nil {
		return err
	}
	*reply = OK
	return nil
}
开发者ID:intralanman,项目名称:cgrates,代码行数:44,代码来源:apier.go


示例11: LoadRatingProfilesFiltered

func (tpr *TpReader) LoadRatingProfilesFiltered(qriedRpf *TpRatingProfile) error {
	var resultRatingProfile *RatingProfile
	mpTpRpfs, err := tpr.lr.GetTpRatingProfiles(qriedRpf)
	if err != nil {
		return fmt.Errorf("no RateProfile for filter %v, error: %v", qriedRpf, err)
	}

	rpfs, err := TpRatingProfiles(mpTpRpfs).GetRatingProfiles()
	if err != nil {
		return err
	}
	for _, tpRpf := range rpfs {
		resultRatingProfile = &RatingProfile{Id: tpRpf.KeyId()}
		for _, tpRa := range tpRpf.RatingPlanActivations {
			at, err := utils.ParseDate(tpRa.ActivationTime)
			if err != nil {
				return fmt.Errorf("cannot parse activation time from %v", tpRa.ActivationTime)
			}
			_, exists := tpr.ratingPlans[tpRa.RatingPlanId]
			if !exists && tpr.ratingStorage != nil {
				if exists, err = tpr.ratingStorage.HasData(utils.RATING_PLAN_PREFIX, tpRa.RatingPlanId); err != nil {
					return err
				}
			}
			if !exists {
				return fmt.Errorf("could not load rating plans for tag: %v", tpRa.RatingPlanId)
			}
			resultRatingProfile.RatingPlanActivations = append(resultRatingProfile.RatingPlanActivations,
				&RatingPlanActivation{
					ActivationTime:  at,
					RatingPlanId:    tpRa.RatingPlanId,
					FallbackKeys:    utils.FallbackSubjKeys(tpRpf.Direction, tpRpf.Tenant, tpRpf.Category, tpRa.FallbackSubjects),
					CdrStatQueueIds: strings.Split(tpRa.CdrStatQueueIds, utils.INFIELD_SEP),
				})
		}
		if err := tpr.ratingStorage.SetRatingProfile(resultRatingProfile); err != nil {
			return err
		}
	}
	return nil
}
开发者ID:foehn,项目名称:cgrates,代码行数:41,代码来源:tp_reader.go


示例12: Execute

func (at *ActionTiming) Execute() (err error) {
	if len(at.AccountIds) == 0 { // nothing to do if no accounts set
		return
	}
	at.resetStartTimeCache()
	aac, err := at.getActions()
	if err != nil {
		Logger.Err(fmt.Sprintf("Failed to get actions for %s: %s", at.ActionsId, err))
		return
	}
	for _, a := range aac {
		if expDate, parseErr := utils.ParseDate(a.ExpirationString); a.Balance.ExpirationDate.IsZero() && parseErr == nil && !expDate.IsZero() {
			a.Balance.ExpirationDate = expDate
		}
		actionFunction, exists := getActionFunc(a.ActionType)
		if !exists {
			Logger.Crit(fmt.Sprintf("Function type %v not available, aborting execution!", a.ActionType))
			return
		}
		for _, ubId := range at.AccountIds {
			_, err := AccLock.Guard(ubId, func() (float64, error) {
				ub, err := accountingStorage.GetAccount(ubId)
				if err != nil {
					Logger.Warning(fmt.Sprintf("Could not get user balances for this id: %s. Skipping!", ubId))
					return 0, err
				} else if ub.Disabled {
					return 0, fmt.Errorf("User %s is disabled", ubId)
				}
				//Logger.Info(fmt.Sprintf("Executing %v on %v", a.ActionType, ub.Id))
				err = actionFunction(ub, nil, a)
				accountingStorage.SetAccount(ub)
				return 0, nil
			})
			if err != nil {
				Logger.Warning(fmt.Sprintf("Error executing action timing: %v", err))
			}
		}
	}
	storageLogger.LogActionTiming(SCHED_SOURCE, at, aac)
	return
}
开发者ID:intralanman,项目名称:cgrates,代码行数:41,代码来源:action_timing.go


示例13: EnableDisableBalance

func (self *ApierV1) EnableDisableBalance(attr *AttrAddBalance, reply *string) error {
	expTime, err := utils.ParseDate(attr.ExpiryTime)
	if err != nil {
		*reply = err.Error()
		return err
	}
	tag := utils.ConcatenatedKey(attr.Direction, attr.Tenant, attr.Account)
	if _, err := self.AccountDb.GetAccount(tag); err != nil {
		return utils.ErrNotFound
	}
	at := &engine.ActionPlan{
		AccountIds: []string{tag},
	}
	if attr.Direction == "" {
		attr.Direction = utils.OUT
	}
	at.SetActions(engine.Actions{
		&engine.Action{
			ActionType:  engine.ENABLE_DISABLE_BALANCE,
			BalanceType: attr.BalanceType,
			Direction:   attr.Direction,
			Balance: &engine.Balance{
				Uuid:           attr.BalanceUuid,
				Id:             attr.BalanceId,
				Value:          attr.Value,
				ExpirationDate: expTime,
				RatingSubject:  attr.RatingSubject,
				DestinationIds: attr.DestinationId,
				Weight:         attr.Weight,
				SharedGroup:    attr.SharedGroup,
				Disabled:       attr.Disabled,
			},
		},
	})
	if err := at.Execute(); err != nil {
		*reply = err.Error()
		return err
	}
	*reply = OK
	return nil
}
开发者ID:henrylee2cn,项目名称:cgrates,代码行数:41,代码来源:apier.go


示例14: LoadRatingProfiles

func (dbr *DbReader) LoadRatingProfiles() error {
	mpTpRpfs, err := dbr.storDb.GetTpRatingProfiles(&utils.TPRatingProfile{TPid: dbr.tpid}) //map[string]*utils.TPRatingProfile
	if err != nil {
		return err
	}
	for _, tpRpf := range mpTpRpfs {
		// extract aliases from subject
		aliases := strings.Split(tpRpf.Subject, ";")
		dbr.dirtyRpAliases = append(dbr.dirtyRpAliases, &TenantRatingSubject{Tenant: tpRpf.Tenant, Subject: aliases[0]})
		if len(aliases) > 1 {
			tpRpf.Subject = aliases[0]
			for _, alias := range aliases[1:] {
				dbr.rpAliases[utils.RatingSubjectAliasKey(tpRpf.Tenant, alias)] = tpRpf.Subject
			}
		}
		rpf := &RatingProfile{Id: tpRpf.KeyId()}
		for _, tpRa := range tpRpf.RatingPlanActivations {
			at, err := utils.ParseDate(tpRa.ActivationTime)
			if err != nil {
				return fmt.Errorf("Cannot parse activation time from %v", tpRa.ActivationTime)
			}
			_, exists := dbr.ratingPlans[tpRa.RatingPlanId]
			if !exists {
				if dbExists, err := dbr.dataDb.HasData(RATING_PLAN_PREFIX, tpRa.RatingPlanId); err != nil {
					return err
				} else if !dbExists {
					return fmt.Errorf("Could not load rating plans for tag: %v", tpRa.RatingPlanId)
				}
			}
			rpf.RatingPlanActivations = append(rpf.RatingPlanActivations,
				&RatingPlanActivation{
					ActivationTime: at,
					RatingPlanId:   tpRa.RatingPlanId,
					FallbackKeys:   utils.FallbackSubjKeys(tpRpf.Direction, tpRpf.Tenant, tpRpf.Category, tpRa.FallbackSubjects),
				})
		}
		dbr.ratingProfiles[tpRpf.KeyId()] = rpf
	}
	return nil
}
开发者ID:intralanman,项目名称:cgrates,代码行数:40,代码来源:loader_db.go


示例15: LoadRatingProfiles

func (tpr *TpReader) LoadRatingProfiles() (err error) {
	tps, err := tpr.lr.GetTpRatingProfiles(&TpRatingProfile{Tpid: tpr.tpid})
	if err != nil {
		return err
	}
	mpTpRpfs, err := TpRatingProfiles(tps).GetRatingProfiles()

	if err != nil {
		return err
	}
	for _, tpRpf := range mpTpRpfs {
		rpf := &RatingProfile{Id: tpRpf.KeyId()}
		for _, tpRa := range tpRpf.RatingPlanActivations {
			at, err := utils.ParseDate(tpRa.ActivationTime)
			if err != nil {
				return fmt.Errorf("cannot parse activation time from %v", tpRa.ActivationTime)
			}
			_, exists := tpr.ratingPlans[tpRa.RatingPlanId]
			if !exists && tpr.ratingStorage != nil { // Only query if there is a connection, eg on dry run there is none
				if exists, err = tpr.ratingStorage.HasData(utils.RATING_PLAN_PREFIX, tpRa.RatingPlanId); err != nil {
					return err
				}
			}
			if !exists {
				return fmt.Errorf("could not load rating plans for tag: %v", tpRa.RatingPlanId)
			}
			rpf.RatingPlanActivations = append(rpf.RatingPlanActivations,
				&RatingPlanActivation{
					ActivationTime:  at,
					RatingPlanId:    tpRa.RatingPlanId,
					FallbackKeys:    utils.FallbackSubjKeys(tpRpf.Direction, tpRpf.Tenant, tpRpf.Category, tpRa.FallbackSubjects),
					CdrStatQueueIds: strings.Split(tpRa.CdrStatQueueIds, utils.INFIELD_SEP),
				})
		}
		tpr.ratingProfiles[tpRpf.KeyId()] = rpf
	}
	return nil
}
开发者ID:foehn,项目名称:cgrates,代码行数:38,代码来源:tp_reader.go


示例16: RemoveBalances

func (self *ApierV1) RemoveBalances(attr *AttrAddBalance, reply *string) error {
	expTime, err := utils.ParseDate(attr.ExpiryTime)
	if err != nil {
		*reply = err.Error()
		return err
	}
	accId := utils.ConcatenatedKey(attr.Tenant, attr.Account)
	if _, err := self.AccountDb.GetAccount(accId); err != nil {
		return utils.ErrNotFound
	}
	at := &engine.ActionPlan{
		AccountIds: []string{accId},
	}
	at.SetActions(engine.Actions{
		&engine.Action{
			ActionType:  engine.REMOVE_BALANCE,
			BalanceType: attr.BalanceType,
			Balance: &engine.Balance{
				Uuid:           attr.BalanceUuid,
				Id:             attr.BalanceId,
				Value:          attr.Value,
				ExpirationDate: expTime,
				RatingSubject:  attr.RatingSubject,
				Directions:     utils.ParseStringMap(attr.Directions),
				DestinationIds: utils.ParseStringMap(attr.DestinationIds),
				Weight:         attr.Weight,
				SharedGroups:   utils.ParseStringMap(attr.SharedGroups),
				Disabled:       attr.Disabled,
			},
		},
	})
	if err := at.Execute(); err != nil {
		*reply = err.Error()
		return err
	}
	*reply = OK
	return nil
}
开发者ID:kevinlovesing,项目名称:cgrates,代码行数:38,代码来源:apier.go


示例17: LoadAccountActionsFiltered


//.........这里部分代码省略.........
							AccountID: accID,
							ActionsID: at.ActionsID,
						}
						if err = tpr.ratingStorage.PushTask(t); err != nil {
							return err
						}
					}
				}
			}
			// write action plan
			err = tpr.ratingStorage.SetActionPlan(accountAction.ActionPlanId, actionPlan, false)
			if err != nil {
				return errors.New(err.Error() + " (SetActionPlan): " + accountAction.ActionPlanId)
			}
		}
		// action triggers
		var actionTriggers ActionTriggers
		//ActionTriggerPriotityList []*ActionTrigger
		if accountAction.ActionTriggersId != "" {
			tpatrs, err := tpr.lr.GetTpActionTriggers(tpr.tpid, accountAction.ActionTriggersId)
			if err != nil {
				return errors.New(err.Error() + " (ActionTriggers): " + accountAction.ActionTriggersId)
			}
			atrs, err := TpActionTriggers(tpatrs).GetActionTriggers()
			if err != nil {
				return err
			}

			atrsMap := make(map[string][]*ActionTrigger)
			for key, atrsLst := range atrs {
				atrs := make([]*ActionTrigger, len(atrsLst))
				for idx, apiAtr := range atrsLst {
					minSleep, _ := utils.ParseDurationWithSecs(apiAtr.MinSleep)
					balanceExpTime, _ := utils.ParseDate(apiAtr.BalanceExpirationDate)
					expTime, _ := utils.ParseTimeDetectLayout(apiAtr.ExpirationDate, tpr.timezone)
					actTime, _ := utils.ParseTimeDetectLayout(apiAtr.ActivationDate, tpr.timezone)
					if apiAtr.UniqueID == "" {
						apiAtr.UniqueID = utils.GenUUID()
					}
					atrs[idx] = &ActionTrigger{
						ID:                    key,
						UniqueID:              apiAtr.UniqueID,
						ThresholdType:         apiAtr.ThresholdType,
						ThresholdValue:        apiAtr.ThresholdValue,
						Recurrent:             apiAtr.Recurrent,
						MinSleep:              minSleep,
						ExpirationDate:        expTime,
						ActivationDate:        actTime,
						BalanceId:             apiAtr.BalanceId,
						BalanceType:           apiAtr.BalanceType,
						BalanceDirections:     utils.ParseStringMap(apiAtr.BalanceDirections),
						BalanceDestinationIds: utils.ParseStringMap(apiAtr.BalanceDestinationIds),
						BalanceWeight:         apiAtr.BalanceWeight,
						BalanceExpirationDate: balanceExpTime,
						BalanceTimingTags:     utils.ParseStringMap(apiAtr.BalanceTimingTags),
						BalanceRatingSubject:  apiAtr.BalanceRatingSubject,
						BalanceCategories:     utils.ParseStringMap(apiAtr.BalanceCategories),
						BalanceSharedGroups:   utils.ParseStringMap(apiAtr.BalanceSharedGroups),
						BalanceBlocker:        apiAtr.BalanceBlocker,
						BalanceDisabled:       apiAtr.BalanceDisabled,
						Weight:                apiAtr.Weight,
						ActionsId:             apiAtr.ActionsId,
					}
				}
				atrsMap[key] = atrs
			}
开发者ID:bhepp,项目名称:cgrates,代码行数:67,代码来源:tp_reader.go


示例18: Execute

func (at *ActionPlan) Execute() (err error) {
	if len(at.AccountIds) == 0 { // nothing to do if no accounts set
		return
	}
	at.resetStartTimeCache()
	aac, err := at.getActions()
	if err != nil {
		utils.Logger.Err(fmt.Sprintf("Failed to get actions for %s: %s", at.ActionsId, err))
		return
	}
	_, err = Guardian.Guard(func() (interface{}, error) {
		for _, accId := range at.AccountIds {
			ub, err := accountingStorage.GetAccount(accId)
			if err != nil {
				utils.Logger.Warning(fmt.Sprintf("Could not get user balances for this id: %s. Skipping!", accId))
				return 0, err
			}
			transactionFailed := false
			toBeSaved := true
			for _, a := range aac {
				if ub.Disabled && a.ActionType != ENABLE_ACCOUNT {
					continue // disabled acocunts are not removed from action  plan
					//return 0, fmt.Errorf("Account %s is disabled", accId)
				}
				if expDate, parseErr := utils.ParseDate(a.ExpirationString); (a.Balance == nil || a.Balance.ExpirationDate.IsZero()) && parseErr == nil && !expDate.IsZero() {
					a.Balance.ExpirationDate = expDate
				}
				// handle remove action
				if a.ActionType == REMOVE_ACCOUNT {
					if err := accountingStorage.RemoveAccount(accId); err != nil {
						utils.Logger.Err(fmt.Sprintf("Could not remove account Id: %s: %v", accId, err))
						transactionFailed = true
						break
					}
					// clean the account id from all action plans
					allATs, err := ratingStorage.GetAllActionPlans()
					if err != nil && err != utils.ErrNotFound {
						utils.Logger.Err(fmt.Sprintf("Could not get action plans: %s: %v", accId, err))
						transactionFailed = true
						break
					}
					for key, ats := range allATs {
						changed := false
						for _, at := range ats {
							for i := 0; i < len(at.AccountIds); i++ {
								if at.AccountIds[i] == accId {
									// delete without preserving order
									at.AccountIds[i] = at.AccountIds[len(at.AccountIds)-1]
									at.AccountIds = at.AccountIds[:len(at.AccountIds)-1]
									i -= 1
									changed = true
								}
							}
						}
						if changed {
							// save action plan
							ratingStorage.SetActionPlans(key, ats)
							// cache
							ratingStorage.CacheRatingPrefixValues(map[string][]string{utils.ACTION_PLAN_PREFIX: []string{utils.ACTION_PLAN_PREFIX + key}})
						}
					}
					toBeSaved = false
					continue // do not go to getActionFunc
					// TODO: maybe we should break here as the account is gone
					// will leave continue for now as the next action can create another acount
				}
				actionFunction, exists := getActionFunc(a.ActionType)
				if !exists {
					// do not allow the action plan to be rescheduled
					at.Timing = nil
					utils.Logger.Err(fmt.Sprintf("Function type %v not available, aborting execution!", a.ActionType))
					transactionFailed = true
					break
				}
				if err := actionFunction(ub, nil, a, aac); err != nil {
					utils.Logger.Err(fmt.Sprintf("Error executing action %s: %v!", a.ActionType, err))
					transactionFailed = true
					break
				}
				toBeSaved = true
			}
			if !transactionFailed && toBeSaved {
				accountingStorage.SetAccount(ub)
			}
		}
		return 0, nil
	}, 0, at.AccountIds...)
	if err != nil {
		utils.Logger.Warning(fmt.Sprintf("Error executing action plan: %v", err))
		return err
	}
	storageLogger.LogActionPlan(utils.SCHED_SOURCE, at, aac)
	return
}
开发者ID:kevinlovesing,项目名称:cgrates,代码行数:94,代码来源:action_plan.go


示例19: Execute

func (at *ActionTiming) Execute() (err error) {
	at.ResetStartTimeCache()
	aac, err := at.getActions()
	if err != nil {
		utils.Logger.Err(fmt.Sprintf("Failed to get actions for %s: %s", at.ActionsID, err))
		return
	}
	for accID, _ := range at.accountIDs {
		_, err = Guardian.Guard(func() (interface{}, error) {
			acc, err := accountingStorage.GetAccount(accID)
			if err != nil {
				utils.Logger.Warning(fmt.Sprintf("Could not get account id: %s. Skipping!", accID))
				return 0, err
			}
			transactionFailed := false
			removeAccountActionFound := false
			for _, a := range aac {
				// check action filter
				if len(a.Filter) > 0 {
					matched, err := acc.matchActionFilter(a.Filter)
					//log.Print("Checkng: ", a.Filter, matched)
					if err != nil {
						return 0, err
					}
					if !matched {
						continue
					}
				}
				if a.Balance == nil {
					a.Balance = &BalanceFilter{}
				}
				if a.ExpirationString != "" { // if it's *unlimited then it has to be zero time
					if expDate, parseErr := utils.ParseDate(a.ExpirationString); parseErr == nil {
						a.Balance.ExpirationDate = &time.Time{}
						*a.Balance.ExpirationDate = expDate
					}
				}

				actionFunction, exists := getActionFunc(a.ActionType)
				if !exists {
					// do not allow the action plan to be rescheduled
					at.Timing = nil
					utils.Logger.Err(fmt.Sprintf("Function type %v not available, aborting execution!", a.ActionType))
					transactionFailed = true
					break
				}
				if err := actionFunction(acc, nil, a, aac); err != nil {
					utils.Logger.Err(fmt.Sprintf("Error executing action %s: %v!", a.ActionType, err))
					transactionFailed = true
					break
				}
				if a.ActionType == REMOVE_ACCOUNT {
					removeAccountActionFound = true
				}
			}
			if !transactionFailed && !removeAccountActionFound {
				accountingStorage.SetAccount(acc)
			}
			return 0, nil
		}, 0, accID)
	}
	if len(at.accountIDs) == 0 { // action timing executing without accounts
		for _, a := range aac {
			if expDate, parseErr := utils.ParseDate(a.ExpirationString); (a.Balance == nil || a.Balance.EmptyExpirationDate()) &&
				parseErr == nil && !expDate.IsZero() {
				a.Balance.ExpirationDate = &time.Time{}
				*a.Balance.ExpirationDate = expDate
			}

			actionFunction, exists := getActionFunc(a.ActionType)
			if !exists {
				// do not allow the action plan to be rescheduled
				at.Timing = nil
				utils.Logger.Err(fmt.Sprintf("Function type %v not available, aborting execution!", a.ActionType))
				break
			}
			if err := actionFunction(nil, nil, a, aac); err != nil {
				utils.Logger.Err(fmt.Sprintf("Error executing accountless action %s: %v!", a.ActionType, err))
				break
			}
		}
	}
	if err != nil {
		utils.Logger.Warning(fmt.Sprintf("Error executing action plan: %v", err))
		return err
	}
	storageLogger.LogActionTiming(utils.SCHED_SOURCE, at, aac)
	return
}
开发者ID:iwada,项目名称:cgrates,代码行数:89,代码来源:action_plan.go


示例20: Execute

func (at *ActionTrigger) Execute(ub *Account, sq *StatsQueueTriggered) (err error) {
	// check for min sleep time
	if at.Recurrent && !at.LastExecutionTime.IsZero() && time.Since(at.LastExecutionTime) < at.MinSleep {
		return
	}
	at.LastExecutionTime = time.Now()
	if ub != nil && ub.Disabled {
		return fmt.Errorf("User %s is disabled and there are triggers in action!", ub.ID)
	}
	// does NOT need to Lock() because it is triggered from a method that took the Lock
	var aac Actions
	aac, err = ratingStorage.GetActions(at.ActionsID, false, utils.NonTransactional)
	if err != nil {
		utils.Logger.Err(fmt.Sprintf("Failed to get actions: %v", err))
		return
	}
	aac.Sort()
	at.Executed = true
	transactionFailed := false
	removeAccountActionFound := false
	for _, a := range aac {
		// check action filter
		if len(a.Filter) > 0 {
			matched, err := ub.matchActionFilter(a.Filter)
			if err != nil {
				return err
			}
			if !matched {
				continue
			}
		}
		if a.Balance == nil { 

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang utils.ParseDurationWithSecs函数代码示例发布时间:2022-05-23
下一篇:
Golang utils.NewStringMap函数代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap