Exemple #1
0
func (this *Entity) QueryUpdate() *sql.Row {
	j := 1
	query := "UPDATE %s SET "
	tFields := reflect.ValueOf(this.fields).Type().Elem()
	vFields := reflect.ValueOf(this.fields).Elem()
	params := make([]interface{}, 0)

	for i := 1; i < tFields.NumField(); i++ {
		value, ok := utils.UpdateOrNot(tFields.Field(i).Tag.Get("type"), vFields.Field(i))
		if !ok {
			continue
		}
		query += tFields.Field(i).Tag.Get("name") + "=$" + strconv.Itoa(j) + ", "
		params = append(params, value)
		j++
	}
	query = query[0 : len(query)-2]

	if len(this.wherePart) != 0 {
		query += " WHERE %s;"
		v1, v2 := this.GenerateWherePart(j)

		return db.QueryRow(fmt.Sprintf(query, this.tableName, v1), append(params, v2...))
	} else {
		query += ";"

		return db.QueryRow(fmt.Sprintf(query, this.tableName), params)
	}
}
Exemple #2
0
func (this *Entity) SelectRow(fields []string) *sql.Row {
	query := "SELECT %s FROM %s"

	if len(this.wherePart) != 0 {
		query += " WHERE %s;"
		where, params := this.GenerateWherePart(1)

		return db.QueryRow(fmt.Sprintf(query, strings.Join(fields, ", "), this.tableName, where), params)
	} else {
		query += ";"

		return db.QueryRow(fmt.Sprintf(query, strings.Join(fields, ", "), this.tableName), nil)
	}
}
Exemple #3
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)
}
Exemple #4
0
func (this *GroupsModel) Add(userId int, params map[string]interface{}) error {
	var faceId int
	query := `SELECT faces.id
        FROM registrations
        INNER JOIN faces ON faces.id = registrations.face_id
        INNER JOIN events ON events.id = registrations.event_id
        INNER JOIN users ON faces.user_id = users.id
        WHERE users.id = $1 AND events.id = $2;`
	db.QueryRow(query, []interface{}{userId, 1}).Scan(&faceId)
	params["face_id"] = faceId
	this.LoadModelData(params).QueryInsert("").Scan()
	return nil
}
Exemple #5
0
func (*Controller) regExists(userId, eventId int) int {
	var regId int
	query := `SELECT registrations.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 users.id = $1 AND events.id = $2;`
	err := db.QueryRow(query, []interface{}{userId, eventId}).Scan(&regId)
	if err != sql.ErrNoRows {
		return regId
	} else {
		return -1
	}
}
Exemple #6
0
func (this *GroupsModel) Update(isAdmin bool, userId int, params, where map[string]interface{}) {
	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;`
	db.QueryRow(query, []interface{}{userId, where["id"]}).Scan(&faceId)

	if !isAdmin && faceId == -1 {
		log.Println("Нет прав редактировать эту группу")
		return
	}

	this.LoadModelData(params).LoadWherePart(where).QueryUpdate().Scan()
}
Exemple #7
0
func (this *Entity) QueryInsert(extra string) *sql.Row {
	i := 1
	query := "INSERT INTO %s ("
	tFields := reflect.ValueOf(this.fields).Type().Elem()
	vFields := reflect.ValueOf(this.fields).Elem()
	params := make([]interface{}, 0)

	for i = 1; i < tFields.NumField(); i++ {
		value, ok := utils.UpdateOrNot(tFields.Field(i).Tag.Get("type"), vFields.Field(i))
		if !ok && tFields.Field(i).Tag.Get("null") == "NULL" {
			value = nil
		}
		query += tFields.Field(i).Tag.Get("name") + ", "
		params = append(params, value)
	}
	query = query[0 : len(query)-2]
	query += ") VALUES (%s) %s;"

	return db.QueryRow(fmt.Sprintf(query, this.tableName, strings.Join(db.MakeParams(i-1), ", "), extra), params)
}
Exemple #8
0
func (this *Entity) QueryUpdate() *sql.Row {
	query := fmt.Sprintf("UPDATE %s SET ", this.tableName)
	tFields := reflect.ValueOf(this.fields).Type().Elem()
	vFields := reflect.ValueOf(this.fields).Elem()
	params := make([]interface{}, 0)

	var set []string
	for i := 1; i < tFields.NumField(); i++ {
		if value, ok := utils.UpdateOrNot(tFields.Field(i).Tag.Get("type"), vFields.Field(i)); ok {
			params = append(params, value)
			set = append(set, tFields.Field(i).Tag.Get("name")+"=$"+strconv.Itoa(len(params)))
		}
	}
	query += strings.Join(set, ", ")

	if len(this.wherePart) != 0 {
		v1, v2 := this.GenerateWherePart(len(params) + 1)
		query += " WHERE " + v1
		params = append(params, v2...)
	}
	return db.QueryRow(query+";", params)
}
Exemple #9
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)
		}
	}
}
Exemple #10
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)
}
Exemple #11
0
func (this *PersonsModel) Add(userId int, params map[string]interface{}) error {
	var to, address string

	token := utils.GetRandSeq(HASH_SIZE)
	params["token"] = token

	log.Println("face_id: ", params["face_id"])
	log.Println("group_id: ", params["group_id"])
	log.Println("status: ", params["status"])

	if db.IsExists("persons", []string{"face_id", "group_id"}, []interface{}{params["face_id"], params["group_id"]}) {
		return errors.New("Участник уже состоит в группе")
	}

	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})
	headName := ""
	if len(data) < 3 {
		return errors.New("Данные о руководителе группы отсутсвуют")

	} 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)
	}

	groupId, err := strconv.Atoi(params["group_id"].(string))
	if err != nil {
		return err
	}

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

	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 faces.id = $1 AND events.id = 1 ORDER BY params.id;`
	data = db.Query(query, []interface{}{params["face_id"]})
	if len(data) < 4 {
		return errors.New("Данные о приглашаемом участнике отсутсвуют.")

	} else {
		address = 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)
	}

	if !mailer.InviteToGroup(to, address, token, headName, groupName) {
		return errors.New("Участник скорее всего указал неправильный email, отправить письмо-приглашенине невозможно")
	}

	this.LoadModelData(params).QueryInsert("").Scan()
	return nil
}
Exemple #12
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)
}
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)
}
Exemple #14
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)
}
Exemple #15
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)
}
Exemple #16
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)
}