Пример #1
0
func (ctx *Context) GetSeenNotificationList() []Notification {
	unseenLen, err := ctx.DbMap.SelectInt("select count(ID) from notifications where userid=? and seen=0", helpers.GetIDEncoded(ctx.User.ID))
	helpers.CheckErr(err, "Failed to count seen notifications")

	if unseenLen >= 5 {
		return []Notification{}
	}

	var seen []Notification
	_, err = ctx.DbMap.Select(&seen, "select * from notifications where userid=? and seen=1", helpers.GetIDEncoded(ctx.User.ID))
	helpers.CheckErr(err, "Failed to get seen notifications")

	length := 5 - int(unseenLen)

	if len(seen) < length {
		length = len(seen)
	}

	notes := make([]Notification, length)
	for i := 0; i < length; i++ {
		index := len(seen) - i - 1
		notes[i] = seen[index]
	}
	return notes
}
Пример #2
0
func (ctx *Context) GetTenants(params ...int64) interface{} {
	var tenants []User

	if len(params) > 0 {
		_, err := ctx.DbMap.Select(&tenants, "select * from users where class=? and employer=? ORDER BY LastName", helpers.GetIDEncoded(params[0]), TE)
		helpers.CheckErr(err, "Failed to query tenants from the user table")
	} else {
		_, err := ctx.DbMap.Select(&tenants, "select * from users where class=? ORDER BY LastName", TE)
		helpers.CheckErr(err, "Failed to query tenants from the user table")
	}
	return tenants
}
Пример #3
0
func (ctx *Context) GetAuxEngineers(params ...int64) interface{} {
	var auxEngineers []User

	if len(params) > 0 {
		_, err := ctx.DbMap.Select(&auxEngineers, "select * from users where class=? and employer=? ORDER BY LastName", helpers.GetIDEncoded(params[0]), AE)
		helpers.CheckErr(err, "Failed to query auxiliary engineers from the user table")
	} else {
		_, err := ctx.DbMap.Select(&auxEngineers, "select * from users where class=? ORDER BY LastName", AE)
		helpers.CheckErr(err, "Failed to query auxilary engineers from the user table")
	}
	return auxEngineers
}
Пример #4
0
func (ctx *Context) GetProjectManagers(params ...int64) interface{} {
	var managers []User

	if len(params) > 0 {
		_, err := ctx.DbMap.Select(&managers, "select * from users where class=? and employer=? ORDER BY LastName", helpers.GetIDEncoded(params[0]), PM)
		helpers.CheckErr(err, "Failed to query project managers from the user table")
	} else {
		_, err := ctx.DbMap.Select(&managers, "select * from users where class=? ORDER BY lastname", PM)
		helpers.CheckErr(err, "Failed to query project managers from the user table")
	}
	return managers
}
Пример #5
0
func Initialize(dbhost string, dbport string, dbname string, dbuser string, dbpass string, dbprotocol string) {
	var err error

	var dialect gorp.Dialect
	var db *sql.DB
	switch dbprotocol {
	case "mysql":
		db, err = sql.Open(dbprotocol, dbuser+":"+dbpass+"@("+dbhost+":"+dbport+")/"+dbname)
		dialect = gorp.MySQLDialect{"InnoDB", "UTF8"}
	case "mssql":
		db, err = sql.Open(dbprotocol, "server="+dbhost+";user id="+dbuser+";password="******";database="+dbname+";")
		dialect = gorp.SqlServerDialect{}
	default:
		log.Fatal("Invalid gorp dialect")
	}

	helpers.CheckErr(err, "sql.open failed")
	if err != nil {
		fmt.Println("sql.Open failed: ", err)
	}

	dbmap = &gorp.DbMap{Db: db, Dialect: dialect}

	err = dbmap.TruncateTables()
	if err != nil {
		fmt.Println("Failed to truncate tables in fempdb: ", err)
	}

	dbmap.AddTableWithName(models.Facility{}, "cases").SetKeys(true, "ID")

	dbmap.AddTableWithName(models.Report{}, "reports").SetKeys(true, "ID")
	dbmap.AddTableWithName(models.Note{}, "notes").SetKeys(true, "ID")

	dbmap.AddTableWithName(models.ServerVirtualization{}, "servers").SetKeys(true, "ID")
	dbmap.AddTableWithName(models.PowerCogeneration{}, "cogen").SetKeys(true, "ID")
	dbmap.AddTableWithName(models.DesktopEfficiencySettings{}, "desktop").SetKeys(true, "ID")
	dbmap.AddTableWithName(models.CommunicationClosets{}, "closets").SetKeys(true, "ID")
	dbmap.AddTableWithName(models.Telework{}, "telework").SetKeys(true, "ID")
	dbmap.AddTableWithName(models.PrinterConsolidation{}, "printer").SetKeys(true, "ID")
	dbmap.AddTableWithName(models.LightingUpgrade{}, "lighting").SetKeys(true, "ID")
	dbmap.AddTableWithName(models.FanCoilControl{}, "fancoil").SetKeys(true, "ID")
	dbmap.AddTableWithName(models.HotWaterRecirculationPump{}, "hotpump").SetKeys(true, "ID")
	dbmap.AddTableWithName(models.SolarPV{}, "solar").SetKeys(true, "ID")
	dbmap.AddTableWithName(models.GeneratorTestEnergyRecovery{}, "generator").SetKeys(true, "ID")

	dbmap.AddTableWithName(models.User{}, "users").SetKeys(true, "ID")
	dbmap.AddTableWithName(models.Notification{}, "notifications").SetKeys(true, "ID")

	err = dbmap.CreateTablesIfNotExists()
	helpers.CheckErr(err, "Call to gorp to create tables failed: ")
}
Пример #6
0
func HotListHandler(w http.ResponseWriter, r *http.Request, ctx *models.Context) error {
	//if r.URL.Query().Get("type") == "json" {
	fmt.Println("Serving JSON for Hot List")
	var facilities []models.Facility
	_, err := ctx.DbMap.Select(&facilities, "select * from cases where CurrentEnergyPerYear > 1000000 AND CurrentEnergyPerYear IS NOT NULL")
	helpers.CheckErr(err, "Failed to query facilities for hot list.")

	fmt.Println("Request to serve JSON received from AJAX...serving map.")
	rows := make([][]string, len(facilities))
	for i, facility := range facilities {
		rows[i] = []string{
			strconv.Itoa(i + 1),
			strconv.FormatInt(facility.ID, 10),
			facility.Name,
			helpers.RenderNullEnergyReport(facility.CurrentEnergyPerYear),
			helpers.RenderNullFloatCurrency(facility.CurrentEnergyCostPerYear),
			ctx.LookupUser(facility.TenantID).LastName + ", " + ctx.LookupUser(facility.TenantID).FirstName,
			ctx.LookupUser(facility.ProjectManagerID).LastName, ", " + ctx.LookupUser(facility.ProjectManagerID).FirstName,
		}
	}
	js, err := json.Marshal(map[string]interface{}{"data": rows})
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return err
	}

	w.Header().Set("Content-Type", "application/json")
	w.Write(js)
	//	return err
	//}
	return err
}
Пример #7
0
func ResetFormHandler(w http.ResponseWriter, r *http.Request, ctx *models.Context) error {
	id, err := ObjectIdFromString(r.URL.Query().Get(":id"))

	if err != nil {
		fmt.Println(err)
		return nil
	}

	var reset models.Reset
	err = ctx.DbMap.SelectOne(&reset, "select * from resets where ID=?", helpers.GetIDEncoded(id))
	helpers.CheckErr(err, "Failed to query resets for form handler.")

	if reset.CreatedAt.Before(time.Now().AddDate(0, 0, -1)) {
		nav := LoginFormHandler(w, r, ctx)
		return nav
	}

	tmpl := template.Must(template.ParseFiles(
		"views/_pbase.html",
		"views/reset.html",
	))

	if err := tmpl.Execute(w, map[string]interface{}{
		"reset": reset,
		"ctx":   ctx,
	}); err != nil {
		log.Println(err.Error())
		return nil
	}
	return nil
}
Пример #8
0
func (ctx *Context) GetEmployees() []User {
	var users []User
	var err error

	_, err = ctx.DbMap.Select(&users, "select * from users where Employer=?", ctx.User.Employer)
	helpers.CheckErr(err, "Failed to query users for employee handler")

	return users
}
Пример #9
0
func (ctx *Context) LookupUser(id int64) User {
	if id == 0 {
		return User{Username: ""}
	}
	var user User
	err := ctx.DbMap.SelectOne(&user, "select * from users where BINARY ID=?", helpers.GetIDEncoded(id))
	helpers.CheckErr(err, "Failed to lookup user from the user table")

	return user
}
Пример #10
0
// POST handler
func ResetPasswordHandler(w http.ResponseWriter, r *http.Request, ctx *models.Context) (err error) {
	email := r.FormValue("Email")

	var user models.User
	err = ctx.DbMap.SelectOne(&user, "select * from users where Email=?", email)
	helpers.CheckErr(err, "Failed to query emails for password reset handler.")
	if err == nil {
		reset := models.Reset{User: user.ID, CreatedAt: time.Now()}
		err = ctx.DbMap.Insert(&reset)
		helpers.CheckErr(err, "Failed to insert new password reset object.")
		if err != nil {
			ctx.Session.AddFlash("Problem resetting password.", "danger")
			return ResetPassword(w, r, ctx)
		}
		/*if helpers.SendPasswordResetEmail(user.Email, user.Username, "http://emap.aplinapps.com/reset/"+GetIDEncoded(reset.ID)) != nil {
			ctx.Session.AddFlash("Problem sending password reset email.", "danger")
			return ResetPassword(w, r, ctx)
		}*/
		return nil
	}

	ctx.Session.AddFlash("Password reset email sent.", "info")
	return ResetPassword(w, r, ctx)
}
Пример #11
0
func (ctx *Context) GetUnseenNotifications() []Notification {
	var unseen []Notification
	_, err := ctx.DbMap.Select(&unseen, "select * from notifications where userid=? and seen=0", helpers.GetIDEncoded(ctx.User.ID))
	helpers.CheckErr(err, "Failed to get unseen notifications")
	NoteLength := len(unseen)
	length := 5

	if NoteLength < 5 {
		length = NoteLength
	}
	notes := make([]Notification, length)

	for i := 0; i < length; i++ {
		index := NoteLength - i - 1
		notes[i] = unseen[index]
	}
	return notes
}
Пример #12
0
func (ctx *Context) GetNotificationCount() int {
	count, err := ctx.DbMap.SelectInt("select count(ID) from notifications where BINARY userid=? and seen=0", helpers.GetIDEncoded(ctx.User.ID))
	helpers.CheckErr(err, "Failed to count notificatons")

	return int(count)
}
Пример #13
0
func SelectNewUserHandler(w http.ResponseWriter, r *http.Request, ctx *models.Context) error {
	un := r.FormValue("Username")
	err := models.RegisterHelper(ctx, un)

	if err != nil {
		switch err.Error() {

		case "User already exists.":
			nav := LoginFormHandler(w, r, ctx)

			if nav != nil {
				log.Println(nav)
			}
			return nav
		case "User does not exist.":
			first, last, email := strings.ToLower(r.FormValue("FirstName")), strings.ToLower(r.FormValue("LastName")), r.FormValue("Email")
			pw, confirm, classStr, un := r.FormValue("Password"), r.FormValue("ConfirmPassword"), r.FormValue("Class"), r.FormValue("Username")
			class, err := strconv.Atoi(classStr)

			log.Println(err)

			if err != nil || !(class >= 1 && class <= 6) {
				ctx.Session.AddFlash("Must select a user class.", "danger")
				nav := RegisterFormHandler(w, r, ctx)

				if nav != nil {
					log.Println(nav)
				}
				return nav
			}

			if len(email) < 5 {
				ctx.Session.AddFlash("Email must be at least 5 characters long.", "danger")
				nav := RegisterFormHandler(w, r, ctx)

				if nav != nil {
					log.Println(nav)
				}
				return nav
			}

			if len(pw) < 8 {
				ctx.Session.AddFlash("Password must be at least 8 characters long.", "danger")
				nav := RegisterFormHandler(w, r, ctx)

				if nav != nil {
					log.Println(nav)
				}
				return nav
			}

			if pw != confirm {
				ctx.Session.AddFlash("Passwords do not match.", "danger")
				nav := RegisterFormHandler(w, r, ctx)

				if nav != nil {
					log.Println(nav)
				}
				return nav
			}
			u := &models.User{
				FirstName: first,
				LastName:  last,
				Username:  un,
				Email:     email,
				Class:     class,
			}
			u.SetPassword(pw)

			err = ctx.DbMap.Insert(u)
			helpers.CheckErr(err, "Failed to insert new user.")
			if err != nil {
				ctx.Session.AddFlash("Problem registering user.", "danger")
				nav := LoginFormHandler(w, r, ctx)

				if nav != nil {
					log.Println(nav)
				}
				return nav
			}
			ctx.Session.Values["user"] = u.ID
			http.Redirect(w, r, "/", http.StatusSeeOther)
			return nil
		case "Query failed.":
			log.Println(err)
			return err
		default:
			http.Error(w, err.Error(), http.StatusInternalServerError)
		}
		return nil
	}
	return nil
}