Example #1
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)
}
Example #2
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 #3
0
func (this *Controller) CheckSid() (id int, result error) {
	userSid := sessions.GetValue("sid", this.Request)
	if !sessions.CheckSession(this.Response, this.Request) || userSid == nil {
		return -1, errors.New("Данные в куках отсутствуют.")
	}

	if err := this.GetModel("users").
		LoadWherePart(map[string]interface{}{"sid": userSid}).
		SelectRow([]string{"id"}).
		Scan(&id); err != nil {
		return -1, errors.New("Данные в куках отсутствуют.")
	}

	return id, nil
}
Example #4
0
func (this *BlankController) GetBlankByEventId(id string) {
	eventId, err := strconv.Atoi(id)
	if utils.HandleErr("[BlankController::GetBlankByEventId] event_id Atoi: ", err, this.Response) {
		return
	}

	if !sessions.CheckSession(this.Response, this.Request) && eventId != 1 {
		this.Render([]string{"mvc/views/loginpage.html", "mvc/views/login.html"}, "loginpage", nil)

		return
	}

	this.Render(
		[]string{"mvc/views/item.html"},
		"item",
		map[string]interface{}{"data": new(models.BlankManager).NewPersonalBlank(true).GetEmptyBlank(eventId)})
}
Example #5
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 #6
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 #7
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 #8
0
//-----------------------------------------------------------------------------
func (this *GridController) JsonToExcel(tableName string) {
	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 {
		http.Error(this.Response, fmt.Sprintf(err.Error()), 400)

		return
	}

	var filters map[string]interface{}
	if request["filters"] == nil {
		filters = nil
	} else {
		filters = request["filters"].(map[string]interface{})
	}

	fields := utils.ArrayInterfaceToString(request["fields"].([]interface{}))
	data := this.GetModel(tableName).
		SetSorting(request["sord"].(string)).
		SetOrder(request["sidx"].(string)).
		Select(fields, filters)

	this.Response.Header().Set("Content-type", "text/csv")
	w := csv.NewWriter(this.Response)

	for _, obj := range data {
		var record []string

		for _, col := range obj.(map[string]interface{}) {
			fmt.Printf("type=%s\n", reflect.TypeOf(col))
			switch col.(type) {
			case int:
				record = append(record, strconv.Itoa(col.(int)))
				break
			case int64:
				record = append(record, strconv.Itoa(int(col.(int64))))
				break
			case string:
				record = append(record, col.(string))
				break
			case bool:
				record = append(record, strconv.FormatBool(col.(bool)))
				break
			case []string:
				record = append(record, col.([]string)[0])
				break
			case time.Time:
				record = append(record, col.(time.Time).Format("2006-01-02 15:04:05 07:00"))
			default:
				panic("JsonToExcel: Unexpected type.")
			}
		}

		w.Write(record)
	}

	w.Flush()
}
Example #9
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 #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)
}
Example #11
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 #12
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)
}