예제 #1
0
func tasksInDays(c *macaron.Context) {
	type Result struct {
		Date  string
		Tasks []Task
	}
	var results []Result
	date, err := time.Parse(DateFormat, c.Query("date"))
	finish := now.New(date).EndOfMonth().AddDate(0, 0, 1)
	if err != nil {
		serverError(c, "error parsing date %s", c.Query("date"))
		return
	}
	limit, err := strconv.ParseInt(c.Query("limit"), 10, 32)
	if err != nil {
		serverError(c, "error parsing limit int %s", c.Query("limit"))
	}
	date = now.New(date).BeginningOfMonth()
	for date.Month() != finish.Month() {
		var tasks []Task
		tasksInScope(&tasks, ScopeDay, date)
		results = append(results, Result{date.Format("2006-01-02"), tasks})
		date = date.AddDate(0, 0, 1)
		if date.Day() == int(limit) {
			break
		}
	}

	c.JSON(200, results)
}
예제 #2
0
func (w Window) makeWindows(left, right TimeShiftFunc) []Window {
	var ws []Window
	if w.From.After(w.Until) {
		return ws
	}
	var start, end time.Time
	from := w.From
	for {
		switch {
		case len(ws) == 0:
			start = now.New(w.From).BeginningOfDay()
		default:
			start = left(from)
		}
		end = right(from)
		if end.After(w.Until) {
			// discard end and use the end of day of until
			ws = append(ws, Window{From: start, Until: now.New(w.Until).EndOfDay()})
			break
		}
		ws = append(ws, Window{From: start, Until: end})
		from = end.Add(oneDay)
	}
	return ws
}
예제 #3
0
func (w Window) Weekly() []Window {
	shiftLeft := func(t time.Time) time.Time {
		return now.New(t).BeginningOfWeek()
	}
	shiftRight := func(t time.Time) time.Time {
		return now.New(t).EndOfWeek()
	}
	return w.makeWindows(shiftLeft, shiftRight)
}
예제 #4
0
func PostersGetMonth(db *gorp.DbMap, t int64) (Posters, error) {
	tm := unixtime.Parse(t).In(time.Now().Location())
	startMonth := now.New(tm).BeginningOfMonth().UnixNano()
	startMonth -= 24 * 60 * 60
	endMonth := now.New(tm).EndOfMonth().UnixNano()
	endMonth += 24 * 60 * 60
	var p Posters
	_, err := db.Select(&p, "select * from Poster where StartDate > ? and"+
		" StartDate < ? and Deleted = 0 and Published = 1 order by StartDate",
		startMonth, endMonth)
	return p, err
}
예제 #5
0
파일: elastic.go 프로젝트: nicollet/bosun
func ESMonthly(e *State, T miniprofiler.Timer, timeField, indexRoot, layout string) (*Results, error) {
	var r Results
	indexer := ESIndexer{}
	indexer.TimeField = timeField
	indexer.Generate = func(start, end *time.Time) []string {
		var indices []string
		truncStart := now.New(*start).BeginningOfMonth()
		truncEnd := now.New(*end).BeginningOfMonth()
		for d := truncStart; !d.After(truncEnd); d = d.AddDate(0, 1, 0) {
			indices = append(indices, fmt.Sprintf("%v%v", indexRoot, d.Format(layout)))
		}
		return indices
	}
	r.Results = append(r.Results, &Result{Value: indexer})
	return &r, nil
}
예제 #6
0
func getPull(t time.Time) int {
	first_day := now.New(t).BeginningOfMonth()
	wday := int(first_day.Weekday())
	if wday == 0 {
		wday = 7
	}
	return wday - 1
}
예제 #7
0
// Given a task's date and scope, return a range of dates that will get all tasks within the scope
func _between(start time.Time, scope int) (time.Time, time.Time) {
	switch scope {
	case ScopeDay:
		from := now.New(start).BeginningOfDay()
		return from, from.AddDate(0, 0, 1)
	case ScopeMonth:
		from := now.New(start).BeginningOfMonth()
		return from, from.AddDate(0, 1, 0)
	case ScopeYear:
		from := now.New(start).BeginningOfYear()
		return from, from.AddDate(1, 0, 0)
	case ScopeBucket:
	}
	if scope > ScopeYear {
		return time.Date(1960, 1, 1, 0, 0, 0, 0, time.Local), time.Now()
	}
	return time.Now(), time.Now()
}
예제 #8
0
func Month(e *State, T miniprofiler.Timer, offset float64, startEnd string) (*Results, error) {
	if startEnd != "start" && startEnd != "end" {
		return nil, fmt.Errorf("last parameter for mtod must be 'start' or 'end'")
	}
	offsetInt := int(offset)
	location := time.FixedZone(fmt.Sprintf("%v", offsetInt), offsetInt*60*60)
	timeZoned := e.now.In(location)
	var mtod float64
	if startEnd == "start" {
		mtod = float64(now.New(timeZoned).BeginningOfMonth().Unix())
	} else {
		mtod = float64(now.New(timeZoned).EndOfMonth().Unix())
	}
	return &Results{
		Results: []*Result{
			{Value: Scalar(float64(mtod))},
		},
	}, nil
}
예제 #9
0
파일: db.go 프로젝트: sisteamnik/guseful
func normTime(a int64) int64 {
	if a < 1440 {
		return a
	}
	t := unixtime.Parse(a).In(time.Now().Location())
	t = t.In(time.Now().Location())
	dur := t.Sub(now.New(t).BeginningOfDay())
	//fmt.Println(t.Format("02.01.2006 15:04"),
	//	now.New(t).BeginningOfDay().Format("02.01.2006 15:04"))
	return int64(dur.Minutes())
}
예제 #10
0
func (r *RateLimiter) Try(remoteAddr, limitType string, maxCount,
	minInterval int64) bool {
	var rls []RateLimit
	tx, err := r.db.Begin()
	if err != nil {
		tx.Rollback()
		return false
	}
	tx.Exec("delete from RateLimit where Created < ?", time.Now().UTC().
		Truncate(15*time.Minute))
	_, err = tx.Select(&rls, "select * from RateLimit where RemoteAddr = ? and"+
		" limitType  = ?", remoteAddr, limitType)
	if err != nil {
		tx.Rollback()
		return false
	}
	if len(rls) == 1 {
		if rls[0].Updated < now.New(time.Now()).BeginningOfDay().UnixNano() {
			rls[0].Count = 1
			upd(tx, rls[0])
			tx.Commit()
			return true
		}
		if rls[0].Count >= maxCount {
			upd(tx, rls[0])
			tx.Commit()
			return false
		}
		if (time.Now().UnixNano() - rls[0].Updated) < minInterval {
			upd(tx, rls[0])
			tx.Commit()
			return false
		}
	} else {
		rlim := RateLimit{}
		rlim.Created = time.Now().UnixNano()
		rlim.RemoteAddr = remoteAddr
		rlim.LimitType = limitType
		err = tx.Insert(&rlim)
		if err != nil {
			tx.Rollback()
			return false
		}
		rls = []RateLimit{rlim}
	}
	if len(rls) == 1 {
		setTry(tx, rls[0])
	}
	tx.Commit()
	return true
}
예제 #11
0
func (a *Adaptor) SetUserPackage(userID int, packageID int) *adaptor.AdaptorError {
	var delSuccess int
	var userPackage string
	packageIDString := strconv.Itoa(packageID)

	pkg, adaptorErr := a.GetPackage(packageID)
	if adaptorErr != nil {
		return adaptorErr
	}

	// delete the user's old package
	err := a.apidClient.DoFunction("delete", url.Values{
		"tableName": []string{"user_package"},
		"where":     []string{`{"user_id" : "` + strconv.Itoa(userID) + `"}`},
	}, &delSuccess)

	if err != nil {
		ln.Err("Something went wrong trying to delete the user's current package", ln.Map{"error": err.Error(), "user_id": userID})
		return adaptor.NewError("Something went wrong trying to delete the user's current package")
	}

	params := url.Values{
		"user_id":          []string{strconv.Itoa(userID)},
		"status":           []string{strconv.Itoa(UserStatusSendGridPaid)},
		"package_id":       []string{packageIDString},
		"package_group_id": []string{strconv.Itoa(pkg.GroupID)},
		"package_status":   []string{strconv.Itoa(PackageStatusActive)},
		"start_date":       []string{time.Now().Format("2006-01-02")},
		"end_date":         []string{now.New(time.Now().AddDate(0, 1, 0)).BeginningOfMonth().Format("2006-01-02")},
		"subusers_limit":   []string{strconv.Itoa(DefaultSubuserLimit)},
		"updated_at":       []string{time.Now().String()},
	}

	columns := NewCrudColumns()
	columns.AddColumns(params)

	// add new user package
	err = a.apidClient.DoFunction("add", url.Values{
		"tableName": []string{"user_package"},
		"values":    []string{columns.String()},
	}, &userPackage)

	if err != nil {
		ln.Err("Something went wrong trying to add a package for the user", ln.Map{"error": err.Error(), "user_id": userID, "package_id": packageID})
		return adaptor.NewError("Something went wrong trying to add the user's package")

	}

	return nil
}
예제 #12
0
func (a *Adaptor) ActivateUserPackage(userID int) *adaptor.AdaptorError {
	dateStart := time.Now().Format("2006-01-02")
	dateEnd := now.New(time.Now().AddDate(0, 1, 0)).BeginningOfMonth().Format("2006-01-02")
	var result string
	err := a.apidClient.DoFunction("update", url.Values{
		"tableName": []string{"user_package"},
		"where":     []string{fmt.Sprintf(`{"user_id":"%d"}`, userID)},
		"values":    []string{fmt.Sprintf(`[{"package_status":1}, {"start_date":"%s"}, {"end_date": "%s"}]`, dateStart, dateEnd)},
	}, &result)
	if err != nil {
		ln.Err("Error activating user package", ln.Map{"error": err.Error(), "user_id": userID})
		return adaptor.NewError(err.Error())
	}
	return nil
}
// generateMonthsList returns a list of months (end of month), length per arg
// Receiver: None
// Params: numberOfMonths -- integer
// Returns: timeList ([]time.Time)
func generateMonthsList(numberOfMonths int) timeList {
	goMoment.FirstDayMonday = true

	// Do everything in UTC, otherwise you get messed up EndOfMonth's on days
	// where daylight savings time switches
	endofThisMonth := goMoment.New(time.Now().UTC()).EndOfMonth()

	monthsList := make(timeList, numberOfMonths)
	onMonth := endofThisMonth
	monthsList[0] = onMonth
	for i := 1; i < numberOfMonths; i++ {
		onMonth = moveDateToEndOfMonth(onMonth.AddDate(0, 0, 1))
		monthsList[i] = onMonth
	}

	return monthsList
}
예제 #14
0
파일: signup.go 프로젝트: john-cai/tools
func (a *Adaptor) AddUserPackage(data client.Signup) []error {

	params := url.Values{
		"user_id":          []string{strconv.Itoa(data.UserID)},
		"status":           []string{strconv.Itoa(UserStatusSendGridFree)},
		"package_id":       []string{strconv.Itoa(data.FreePackage.ID)},
		"package_group_id": []string{strconv.Itoa(data.FreePackage.PackageGroupID)},
		"package_status":   []string{strconv.Itoa(PackageStatusActive)},
		"start_date":       []string{time.Now().Format("2006-01-02")},
		"end_date":         []string{now.New(time.Now().AddDate(0, 1, 0)).BeginningOfMonth().Format("2006-01-02")},
		"subusers_limit":   []string{"0"},
		"updated_at":       []string{time.Now().String()},
	}

	if data.ResellerID != 0 {
		params.Set("status", strconv.Itoa(data.UserPackageStatus))
		params.Del("package_id")
		params.Del("package_group_id")
		params.Del("package_status")
	}

	columns := NewCrudColumns()
	columns.AddColumns(params)

	var success string
	err := a.apidClient.DoFunction("add", url.Values{
		"tableName": []string{"user_package"},
		"values":    []string{columns.String()},
	}, &success)

	if err != nil {
		return []error{err}
	}

	if success != ApidSuccess {
		return []error{errors.New("add user package unsuccessful")}
	}

	return make([]error, 0)
}
예제 #15
0
func addWeeklyAllowance(kidID int, allowance float64) error {
	tx, err := db.Begin()
	if err != nil {
		return err
	}
	defer tx.Rollback()
	// in transaction:
	// Add the money
	log.Printf("Adding allowance %v for kid %v", allowance, kidID)
	_, err = AddMoney(0, kidID, allowance, "Allowance", nil, tx)
	if err != nil {
		return err
	}
	nextAllowance := now.New(time.Now().AddDate(0, 0, 1)).Sunday()
	log.Printf("Setting next allowance to %v", nextAllowance)
	_, err = tx.Exec("UPDATE kids SET nextallowance=? WHERE kidid=?", nextAllowance, kidID)
	if err != nil {
		return err
	}
	tx.Commit()
	return nil
}
예제 #16
0
func (i Interval) nextTime(t time.Time, n int, units string) (time.Time, error) {
	switch units {
	case "minutes":
		return now.New(t.Add(time.Minute * time.Duration(n))).BeginningOfMinute(), nil
	case "hours":
		return now.New(t.Add(time.Hour * time.Duration(n))).BeginningOfHour(), nil
	case "days":
		return now.New(t.AddDate(0, 0, n)).BeginningOfDay(), nil
	case "weeks":
		return now.New(t.AddDate(0, 0, 7*n)).BeginningOfDay(), nil
	case "months":
		return now.New(t.AddDate(0, n, 0)).BeginningOfDay(), nil
	case "years":
		return now.New(t.AddDate(n, 0, 0)).BeginningOfDay(), nil
	}
	return time.Time{}, InvalidIntervalError
}
// moveDateToEndOfMonth moves any date to the end of its respective month
// Receiver: None
// Params: date time.Time -- original date
// Returns: time.Time -- end of the month
func moveDateToEndOfMonth(date time.Time) time.Time {
	return goMoment.New(date).EndOfMonth()
}
예제 #18
0
파일: peer.go 프로젝트: vassilux/revor
func GetPeerWeekCallStatsByDayAndPeer(day string, peer string, inout string, mongoDb *mgo.Database) []models.HourByDaysRecord {
	var collectiionName string
	finalResults := make([]models.HourByDaysRecord, 24)
	if inout == "in" {
		collectiionName = "dailypeer_incomming"
	} else if inout == "out" {
		collectiionName = "dailypeer_outgoing"
	} else {
		return finalResults
	}

	incomming := mongoDb.C(collectiionName)
	results := []models.DayOfWeekCalls{}
	requestedDate, err := time.Parse(time.RFC3339, day)
	if err != nil {
		panic(err)
	}
	mondayDate := now.New(requestedDate).Monday()
	sundayDate := now.New(requestedDate).EndOfSunday()
	var myMatch bson.M

	if len(peer) > 0 {
		myMatch = bson.M{
			"$match": bson.M{
				"metadata.dt":          bson.M{"$gte": mondayDate, "$lte": sundayDate},
				"metadata.dst":         bson.RegEx{peer, "i"},
				"metadata.disposition": 16,
			},
		}
	} else {
		myMatch = bson.M{
			"$match": bson.M{
				"metadata.dt":          bson.M{"$gte": mondayDate, "$lte": sundayDate},
				"metadata.disposition": 16,
			},
		}
	}

	//
	myProject := bson.M{
		"$project": bson.M{
			"day":              bson.M{"$dayOfWeek": "$metadata.dt"},
			"date":             "$metadata.dt",
			"disposition":      "$metadata.disposition",
			"calls":            "$calls",
			"duration":         "$duration",
			"answer_wait_time": "$answer_wait_time",
			"calls_per_hours":  "$calls_per_hours",
		},
	}

	myGroup := bson.M{
		"$group": bson.M{
			"_id":              bson.M{"day": "$day", "disposition": "$disposition", "date": "$date"},
			"calls":            bson.M{"$sum": "$calls"},
			"durations":        bson.M{"$sum": "$duration"},
			"answer_wait_time": bson.M{"$sum": "$answer_wait_time"},
			"callsPerHours":    bson.M{"$addToSet": bson.M{"hourlyCalls": "$calls_per_hours"}},
		},
	}

	mySort := bson.M{
		"$sort": bson.M{
			"_id": 1,
		},
	}

	myProjectFinal := bson.M{
		"$project": bson.M{
			"_id":            0,
			"dayOfWeek":      "$_id.day",
			"disposition":    "$_id.disposition",
			"calls":          "$calls",
			"duration":       "$durations",
			"answerWaitTime": "$answer_wait_time",
			"date":           "$_id.date",
			"callsPerHours":  "$callsPerHours",
		},
	}
	//
	operations := []bson.M{myMatch, myProject, myGroup, mySort, myProjectFinal}
	pipe := incomming.Pipe(operations)
	err = pipe.All(&results)
	if err != nil {
		panic(err)
	}
	//

	for i := 0; i < 24; i++ {
		finalResults[i].Hour = fmt.Sprintf("%02d:00", i)
	}
	//
	for j := 0; j < len(results); j++ {
		//
		results[j].MakeSummaryCallsPerHours()
		results[j].PopulateHoursByDays(finalResults)
	}
	return finalResults
}
예제 #19
0
func (p Posters) IsSunday(t time.Time, i int) bool {
	t = time.Date(t.Year(), t.Month(), i, t.Hour(), t.Minute(), 0, 0, t.Location())
	n := now.New(t)
	return n.EndOfWeek().Add(time.Hour*24).Day() == i
}