Example #1
0
func (this *BlankController) GetBlankByRegId() {
	if !sessions.CheckSession(this.Response, this.Request) {
		http.Redirect(this.Response, this.Request, "/", http.StatusUnauthorized)
		return
	}

	request, err := utils.ParseJS(this.Request, this.Response)
	if err != nil {
		utils.SendJSReply(map[string]interface{}{"result": err.Error()}, this.Response)
		return
	}

	regId, err := strconv.Atoi(request["reg_id"].(string))
	if err != nil {
		utils.SendJSReply(map[string]interface{}{"result": err.Error()}, this.Response)
		return
	}

	blank := new(models.BlankManager).NewPersonalBlank(true).SetRegId(regId)
	result := blank.GetBlank()

	if len(result) == 0 {
		result = blank.SetPersonal(false).GetBlank()
	}

	utils.SendJSReply(
		map[string]interface{}{
			"result": "ok",
			"data":   result,
			"role":   this.isAdmin()},
		this.Response)
}
Example #2
0
func (this *BlankController) GetHistoryRequest() {
	userId, err := this.CheckSid()
	if err != nil {
		utils.SendJSReply(map[string]interface{}{"result": "Unauthorized"}, this.Response)
		return
	}

	data, err := utils.ParseJS(this.Request, this.Response)
	if err != nil {
		utils.SendJSReply(map[string]interface{}{"result": err.Error()}, this.Response)
		return
	}

	eventId, err := strconv.Atoi(data["event_id"].(string))
	if err != nil {
		utils.SendJSReply(map[string]interface{}{"result": err.Error()}, this.Response)
		return
	}

	query := `SELECT params.id as param_id, params.name as param_name,
            param_types.name as type, param_values.value, forms.id as form_id
        FROM events
        INNER JOIN events_forms ON events_forms.event_id = events.id
        INNER JOIN forms ON events_forms.form_id = forms.id
        INNER JOIN registrations ON events.id = registrations.event_id
        INNER JOIN faces ON faces.id = registrations.face_id
        INNER JOIN users ON users.id = faces.user_id
        INNER JOIN params ON params.form_id = forms.id
        INNER JOIN param_types ON param_types.id = params.param_type_id
        INNER JOIN param_values ON param_values.param_id = params.id
            AND param_values.reg_id = registrations.id
        WHERE users.id = $1 AND events.id = $2 AND forms.personal = true;`

	utils.SendJSReply(map[string]interface{}{"result": "ok", "data": db.Query(query, []interface{}{userId, eventId})}, this.Response)
}
Example #3
0
//-----------------------------------------------------------------------------
func (this *GridController) GetEventTypesByEventId() {
	if !sessions.CheckSession(this.Response, this.Request) {
		http.Redirect(this.Response, this.Request, "/", http.StatusUnauthorized)

		return
	}

	if !this.isAdmin() {
		http.Redirect(this.Response, this.Request, "/", http.StatusForbidden)

		return
	}

	request, err := utils.ParseJS(this.Request, this.Response)
	if err != nil {
		utils.SendJSReply(map[string]interface{}{"result": err.Error()}, this.Response)

		return
	}

	eventId, err := strconv.Atoi(request["event_id"].(string))
	if err != nil {
		utils.SendJSReply(map[string]interface{}{"result": err.Error()}, this.Response)

		return
	}

	query := `SELECT event_types.id, event_types.name FROM events_types
        INNER JOIN events ON events.id = events_types.event_id
        INNER JOIN event_types ON event_types.id = events_types.type_id
        WHERE events.id = $1 ORDER BY event_types.id;`
	result := db.Query(query, []interface{}{eventId})

	utils.SendJSReply(map[string]interface{}{"result": "ok", "data": result}, this.Response)
}
func (this *RegistrationController) Logout() {
	userId, err := this.CheckSid()
	if err != nil {
		http.Redirect(this.Response, this.Request, "/", http.StatusUnauthorized)
		utils.SendJSReply(map[string]string{"result": "badSid"}, this.Response)

		return
	}

	var enabled bool
	if err = this.GetModel("users").
		LoadWherePart(map[string]interface{}{"id": userId}).
		SelectRow([]string{"enabled"}).
		Scan(&enabled); utils.HandleErr("[RegistrationController::Logout]: ", err, this.Response) {
		utils.SendJSReply(map[string]string{"result": err.Error()}, this.Response)

		return
	}

	params := map[string]interface{}{"enabled": enabled, "sid": " "}
	where := map[string]interface{}{"id": userId}
	this.GetModel("users").Update(this.isAdmin(), userId, params, where)
	sessions.ClearSession(this.Response)
	utils.SendJSReply(map[string]string{"result": "ok"}, this.Response)
}
Example #5
0
func (this *BlankController) GetListHistoryEvents() {
	userId, err := this.CheckSid()
	if err != nil {
		utils.SendJSReply(map[string]interface{}{"result": "Unauthorized"}, this.Response)

		return
	}

	data, err := utils.ParseJS(this.Request, this.Response)
	if err != nil {
		utils.SendJSReply(map[string]interface{}{"result": err.Error()}, this.Response)

		return
	}

	ids := map[string]interface{}{"form_id": make([]interface{}, 0)}
	if data["form_ids"] == nil || len(data["form_ids"].([]interface{})) == 0 {
		utils.SendJSReply(map[string]interface{}{"result": "Нет данных о формах анкеты"}, this.Response)

		return
	}

	for _, v := range data["form_ids"].([]interface{}) {
		ids["form_id"] = append(ids["form_id"].([]interface{}), int(v.(float64)))
	}

	eventsForms := this.GetModel("events_forms")
	events := eventsForms.
		LoadWherePart(ids).
		SetCondition(models.OR).
		Select_([]string{"event_id"})

	if len(events) == 0 {
		utils.SendJSReply(map[string]interface{}{"result": "Нет данных"}, this.Response)

		return
	}

	query := `SELECT DISTINCT events.id, events.name FROM events
        INNER JOIN events_forms ON events_forms.event_id = events.id
        INNER JOIN forms ON events_forms.form_id = forms.id
        INNER JOIN registrations ON registrations.event_id = events.id
        INNER JOIN faces ON faces.id = registrations.face_id
        INNER JOIN users ON users.id = faces.user_id
        WHERE users.id=$1 AND events.id IN (`

	var i int
	params := []interface{}{userId}

	for i = 2; i < len(events); i++ {
		query += "$" + strconv.Itoa(i) + ", "
		params = append(params, int(events[i-2].(map[string]interface{})["event_id"].(int)))
	}

	query += "$" + strconv.Itoa(i) + ")"
	params = append(params, int(events[i-2].(map[string]interface{})["event_id"].(int)))

	utils.SendJSReply(map[string]interface{}{"result": "ok", "data": db.Query(query, params)}, this.Response)
}
Example #6
0
//-----------------------------------------------------------------------------
func (this *BlankController) EditParams() {
	userId, err := this.CheckSid()
	if err != nil {
		http.Redirect(this.Response, this.Request, "/", http.StatusUnauthorized)
		return
	}

	request, err := utils.ParseJS(this.Request, this.Response)
	if err != nil {
		utils.SendJSReply(map[string]interface{}{"result": err.Error()}, this.Response)
		return
	}

	date := time.Now().Format("2006-01-02T15:04:05Z00:00")

	for _, v := range request["data"].([]interface{}) {
		paramValId, err := strconv.Atoi(v.(map[string]interface{})["param_val_id"].(string))
		if err != nil {
			utils.SendJSReply(map[string]interface{}{"result": err.Error()}, this.Response)
			return
		}

		query := `SELECT params.name, params.required, params.editable
            FROM params
            INNER JOIN param_values ON param_values.param_id = params.id
            WHERE param_values.id = $1;`
		result := db.Query(query, []interface{}{paramValId})

		name := result[0].(map[string]interface{})["name"].(string)
		required := result[0].(map[string]interface{})["required"].(bool)
		editable := result[0].(map[string]interface{})["editable"].(bool)
		value := v.(map[string]interface{})["value"].(string)

		if required && utils.MatchRegexp("^[ \t\v\r\n\f]{0,}$", value) {
			utils.SendJSReply(map[string]interface{}{"result": "Заполните параметр '" + name + "'"}, this.Response)
			return
		}

		if !this.isAdmin() && !editable {
			continue
		}

		if value == "" {
			value = " "
		}

		params := map[string]interface{}{"value": value, "date": date, "user_id": userId}
		where := map[string]interface{}{"id": paramValId}
		this.GetModel("param_values").Update(this.isAdmin(), userId, params, where)
	}

	utils.SendJSReply(map[string]interface{}{"result": "Изменения сохранены"}, this.Response)
}
Example #7
0
func (this *UserController) SendEmailWellcomeToProfile() {
	if !this.isAdmin() {
		http.Redirect(this.Response, this.Request, "/", http.StatusForbidden)
		return
	}

	request, err := utils.ParseJS(this.Request, this.Response)
	if utils.HandleErr("[UserController::SendEmailWellcomeToProfile]: ", err, this.Response) {
		utils.SendJSReply(map[string]interface{}{"result": err.Error()}, this.Response)
		return
	}

	userId, err := strconv.Atoi(request["user_id"].(string))
	if err != nil {
		utils.SendJSReply(map[string]interface{}{"result": err.Error()}, this.Response)
		return
	}

	query := `SELECT param_values.value
        FROM param_values
        INNER JOIN registrations ON registrations.id = param_values.reg_id
        INNER JOIN params ON params.id = param_values.param_id
        INNER JOIN events ON events.id = registrations.event_id
        INNER JOIN faces ON faces.id = registrations.face_id
        INNER JOIN users ON users.id = faces.user_id
        WHERE params.id in (4, 5, 6, 7) AND users.id = $1 ORDER BY params.id;`
	data := db.Query(query, []interface{}{userId})

	if len(data) < 4 {
		utils.SendJSReply(map[string]interface{}{"result": "Нет регистрационных данных пользователя."}, this.Response)
		return
	}

	to := data[1].(map[string]interface{})["value"].(string) + " "
	to += data[2].(map[string]interface{})["value"].(string) + " "
	to += data[3].(map[string]interface{})["value"].(string)
	email := data[0].(map[string]interface{})["value"].(string)

	token := utils.GetRandSeq(HASH_SIZE)
	if !mailer.SendEmailWellcomeToProfile(to, email, token) {
		utils.SendJSReply(map[string]interface{}{"result": "Проверьте правильность email."}, this.Response)
		return
	}

	params := map[string]interface{}{"token": token, "enabled": true}
	where := map[string]interface{}{"id": userId}
	this.GetModel("users").Update(this.isAdmin(), userId, params, where)

	utils.SendJSReply(map[string]interface{}{"result": "Письмо отправлено"}, this.Response)
}
Example #8
0
//-----------------------------------------------------------------------------
func (this *BlankController) GetEditHistoryData() {
	data, err := utils.ParseJS(this.Request, this.Response)
	if err != nil {
		utils.SendJSReply(map[string]interface{}{"result": err.Error()}, this.Response)
		return
	}

	regId, err := strconv.Atoi(data["reg_id"].(string))
	if err != nil {
		utils.SendJSReply(map[string]interface{}{"result": err.Error()}, this.Response)
		return
	}

	formType := data["personal"].(string)
	if formType != "true" && formType != "false" {
		utils.SendJSReply(map[string]interface{}{"result": "Invalid form type"}, this.Response)
		return
	}

	query := `SELECT params.id as param_id, forms.id as form_id, p.date as edit_date,
        array_to_string(ARRAY(
            SELECT param_values.value
                FROM events
                INNER JOIN events_forms ON events_forms.event_id = events.id
                INNER JOIN forms ON events_forms.form_id = forms.id
                INNER JOIN registrations ON events.id = registrations.event_id
                INNER JOIN faces ON faces.id = registrations.face_id
                INNER JOIN users ON users.id = faces.user_id
                INNER JOIN params ON params.form_id = forms.id
                INNER JOIN param_types ON param_types.id = params.param_type_id
                INNER JOIN param_values ON param_values.param_id = params.id
                    AND registrations.id = param_values.reg_id
                WHERE (params.id in (5, 6, 7) AND events.id = 1) and users.id = p.user_id
        ), ' ') as login
        FROM events
        INNER JOIN events_forms ON events_forms.event_id = events.id
        INNER JOIN forms ON events_forms.form_id = forms.id
        INNER JOIN registrations ON events.id = registrations.event_id
        INNER JOIN faces ON faces.id = registrations.face_id
        INNER JOIN users ON users.id = faces.user_id
        INNER JOIN params ON params.form_id = forms.id
        INNER JOIN param_types ON param_types.id = params.param_type_id
        INNER JOIN param_values as p ON p.param_id = params.id
            AND p.reg_id = registrations.id
        WHERE registrations.id = $1 AND forms.personal = $2;`

	utils.SendJSReply(map[string]interface{}{"result": "ok", "data": db.Query(query, []interface{}{regId, formType})}, this.Response)
}
Example #9
0
func (this *Handler) GroupRegistrationsLoad() {
	userId, err := this.CheckSid()
	if err != nil {
		http.Error(this.Response, "Unauthorized", 400)
		return
	}

	limit, err := strconv.Atoi(this.Request.PostFormValue("rows"))
	if err != nil {
		http.Error(this.Response, err.Error(), 400)
		return
	}

	page, err := strconv.Atoi(this.Request.PostFormValue("page"))
	if err != nil {
		http.Error(this.Response, err.Error(), 400)
		return
	}

	sidx := this.Request.FormValue("sidx")
	start := limit*page - limit

	query := `SELECT group_registrations.id, group_registrations.event_id,
            group_registrations.group_id
        FROM group_registrations
        INNER JOIN events ON events.id = group_registrations.event_id
        INNER JOIN groups ON groups.id = group_registrations.group_id
        INNER JOIN persons ON persons.group_id = groups.id
        INNER JOIN faces ON faces.id = persons.face_id
        INNER JOIN users ON users.id = faces.user_id
        WHERE users.id = $1 AND events.team = $2 ORDER BY $3 LIMIT $4 OFFSET $5;`
	rows := db.Query(query, []interface{}{userId, true, sidx, limit, start})

	query = `SELECT COUNT(*) FROM (SELECT group_registrations.id
        FROM group_registrations
        INNER JOIN events ON events.id = group_registrations.event_id
        INNER JOIN groups ON groups.id = group_registrations.group_id
        INNER JOIN persons ON persons.group_id = groups.id
        INNER JOIN faces ON faces.id = persons.face_id
        INNER JOIN users ON users.id = faces.user_id
        WHERE users.id = $1 AND events.team = $2 GROUP BY group_registrations.id) as count;`

	var count int
	db.QueryRow(query, []interface{}{userId, true}).Scan(&count)

	var totalPages int
	if count > 0 {
		totalPages = int(math.Ceil(float64(count) / float64(limit)))
	} else {
		totalPages = 0
	}

	result := make(map[string]interface{}, 2)
	result["rows"] = rows
	result["page"] = page
	result["total"] = totalPages
	result["records"] = count

	utils.SendJSReply(result, this.Response)
}
Example #10
0
func (this *UserController) ResetPassword() {
	userId, err := this.CheckSid()
	if err != nil {
		http.Redirect(this.Response, this.Request, "/", http.StatusUnauthorized)
		return
	}

	request, err := utils.ParseJS(this.Request, this.Response)
	if err != nil {
		utils.SendJSReply(err.Error(), this.Response)
		return
	}

	pass := request["pass"].(string)
	if !utils.MatchRegexp("^.{6,36}$", pass) {
		utils.SendJSReply(map[string]interface{}{"result": "badPassword"}, this.Response)
		return
	}

	var id int
	if request["id"] == nil {
		id = userId

	} else {
		id, err = strconv.Atoi(request["id"].(string))
		if utils.HandleErr("[UserController::ResetPassword] strconv.Atoi: ", err, this.Response) {
			utils.SendJSReply(map[string]interface{}{"result": err.Error()}, this.Response)
			return
		}
	}

	var enabled bool
	salt := strconv.Itoa(int(time.Now().Unix()))
	where := map[string]interface{}{"id": id}

	user := this.GetModel("users")
	user.LoadWherePart(where).
		SelectRow([]string{"enabled"}).
		Scan(&enabled)

	params := map[string]interface{}{"enabled": enabled, "salt": salt, "pass": utils.GetMD5Hash(pass + salt)}
	user.Update(this.isAdmin(), id, params, where)

	utils.SendJSReply(map[string]interface{}{"result": "ok"}, this.Response)
}
Example #11
0
func (this *BlankController) GetGroupBlank() {
	request, err := utils.ParseJS(this.Request, this.Response)
	if err != nil {
		utils.SendJSReply(map[string]interface{}{"result": err.Error()}, this.Response)
		return
	}

	groupRegId, err := strconv.Atoi(request["group_reg_id"].(string))
	if err != nil {
		utils.SendJSReply(map[string]interface{}{"result": err.Error()}, this.Response)
		return
	}

	utils.SendJSReply(
		map[string]interface{}{
			"result": "ok",
			"data":   new(models.BlankManager).NewGroupBlank(false).SetGroupRegId(groupRegId).GetTeamBlank()},
		this.Response)
}
Example #12
0
func (this *GroupController) IsRegGroup() {
	_, err := this.CheckSid()
	if err != nil {
		http.Redirect(this.Response, this.Request, "/", http.StatusUnauthorized)
		return
	}

	request, err := utils.ParseJS(this.Request, this.Response)
	if err != nil {
		utils.SendJSReply(map[string]interface{}{"result": err.Error()}, this.Response)
	}

	groupId, err := strconv.Atoi(request["group_id"].(string))
	if err != nil {
		utils.SendJSReply(map[string]interface{}{"result": err.Error()}, this.Response)
	}

	addDelFlag := !db.IsExists("group_registrations", []string{"group_id"}, []interface{}{groupId})
	utils.SendJSReply(map[string]interface{}{"result": "ok", "addDelFlag": addDelFlag}, this.Response)
}
Example #13
0
func (this *RegistrationController) Login() {
	data, err := utils.ParseJS(this.Request, this.Response)
	if utils.HandleErr("[RegistrationController::Login]: ", err, this.Response) {
		utils.SendJSReply(map[string]interface{}{"result": err.Error()}, this.Response)

		return
	}

	login := data["login"].(string)
	pass := data["password"].(string)

	var id int
	var enabled bool
	var passHash, salt string
	result := make(map[string]interface{}, 1)

	if err = this.GetModel("users").
		LoadWherePart(map[string]interface{}{"login": login}).
		SelectRow([]string{"id", "pass", "salt", "enabled"}).
		Scan(&id, &passHash, &salt, &enabled); err != nil {
		result["result"] = "invalidCredentials"

	} else if enabled == false {
		result["result"] = "notEnabled"

	} else if passHash != utils.GetMD5Hash(pass+salt) {
		result["result"] = "badPassword"

	} else {
		result["result"] = "ok"

		sid := utils.GetRandSeq(HASH_SIZE)
		params := map[string]interface{}{"sid": sid, "enabled": true}
		where := map[string]interface{}{"id": id}
		this.GetModel("users").Update(this.isAdmin(), id, params, where)
		sessions.SetSession(this.Response, map[string]interface{}{"sid": sid})
	}

	utils.SendJSReply(result, this.Response)
}
Example #14
0
func (this *Handler) GroupsLoad() {
	userId, err := this.CheckSid()
	if err != nil {
		http.Error(this.Response, "Unauthorized", 400)
		return
	}

	limit, err := strconv.Atoi(this.Request.PostFormValue("rows"))
	if err != nil {
		http.Error(this.Response, err.Error(), 400)
		return
	}

	page, err := strconv.Atoi(this.Request.PostFormValue("page"))
	if err != nil {
		http.Error(this.Response, err.Error(), 400)
		return
	}

	sidx := this.Request.FormValue("sidx")
	start := limit*page - limit

	query := `SELECT groups.id, groups.name, groups.face_id
        FROM groups
        INNER JOIN persons ON persons.group_id = groups.id
        INNER JOIN faces ON faces.id = persons.face_id
        INNER JOIN users ON users.id = faces.user_id
        WHERE users.id = $1 ORDER BY $2 LIMIT $3 OFFSET $4;`
	rows := db.Query(query, []interface{}{userId, sidx, limit, start})

	query = `SELECT COUNT(*) FROM (SELECT groups.id FROM groups
        INNER JOIN persons ON persons.group_id = groups.id
        INNER JOIN faces ON faces.id = persons.face_id
        INNER JOIN users ON users.id = faces.user_id
        WHERE users.id = $1) as count;`
	count := int(db.Query(query, []interface{}{userId})[0].(map[string]interface{})["count"].(int))

	var totalPages int
	if count > 0 {
		totalPages = int(math.Ceil(float64(count) / float64(limit)))
	} else {
		totalPages = 0
	}

	result := make(map[string]interface{}, 2)
	result["rows"] = rows
	result["page"] = page
	result["total"] = totalPages
	result["records"] = count

	utils.SendJSReply(result, this.Response)
}
Example #15
0
func (this *UserController) CheckSession() {
	var userHash string
	var result interface{}

	sid := sessions.GetValue("sid", this.Request)
	if sid == nil {
		result = map[string]interface{}{"result": "no"}

	} else {
		err := this.GetModel("users").
			LoadWherePart(map[string]interface{}{"sid": sid}).
			SelectRow([]string{"sid"}).
			Scan(&userHash)
		if err != sql.ErrNoRows && sessions.CheckSession(this.Response, this.Request) {
			result = map[string]interface{}{"result": "ok"}
		} else {
			result = map[string]interface{}{"result": "no"}
		}
	}

	utils.SendJSReply(result, this.Response)
}
Example #16
0
func (this *BlankController) GetPersonBlankFromGroup() {
	userId, err := this.CheckSid()
	if err != nil {
		utils.SendJSReply(map[string]interface{}{"result": "Unauthorized"}, this.Response)
		return
	}

	request, err := utils.ParseJS(this.Request, this.Response)
	if err != nil {
		utils.SendJSReply(map[string]interface{}{"result": err.Error()}, this.Response)
		return
	}

	var personalForm bool
	switch request["personal"].(string) {
	case "true":
		personalForm = true
		break
	case "false":
		personalForm = false
		break
	default:
		panic("Invalid bool value")
	}

	faceId, err := strconv.Atoi(request["face_id"].(string))
	if err != nil {
		utils.SendJSReply(map[string]interface{}{"result": err.Error()}, this.Response)
		return
	}

	groupRegId, err := strconv.Atoi(request["group_reg_id"].(string))
	if err != nil {
		utils.SendJSReply(map[string]interface{}{"result": err.Error()}, this.Response)
		return
	}

	var regId int

	if faceId == -1 {
		if this.isAdmin() {
			db.QueryRow(db.QueryGetCaptFaceIdAndRegId, []interface{}{groupRegId}).Scan(&faceId, &regId)
		} else {
			if err := this.GetModel("faces").
				LoadWherePart(map[string]interface{}{"user_id": userId}).
				SelectRow([]string{"id"}).
				Scan(&faceId); err != nil {
				utils.SendJSReply(map[string]interface{}{"result": err.Error()}, this.Response)

				return
			}
			db.QueryRow(db.QueryGetCaptRegIdByGroupRegIdAndFaceId, []interface{}{groupRegId, faceId}).Scan(&regId)
		}
	} else {
		db.QueryRow(db.QueryGetRegIdByGroupRegIdAndFaceId, []interface{}{groupRegId, faceId}).Scan(&regId)
	}

	log.Println("faceId: ", faceId, ", groupRegId: ", groupRegId, ", regId: ", regId, ", formType: ", personalForm)

	blank := new(models.BlankManager).NewGroupBlank(personalForm)
	blank.SetGroupRegId(groupRegId).SetFaceId(faceId)

	utils.SendJSReply(
		map[string]interface{}{
			"result": "ok",
			"data":   blank.GetBlank(),
			"role":   this.isAdmin(),
			"regId":  regId},
		this.Response)
}
Example #17
0
//-----------------------------------------------------------------------------
func (this *GridController) GetPersonsByEventId() {
	if !sessions.CheckSession(this.Response, this.Request) {
		http.Redirect(this.Response, this.Request, "/", http.StatusUnauthorized)

		return
	}

	if !this.isAdmin() {
		http.Redirect(this.Response, this.Request, "/", http.StatusForbidden)

		return
	}

	if this.Request.URL.Query().Get("event") == "" || this.Request.URL.Query().Get("params") == "" {

		return
	}

	eventId, err := strconv.Atoi(this.Request.URL.Query().Get("event"))
	if err != nil {
		utils.SendJSReply(map[string]interface{}{"result": err.Error()}, this.Response)

		return
	}

	paramsIds := strings.Split(this.Request.URL.Query().Get("params"), ",")

	if len(paramsIds) == 0 {
		utils.SendJSReply(map[string]interface{}{"result": "Выберите параметры."}, this.Response)

		return
	}

	var queryParams []interface{}
	query := "SELECT params.name FROM params WHERE params.id in ("

	for k, v := range paramsIds {
		paramId, err := strconv.Atoi(v)
		if err != nil {
			utils.SendJSReply(map[string]interface{}{"result": err.Error()}, this.Response)

			return
		}
		query += "$" + strconv.Itoa(k+1) + ", "
		queryParams = append(queryParams, paramId)
	}
	query = query[:len(query)-2]
	query += ") ORDER BY id;"

	var caption []string
	for _, v := range db.Query(query, queryParams) {
		caption = append(caption, v.(map[string]interface{})["name"].(string))
	}

	result := []interface{}{0: map[string]interface{}{"id": -1, "data": caption}}

	query = `SELECT
        reg.id as id,
        ARRAY(
            SELECT param_values.value
            FROM param_values
            INNER JOIN registrations ON registrations.id = param_values.reg_id
            INNER JOIN events ON events.id = registrations.event_id
            INNER JOIN params ON params.id = param_values.param_id
            WHERE param_values.param_id IN (` + strings.Join(db.MakeParams(len(queryParams)), ", ")
	query += `) AND events.id = $` + strconv.Itoa(len(queryParams)+1) + ` AND registrations.id = reg.id ORDER BY param_values.param_id
        ) as data

        FROM param_values
        INNER JOIN registrations as reg ON reg.id = param_values.reg_id
        INNER JOIN events as ev ON ev.id = reg.event_id
        INNER JOIN params ON params.id = param_values.param_id
        WHERE ev.id = $` + strconv.Itoa(len(queryParams)+1) + ` GROUP BY reg.id ORDER BY reg.id;`

	data := db.Query(query, append(queryParams, eventId))

	this.Render([]string{"mvc/views/list.html"}, "list", append(result, data...))
}
Example #18
0
func (this *GridController) ImportForms() {
	if !sessions.CheckSession(this.Response, this.Request) {
		http.Redirect(this.Response, this.Request, "/", http.StatusUnauthorized)

		return
	}

	if !this.isAdmin() {
		http.Redirect(this.Response, this.Request, "/", http.StatusForbidden)

		return
	}

	request, err := utils.ParseJS(this.Request, this.Response)
	if err != nil {
		utils.SendJSReply(map[string]interface{}{"result": err.Error()}, this.Response)

		return
	}

	eventId, err := strconv.Atoi(request["event_id"].(string))
	if err != nil {
		utils.SendJSReply(map[string]interface{}{"result": err.Error()}, this.Response)

		return
	}

	for _, v := range request["event_types_ids"].([]interface{}) {
		typeId, err := strconv.Atoi(v.(string))
		if err != nil {
			utils.SendJSReply(map[string]interface{}{"result": err.Error()}, this.Response)

			return
		}

		var lastEventId int
		query := `SELECT events.id FROM events
            INNER JOIN events_types ON events_types.event_id = events.id
            INNER JOIN event_types ON event_types.id = events_types.type_id
            WHERE event_types.id = $1 AND events.id <> $2
            ORDER BY id DESC LIMIT 1;`
		db.QueryRow(query, []interface{}{typeId, eventId}).Scan(&lastEventId)

		query = `SELECT forms.id FROM forms
            INNER JOIN events_forms ON events_forms.form_id = forms.id
            INNER JOIN events ON events.id = events_forms.event_id
            WHERE events.id = $1 ORDER BY forms.id;`
		formsResult := db.Query(query, []interface{}{lastEventId})

		for i := 0; i < len(formsResult); i++ {
			formId := int(formsResult[i].(map[string]interface{})["id"].(int))

			eventsForms := this.GetModel("events_forms")

			var eventFormId int
			if err := eventsForms.
				LoadWherePart(map[string]interface{}{"event_id": eventId, "form_id": formId}).
				SelectRow([]string{"id"}).
				Scan(&eventFormId); err != sql.ErrNoRows {
				continue
			}

			eventsForms.
				LoadModelData(map[string]interface{}{"event_id": eventId, "form_id": formId}).
				QueryInsert("").
				Scan()
		}
	}

	utils.SendJSReply(map[string]interface{}{"result": "ok"}, this.Response)
}
Example #19
0
func (this *GroupController) AddPerson() {
	userId, err := this.CheckSid()
	if err != nil {
		utils.SendJSReply(map[string]interface{}{"result": "Unauthorized"}, this.Response)
		return
	}

	request, err := utils.ParseJS(this.Request, this.Response)
	if err != nil {
		utils.SendJSReply(map[string]interface{}{"result": err.Error()}, this.Response)
		return
	}

	groupId, err := strconv.Atoi(request["group_id"].(string))
	if err != nil {
		utils.SendJSReply(map[string]interface{}{"result": err.Error()}, this.Response)
		return
	}

	var groupName string
	db.QueryRow("SELECT name FROM groups WHERE id = $1;", []interface{}{groupId}).Scan(&groupName)

	date := time.Now().Format("2006-01-02T15:04:05Z00:00")
	token := utils.GetRandSeq(HASH_SIZE)
	to, address, headName := "", "", ""

	query := `SELECT param_values.value
        FROM param_values
        INNER JOIN registrations ON registrations.id = param_values.reg_id
        INNER JOIN params ON params.id = param_values.param_id
        INNER JOIN events ON events.id = registrations.event_id
        INNER JOIN faces ON faces.id = registrations.face_id
        INNER JOIN users ON users.id = faces.user_id
        WHERE params.id in (5, 6, 7) AND users.id = $1 AND events.id = 1 ORDER BY params.id;`
	data := db.Query(query, []interface{}{userId})

	if len(data) < 3 {
		utils.SendJSReply(map[string]interface{}{"result": "Данные о руководителе группы отсутсвуют"}, this.Response)
		return

	} else {
		headName = data[0].(map[string]interface{})["value"].(string)
		headName += " " + data[1].(map[string]interface{})["value"].(string)
		headName += " " + data[2].(map[string]interface{})["value"].(string)
	}

	var faceId int
	this.GetModel("faces").QueryInsert("RETURNING id").Scan(&faceId)

	this.GetModel("persons").
		LoadModelData(map[string]interface{}{"face_id": faceId, "group_id": groupId, "status": false, "token": token}).
		QueryInsert("").
		Scan()

	var regId int
	this.GetModel("registrations").
		LoadModelData(map[string]interface{}{"face_id": faceId, "event_id": 1, "status": false}).
		QueryInsert("RETURNING id").
		Scan(&regId)

	var paramValueIds []string

	for _, element := range request["data"].([]interface{}) {
		paramId, err := strconv.Atoi(element.(map[string]interface{})["id"].(string))
		if err != nil {
			log.Println(err.Error())
			continue
		}

		query := `SELECT params.name FROM params WHERE params.id = $1;`
		res := db.Query(query, []interface{}{paramId})

		name := res[0].(map[string]interface{})["name"].(string)
		value := element.(map[string]interface{})["value"].(string)

		if utils.MatchRegexp("^[ \t\v\r\n\f]{0,}$", value) {
			db.QueryDeleteByIds("param_vals", strings.Join(paramValueIds, ", "))
			db.QueryDeleteByIds("registrations", strconv.Itoa(regId))
			db.QueryDeleteByIds("faces", strconv.Itoa(faceId))
			utils.SendJSReply(map[string]interface{}{"result": "Заполните параметр '" + name + "'."}, this.Response)
			return
		}

		var paramValId int
		paramValues := this.GetModel("param_values")
		err = paramValues.LoadModelData(map[string]interface{}{
			"param_id": paramId,
			"value":    value,
			"date":     date,
			"user_id":  userId,
			"reg_id":   regId}).
			QueryInsert("RETURNING id").
			Scan(&paramValId)
		if err, ok := err.(*pq.Error); ok {
			log.Println(err.Code.Name())
		}

		paramValueIds = append(paramValueIds, strconv.Itoa(paramValId))

		if paramId == 4 {
			address = value
		} else if paramId == 5 || paramId == 6 || paramId == 7 {
			to += value + " "
		}
	}

	if !mailer.InviteToGroup(to, address, token, headName, groupName) {
		utils.SendJSReply(
			map[string]interface{}{
				"result": "Вы указали неправильный email, отправить письмо-приглашенине невозможно"},
			this.Response)
		return
	}

	utils.SendJSReply(map[string]interface{}{"result": "ok"}, this.Response)
}
Example #20
0
func (this *GridController) Load(tableName string) {
	if tableName != "events" && !sessions.CheckSession(this.Response, this.Request) {
		http.Error(this.Response, "Unauthorized", 400)
		return
	}

	isAdmin := this.isAdmin()

	var filters map[string]interface{}
	if this.Request.PostFormValue("_search") == "true" {
		err := json.NewDecoder(strings.NewReader(this.Request.PostFormValue("filters"))).Decode(&filters)
		if err != nil {
			http.Error(this.Response, err.Error(), 400)
			return
		}
	}

	limit, err := strconv.Atoi(this.Request.PostFormValue("rows"))
	if err != nil {
		http.Error(this.Response, err.Error(), 400)
		return
	}

	page, err := strconv.Atoi(this.Request.PostFormValue("page"))
	if err != nil {
		http.Error(this.Response, err.Error(), 400)
		return
	}

	sord := this.Request.PostFormValue("sord")
	sidx := this.Request.FormValue("sidx")
	start := limit*page - limit

	if tableName == "search" {
		var filters map[string]interface{}
		err := json.NewDecoder(strings.NewReader(this.Request.PostFormValue("filters"))).Decode(&filters)
		if err != nil {
			utils.SendJSReply(nil, this.Response)
			return
		}

		model := this.GetModel("faces")
		query := `SELECT DISTINCT faces.id, faces.user_id
            FROM param_values
            INNER JOIN registrations ON registrations.id = param_values.reg_id
            INNER JOIN faces ON faces.id = registrations.face_id
            INNER JOIN events ON events.id = registrations.event_id
            INNER JOIN params ON params.id = param_values.param_id
            INNER JOIN users ON users.id = faces.user_id`

		where, params, _ := model.WhereByParams(filters, 1)

		if !isAdmin {
			where = ` WHERE events.id = 1 AND users.enabled = true AND ` + where
		} else {
			if where != "" {
				where = " WHERE " + where
			}
		}
		where += ` ORDER BY faces.id ` + sord
		query += where + ` LIMIT $` + strconv.Itoa(len(params)+1) + ` OFFSET $` + strconv.Itoa(len(params)+2) + `;`
		rows := db.Query(query, append(params, []interface{}{limit, start}...))

		query = `SELECT COUNT(*)
            FROM (SELECT DISTINCT faces.id, faces.user_id
            FROM param_values
            INNER JOIN registrations ON registrations.id = param_values.reg_id
            INNER JOIN faces ON faces.id = registrations.face_id
            INNER JOIN events ON events.id = registrations.event_id
            INNER JOIN params ON params.id = param_values.param_id
            INNER JOIN users ON users.id = faces.user_id`
		query += where + ") as count;"
		count := int(db.Query(query, params)[0].(map[string]interface{})["count"].(int))

		var totalPages int
		if count > 0 {
			totalPages = int(math.Ceil(float64(count) / float64(limit)))
		} else {
			totalPages = 0
		}

		result := make(map[string]interface{}, 4)
		result["rows"] = rows
		result["page"] = page
		result["total"] = totalPages
		result["records"] = count

		utils.SendJSReply(result, this.Response)
		return
	}

	model := this.GetModel(tableName)
	where, params, _ := model.Where(filters, 1)

	if tableName == "param_values" && !isAdmin {
		w := " WHERE param_values.param_id in (4, 5, 6, 7)"
		if where != "" {
			where = w + " AND " + where
		} else {
			where = w
		}
	} else {
		if where != "" {
			where = " WHERE " + where
		}
	}

	query := `SELECT ` + strings.Join(model.GetColumns(), ", ") + ` FROM ` + model.GetTableName() + where + ` ORDER BY ` + sidx + ` ` + sord + ` LIMIT $` + strconv.Itoa(len(params)+1) + ` OFFSET $` + strconv.Itoa(len(params)+2) + `;`
	rows := db.Query(query, append(params, []interface{}{limit, start}...))

	query = `SELECT COUNT(*) FROM (SELECT ` + model.GetTableName() + `.id FROM ` + model.GetTableName()
	query += where + `) as count;`
	count := int(db.Query(query, params)[0].(map[string]interface{})["count"].(int))

	var totalPages int
	if count > 0 {
		totalPages = int(math.Ceil(float64(count) / float64(limit)))
	} else {
		totalPages = 0
	}

	result := make(map[string]interface{}, 4)
	result["rows"] = rows
	result["page"] = page
	result["total"] = totalPages
	result["records"] = count

	utils.SendJSReply(result, this.Response)
}
Example #21
0
func (this *Handler) RegistrationsLoad(userId_ string) {
	userId, err := this.CheckSid()
	if err != nil {
		http.Error(this.Response, "Unauthorized", 400)
		return
	}

	limit, err := strconv.Atoi(this.Request.PostFormValue("rows"))
	if err != nil {
		http.Error(this.Response, err.Error(), 400)
		return
	}

	page, err := strconv.Atoi(this.Request.PostFormValue("page"))
	if err != nil {
		http.Error(this.Response, err.Error(), 400)
		return
	}

	sidx := this.Request.FormValue("sidx")
	start := limit*page - limit

	var id int
	if this.isAdmin() {
		id, err = strconv.Atoi(userId_)
		if err != nil {
			http.Error(this.Response, err.Error(), 400)
			return
		}
	} else {
		id = userId
	}

	query := `SELECT registrations.id, registrations.event_id, registrations.status FROM registrations
        INNER JOIN events ON events.id = registrations.event_id
        INNER JOIN events_forms ON events_forms.event_id = events.id
        INNER JOIN forms ON forms.id = events_forms.form_id
        INNER JOIN params ON forms.id = params.form_id
        INNER JOIN param_types ON param_types.id = params.param_type_id
        INNER JOIN param_values ON params.id = param_values.param_id AND param_values.reg_id = registrations.id
        INNER JOIN faces ON faces.id = registrations.face_id
        INNER JOIN users ON users.id = faces.user_id
        WHERE users.id = $1 AND forms.personal = true
        GROUP BY registrations.id
        ORDER BY $2 LIMIT $3 OFFSET $4;`
	rows := db.Query(query, []interface{}{id, sidx, limit, start})

	query = `SELECT COUNT(*) FROM (SELECT registrations.id FROM registrations
        INNER JOIN events ON events.id = registrations.event_id
        INNER JOIN events_forms ON events_forms.event_id = events.id
        INNER JOIN forms ON forms.id = events_forms.form_id
        INNER JOIN params ON forms.id = params.form_id
        INNER JOIN param_types ON param_types.id = params.param_type_id
        INNER JOIN param_values ON params.id = param_values.param_id AND param_values.reg_id = registrations.id
        INNER JOIN faces ON faces.id = registrations.face_id
        INNER JOIN users ON users.id = faces.user_id
        WHERE users.id = $1 AND forms.personal = true
        GROUP BY registrations.id) as count;`
	count := int(db.Query(query, []interface{}{id})[0].(map[string]interface{})["count"].(int))

	var totalPages int
	if count > 0 {
		totalPages = int(math.Ceil(float64(count) / float64(limit)))
	} else {
		totalPages = 0
	}

	result := make(map[string]interface{}, 2)
	result["rows"] = rows
	result["page"] = page
	result["total"] = totalPages
	result["records"] = count

	utils.SendJSReply(result, this.Response)
}
Example #22
0
func (this *UserController) ConfirmOrRejectPersonRequest() {
	if !sessions.CheckSession(this.Response, this.Request) {
		http.Redirect(this.Response, this.Request, "/", http.StatusUnauthorized)
		return
	}

	if !this.isAdmin() {
		http.Redirect(this.Response, this.Request, "/", http.StatusForbidden)
		return
	}

	request, err := utils.ParseJS(this.Request, this.Response)
	if err != nil {
		utils.SendJSReply(map[string]interface{}{"result": err.Error()}, this.Response)
		return
	}

	eventId, err := strconv.Atoi(request["event_id"].(string))
	if err != nil {
		utils.SendJSReply(map[string]interface{}{"result": err.Error()}, this.Response)
		return
	}

	regId, err := strconv.Atoi(request["reg_id"].(string))
	if err != nil {
		utils.SendJSReply(map[string]interface{}{"result": err.Error()}, this.Response)
		return
	}

	query := `SELECT param_values.value, users.id as user_id
        FROM param_values
        INNER JOIN registrations ON registrations.id = param_values.reg_id
        INNER JOIN params ON params.id = param_values.param_id
        INNER JOIN events ON events.id = registrations.event_id
        INNER JOIN faces ON faces.id = registrations.face_id
        INNER JOIN users ON users.id = faces.user_id
        WHERE params.id in (4, 5, 6, 7) AND users.id in (
            SELECT users.id FROM registrations INNER JOIN events ON events.id = registrations.event_id
            INNER JOIN faces ON faces.id = registrations.face_id
            INNER JOIN users ON users.id = faces.user_id
            WHERE registrations.id = $1
        ) ORDER BY params.id;`

	data := db.Query(query, []interface{}{regId})

	if len(data) < 2 {
		utils.SendJSReply(
			map[string]interface{}{"result": "Нет регистрационных данных пользователя"},
			this.Response)
		return
	}

	email := data[0].(map[string]interface{})["value"].(string)

	to := data[1].(map[string]interface{})["value"].(string)
	to += " " + data[2].(map[string]interface{})["value"].(string)
	to += " " + data[3].(map[string]interface{})["value"].(string)

	event := db.Query(
		"SELECT name FROM events WHERE id=$1;",
		[]interface{}{eventId})[0].(map[string]interface{})["name"].(string)

	if request["confirm"].(bool) {
		if eventId == 1 {
			utils.SendJSReply(map[string]interface{}{"result": "Эту заявку нельзя подтвердить письмом"}, this.Response)
		} else {
			if mailer.SendEmailToConfirmRejectPersonRequest(to, email, event, true) {
				utils.SendJSReply(map[string]interface{}{"result": "Письмо с подтверждением заявки отправлено"}, this.Response)
			} else {
				utils.SendJSReply(map[string]interface{}{"result": "Ошибка. Письмо с подтверждением заявки не отправлено"}, this.Response)
			}
		}

	} else {
		if eventId == 1 {
			utils.SendJSReply(map[string]interface{}{"result": "Эту заявку нельзя отклонить письмом"}, this.Response)
		} else {
			query := `DELETE FROM param_values WHERE param_values.reg_id = $1;`
			db.Query(query, []interface{}{regId})

			query = `DELETE FROM registrations WHERE id = $1;`
			db.Query(query, []interface{}{regId})

			if mailer.SendEmailToConfirmRejectPersonRequest(to, email, event, false) {
				utils.SendJSReply(map[string]interface{}{"result": "Письмо с отклонением заявки отправлено"}, this.Response)
			} else {
				utils.SendJSReply(map[string]interface{}{"result": "Ошибка. Письмо с отклонением заявки не отправлено"}, this.Response)
			}
		}
	}
}
Example #23
0
func (this *Handler) PersonsLoad(groupId string) {
	userId, err := this.CheckSid()
	if err != nil {
		http.Error(this.Response, "Unauthorized", 400)
		return
	}

	limit, err := strconv.Atoi(this.Request.PostFormValue("rows"))
	if err != nil {
		http.Error(this.Response, err.Error(), 400)
		return
	}

	page, err := strconv.Atoi(this.Request.PostFormValue("page"))
	if err != nil {
		http.Error(this.Response, err.Error(), 400)
		return
	}

	id, err := strconv.Atoi(groupId)
	if err != nil {
		http.Error(this.Response, err.Error(), 400)
		return
	}

	faceId := -1
	query := `SELECT groups.face_id FROM groups
        INNER JOIN faces ON faces.id = groups.face_id
        INNER JOIN users ON users.id = faces.user_id
        WHERE users.id = $1 AND groups.id = $2;`
	err = db.QueryRow(query, []interface{}{userId, id}).Scan(&faceId)

	if (err != nil || faceId == -1) && !this.isAdmin() {
		http.Error(this.Response, "Вы не являетесь владельцем группы", 400)
		return
	}

	sidx := this.Request.FormValue("sidx")
	start := limit*page - limit

	query = `SELECT persons.id, persons.group_id, persons.face_id, persons.status
        FROM persons
        INNER JOIN groups ON groups.id = persons.group_id
        WHERE groups.id = $1 ORDER BY $2 LIMIT $3 OFFSET $4;`
	rows := db.Query(query, []interface{}{id, sidx, limit, start})

	query = `SELECT COUNT(*) FROM (SELECT persons.id FROM persons
        INNER JOIN groups ON groups.id = persons.group_id
        WHERE groups.id = $1) as count;`
	count := int(db.Query(query, []interface{}{id})[0].(map[string]interface{})["count"].(int))

	log.Println("count: ", count)

	var totalPages int
	if count > 0 {
		totalPages = int(math.Ceil(float64(count) / float64(limit)))
	} else {
		totalPages = 0
	}

	result := make(map[string]interface{}, 2)
	result["rows"] = rows
	result["page"] = page
	result["total"] = totalPages
	result["records"] = count

	utils.SendJSReply(result, this.Response)
}
Example #24
0
func (this *RegistrationController) EventRegisterAction() {
	var result string
	var regId int

	data, err := utils.ParseJS(this.Request, this.Response)
	if err != nil {
		utils.SendJSReply(map[string]interface{}{"result": err.Error()}, this.Response)

		return
	}

	eventId := int(data["event_id"].(float64))

	if eventId == 1 && sessions.CheckSession(this.Response, this.Request) {
		utils.SendJSReply(map[string]interface{}{"result": "authorized"}, this.Response)

		return
	}

	if sessions.CheckSession(this.Response, this.Request) {
		userId, err := this.CheckSid()
		if err != nil {
			utils.SendJSReply(map[string]interface{}{"result": "Unauthorized"}, this.Response)

			return
		}

		var faceId int
		query := `SELECT faces.id FROM faces
            INNER JOIN registrations ON registrations.face_id = faces.id
            INNER JOIN events ON events.id = registrations.event_id
            INNER JOIN users ON users.id = faces.user_id
            WHERE users.id = $1 AND events.id = 1;`
		err = db.QueryRow(query, []interface{}{userId}).Scan(&faceId)

		if err != nil {
			utils.SendJSReply(map[string]interface{}{"result": err.Error()}, this.Response)

			return
		}

		this.GetModel("registrations").
			LoadModelData(map[string]interface{}{"face_id": faceId, "event_id": eventId, "status": false}).
			QueryInsert("RETURNING id").
			Scan(&regId)

		if err = this.InsertUserParams(userId, regId, data["data"].([]interface{})); err != nil {
			utils.SendJSReply(map[string]interface{}{"result": err.Error()}, this.Response)

			return
		}

	} else if eventId == 1 {
		userLogin, userPass, email, flag := "", "", "", 0

		for _, element := range data["data"].([]interface{}) {
			paramId, err := strconv.Atoi(element.(map[string]interface{})["id"].(string))
			if err != nil {
				continue
			}

			value := element.(map[string]interface{})["value"].(string)

			if paramId == 1 {
				if utils.MatchRegexp("^[ \t\v\r\n\f]{0,}$", value) {
					utils.SendJSReply(map[string]interface{}{"result": "Заполните параметр 'Логин'."}, this.Response)

					return
				}
				userLogin = value
				flag += 1
				continue

			} else if paramId == 2 || paramId == 3 {
				if utils.MatchRegexp("^[ \t\v\r\n\f]{0,}$", value) {
					utils.SendJSReply(map[string]interface{}{"result": "Заполните параметр 'Пароль/Подтвердите пароль'."}, this.Response)

					return
				}
				userPass = value
				flag += 1
				continue

			} else if paramId == 4 {
				if utils.MatchRegexp("^[ \t\v\r\n\f]{0,}$", value) {
					utils.SendJSReply(map[string]interface{}{"result": "Заполните параметр 'Email'."}, this.Response)

					return
				}
				email = value
				flag += 1
				continue

			} else if flag > 3 {
				break
			}
		}

		result, regId = this.Register(userLogin, userPass, email, "user")
		if result != "ok" && regId == -1 {
			utils.SendJSReply(map[string]interface{}{"result": result}, this.Response)

			return
		}

		query := `SELECT users.id
            FROM users
            INNER JOIN faces ON faces.user_id = users.id
            INNER JOIN registrations ON registrations.face_id = faces.id
            WHERE registrations.id = $1;`
		userId := db.Query(query, []interface{}{regId})[0].(map[string]interface{})["id"].(int)

		err = this.InsertUserParams(userId, regId, data["data"].([]interface{}))
		if err != nil {
			db.QueryDeleteByIds("users", strconv.Itoa(userId))
			utils.SendJSReply(map[string]interface{}{"result": err.Error()}, this.Response)

			return
		}

	} else {
		utils.SendJSReply(map[string]interface{}{"result": "Unauthorized"}, this.Response)

		return
	}

	utils.SendJSReply(map[string]interface{}{"result": "ok"}, this.Response)
}
Example #25
0
func (this *UserController) CheckEnable(id string) {
	eventId, err := strconv.Atoi(id)
	if utils.HandleErr("[UserController::CheckEnable] event_id Atoi: ", err, this.Response) {
		utils.SendJSReply(map[string]interface{}{"result": err.Error()}, this.Response)
		return
	}

	if eventId == 1 {
		if sessions.CheckSession(this.Response, this.Request) {
			utils.SendJSReply(map[string]interface{}{"result": "authorized"}, this.Response)
			return
		}
		utils.SendJSReply(map[string]interface{}{"result": "ok"}, this.Response)
		return
	}

	userId, err := this.CheckSid()
	if err != nil && eventId != 1 {
		utils.SendJSReply(map[string]interface{}{"result": "Unauthorized"}, this.Response)
		return
	}

	regId := this.regExists(userId, eventId)
	if regId == -1 {
		groups := this.GetModel("groups")
		persons := this.GetModel("persons")
		groupsModel := Model{
			TableName:    groups.GetTableName(),
			ColNames:     groups.GetColNames(),
			ColModel:     groups.GetColModel(false, userId),
			Caption:      groups.GetCaption(),
			Sub:          groups.GetSub(),
			SubTableName: persons.GetTableName(),
			SubCaption:   persons.GetCaption(),
			SubColModel:  persons.GetColModel(false, userId),
			SubColNames:  persons.GetColNames()}
		utils.SendJSReply(map[string]interface{}{"result": "ok", "groups": groupsModel}, this.Response)
	} else {
		var teamEvent bool
		if err = this.GetModel("events").
			LoadWherePart(map[string]interface{}{"id": eventId}).
			SelectRow([]string{"team"}).
			Scan(&teamEvent); err != nil {
			utils.SendJSReply(map[string]interface{}{"result": err.Error()}, this.Response)
			return
		}

		if teamEvent {
			var groupRegId int
			query := `SELECT group_registrations.id
                FROM regs_groupregs
                INNER JOIN registrations ON registrations.id = regs_groupregs.reg_id
                INNER JOIN group_registrations ON group_registrations.id = regs_groupregs.groupreg_id
                INNER JOIN events ON events.id = registrations.event_id AND events.id = group_registrations.event_id
                INNER JOIN faces ON faces.id = registrations.face_id
                INNER JOIN users ON users.id = faces.user_id
                INNER JOIN groups ON group_registrations.group_id = groups.id
                WHERE users.id = $1 AND events.id = $2 GROUP BY group_registrations.id;`
			db.QueryRow(query, []interface{}{userId, eventId}).Scan(&groupRegId)
			utils.SendJSReply(map[string]interface{}{"result": "regExists", "groupRegId": strconv.Itoa(groupRegId)}, this.Response)
		} else {
			utils.SendJSReply(map[string]interface{}{"result": "regExists", "regId": strconv.Itoa(regId)}, this.Response)
		}
	}
}
Example #26
0
func (this *GroupController) Register() {
	userId, err := this.CheckSid()
	if err != nil {
		http.Redirect(this.Response, this.Request, "/", http.StatusUnauthorized)
		return
	}

	request, err := utils.ParseJS(this.Request, this.Response)
	if err != nil {
		utils.SendJSReply(map[string]interface{}{"result": err.Error()}, this.Response)
	}

	groupId, err := strconv.Atoi(request["group_id"].(string))
	if err != nil {
		utils.SendJSReply(map[string]interface{}{"result": err.Error()}, this.Response)
	}

	eventId, err := strconv.Atoi(request["event_id"].(string))
	if err != nil {
		utils.SendJSReply(map[string]interface{}{"result": err.Error()}, this.Response)
	}

	var eventName string
	var teamEvent bool
	if err = this.GetModel("events").
		LoadWherePart(map[string]interface{}{"id": eventId}).
		SelectRow([]string{"name", "team"}).
		Scan(&eventName, &teamEvent); err != nil {
		utils.SendJSReply(map[string]interface{}{"result": err.Error()}, this.Response)
		return
	}

	faceId, groupName := 1, ""
	query := `SELECT groups.face_id, groups.name FROM groups
        INNER JOIN faces ON faces.id = groups.face_id
        INNER JOIN users ON users.id = faces.user_id
        WHERE users.id = $1 AND groups.id = $2;`
	err = db.QueryRow(query, []interface{}{userId, groupId}).Scan(&faceId, &groupName)

	if (err != nil || faceId == 1 || groupName == "") && !this.isAdmin() {
		utils.SendJSReply(map[string]interface{}{"result": "Вы не являетесь владельцем группы"}, this.Response)
		return
	}

	if db.IsExists("group_registrations", []string{"group_id", "event_id"}, []interface{}{groupId, eventId}) {
		utils.SendJSReply(map[string]interface{}{"result": "Группа уже зарегистрированна в этом мероприятии"}, this.Response)
		return
	}

	var groupregId int
	this.GetModel("group_registrations").
		LoadModelData(map[string]interface{}{"event_id": eventId, "group_id": groupId, "status": false}).
		QueryInsert("RETURNING id").
		Scan(&groupregId)

	query = `SELECT persons.status, persons.group_id, f.id as face_id,
        array_to_string(
        array(
            SELECT param_values.value
            FROM param_values
            INNER JOIN registrations ON registrations.id = param_values.reg_id
            INNER JOIN faces ON faces.id = registrations.face_id
            INNER JOIN events ON events.id = registrations.event_id
            INNER JOIN params ON params.id = param_values.param_id
            WHERE param_values.param_id IN (5, 6, 7) AND events.id = 1 AND faces.id = f.id ORDER BY param_values.param_id
        ), ' ') as name,

        (SELECT param_values.value
            FROM param_values
            INNER JOIN registrations ON registrations.id = param_values.reg_id
            INNER JOIN faces ON faces.id = registrations.face_id
            INNER JOIN events ON events.id = registrations.event_id
            INNER JOIN params ON params.id = param_values.param_id
            WHERE param_values.param_id = 4 AND events.id = 1 AND faces.id = f.id
        ) as email

        FROM persons
        INNER JOIN groups ON groups.id = persons.group_id
        INNER JOIN faces as f ON f.id = persons.face_id
        WHERE groups.id = $1;`
	data := db.Query(query, []interface{}{groupId})

	query = `SELECT params.id FROM events_forms
        INNER JOIN events ON events.id = events_forms.event_id
        INNER JOIN forms ON forms.id = events_forms.form_id
        INNER JOIN params ON forms.id = params.form_id
        WHERE events.id = $1 AND forms.personal = true ORDER BY forms.id;`
	params := db.Query(query, []interface{}{eventId})

	date := time.Now().Format("20060102T15:04:05Z00:00")

	for _, v := range data {
		status := v.(map[string]interface{})["status"].(bool)
		personFaceId := v.(map[string]interface{})["face_id"].(int)
		var personUserId int
		this.GetModel("faces").
			LoadWherePart(map[string]interface{}{"id": personFaceId}).
			SelectRow([]string{"user_id"}).
			Scan(&personUserId)

		if !status {
			continue
		}

		regId := this.regExists(personUserId, eventId)
		if regId == -1 {
			this.GetModel("registrations").
				LoadModelData(map[string]interface{}{
					"face_id":  personFaceId,
					"event_id": eventId,
					"status":   false}).
				QueryInsert("RETURNING id").
				Scan(&regId)

			for _, elem := range params {
				paramId := int(elem.(map[string]interface{})["id"].(int))
				this.GetModel("param_values").
					LoadModelData(map[string]interface{}{
						"param_id": paramId,
						"value":    " ",
						"date":     date,
						"user_id":  userId,
						"reg_id":   regId}).
					QueryInsert("").
					Scan()
			}
		}

		this.GetModel("regs_groupregs").
			LoadModelData(map[string]interface{}{"groupreg_id": groupregId, "reg_id": regId}).
			QueryInsert("").
			Scan()

		to := v.(map[string]interface{})["name"].(string)
		address := v.(map[string]interface{})["email"].(string)
		if !mailer.AttendAnEvent(to, address, eventName, groupName) {
			utils.SendJSReply(map[string]interface{}{"result": "Ошибка. Письмо с уведомлением не отправлено."}, this.Response)
		}
	}

	if teamEvent == true {
		query = `SELECT params.id FROM events_forms
            INNER JOIN events ON events.id = events_forms.event_id
            INNER JOIN forms ON forms.id = events_forms.form_id
            INNER JOIN params ON forms.id = params.form_id
            WHERE events.id = $1 AND forms.personal = false ORDER BY forms.id;`
		params := db.Query(query, []interface{}{eventId})

		var regId int
		this.GetModel("registrations").
			LoadModelData(map[string]interface{}{"face_id": faceId, "event_id": eventId, "status": false}).
			QueryInsert("RETURNING id").
			Scan(&regId)

		for _, elem := range params {
			this.GetModel("param_values").
				LoadModelData(map[string]interface{}{
					"param_id": int(elem.(map[string]interface{})["id"].(int)),
					"value":    " ",
					"date":     date,
					"user_id":  userId,
					"reg_id":   regId}).
				QueryInsert("").
				Scan()
		}

		this.GetModel("regs_groupregs").
			LoadModelData(map[string]interface{}{"groupreg_id": groupregId, "reg_id": regId}).
			QueryInsert("").
			Scan()
	}

	utils.SendJSReply(map[string]interface{}{"result": "ok"}, this.Response)
}