func (s *ScenarioSimulation) GetDataSimulation(k *knot.WebContext) interface{} {
	k.Config.OutputType = knot.OutputJson

	result, status, msg := tk.M{}, "", ""

	simDataTmp := []tk.M{}
	filter := tk.M{}
	filter.Set("name", "GetAllScenarioSimulation")
	csr, err := s.DB().Connection.NewQuery().Command("procedure", filter).Cursor(nil)
	defer csr.Close()

	err = csr.Fetch(&simDataTmp, 0, true)

	if err != nil {
		msg = err.Error()
		status = "NOK"
	} else {
		status = "OK"
	}

	SimulationDatas := constructScenarionSimulation(simDataTmp)

	result.Set("Status", status)
	result.Set("Message", msg)
	result.Set("Data", SimulationDatas)

	return result
}
Beispiel #2
0
func decodeTSV(file []byte) (retVal interface{}, e error) {
	reader := csv.NewReader(strings.NewReader(string(file)))
	reader.Comma = '\t'
	records, e := reader.ReadAll()

	if e != nil {
		return
	}

	var list []interface{}

	for _, row := range records {
		line := toolkit.M{}
		for idx, val := range row {
			line.Set(toolkit.ToString(idx), val)
		}

		list = append(list, line)
	}

	if len(list) > 0 {
		retVal = list[0]
	}

	return
}
Beispiel #3
0
func (a *GroupController) FindUserLdap(r *knot.WebContext) interface{} {
	r.Config.OutputType = knot.OutputJson
	payload := map[string]interface{}{}
	err := r.GetPayload(&payload)
	if err != nil {
		return helper.CreateResult(false, nil, err.Error())
	}

	addr := payload["Address"].(string)
	basedn := payload["BaseDN"].(string)
	filter := payload["Filter"].(string)
	username := payload["Username"].(string)
	password := payload["Password"].(string)
	var attr []string

	err = toolkit.Serde(payload["Attribute"], &attr, "json")
	if err != nil {
		return helper.CreateResult(false, err, "error")
	}

	param := toolkit.M{}

	param.Set("username", username)
	param.Set("password", password)
	param.Set("attributes", attr)

	arrm, err := acl.FindDataLdap(addr, basedn, filter, param)
	if err != nil {
		return helper.CreateResult(false, err, "error")
	}

	return helper.CreateResult(true, arrm, "success")
}
Beispiel #4
0
func (d *DataContext) Find(m IModel, parms tk.M) (dbox.ICursor, error) {
	////_ = "breakpoint"
	q := d.Connection.NewQuery().From(m.TableName())
	if qe := parms.Get(ConfigSelect); qe != nil {
		fields := qe.(string)
		selectFields := strings.Split(fields, ",")
		q = q.Select(selectFields...)
	}
	if qe := parms.Get(ConfigWhere, nil); qe != nil {
		//q = q.Where(qe.(*dbox.Filter))
		filters := qe.([]*dbox.Filter)
		if len(filters) > 0 {
			q = q.Where(dbox.And(filters...))
		}
	}
	if qe := parms.Get(ConfigOrder, nil); qe != nil {
		q = q.Order(qe.([]string)...)
	}
	if qe := parms.Get(ConfigSkip, nil); qe != nil {
		q = q.Skip(qe.(int))
	}
	if qe := parms.Get(ConfigLimit, nil); qe != nil {
		q = q.Take(qe.(int))
	}
	//fmt.Printf("Debug Q: %s\n", tk.JsonString(q))
	return q.Cursor(nil)
	//return c
}
func (d *DataBrowserController) parseQuery(conn dbox.IConnection, dbrowser colonycore.DataBrowser, datacon *colonycore.Connection) (dbox.IQuery, error) {
	var dataQuery dbox.IQuery

	if dbrowser.QueryType == "nonQueryText" {
		dataQuery = conn.NewQuery().From(dbrowser.TableNames)
	} else if dbrowser.QueryType == "SQL" {
		if toolkit.HasMember(rdbms, datacon.Driver) {
			dataQuery = conn.NewQuery().Command("freequery", toolkit.M{}.
				Set("syntax", dbrowser.QueryText))
		} else {
			return nil, errors.New("Free Text Query with SQL only for RDBMS, please use Dbox")
		}
	} else if dbrowser.QueryType == "Dbox" {
		queryInfo := toolkit.M{}
		toolkit.UnjsonFromString(dbrowser.QueryText, &queryInfo)
		toolkit.Println("queryinfo", queryInfo)

		if qFrom := queryInfo.Get("from", "").(string); qFrom != "" {
			dataQuery = conn.NewQuery()
			dataQuery = dataQuery.From(qFrom)
		}
		if qSelect := queryInfo.Get("select", "").(string); qSelect != "" {
			if qSelect != "*" {
				dataQuery = dataQuery.Select(strings.Split(qSelect, ",")...)
			}
		}
	}
	return dataQuery, nil
}
Beispiel #6
0
func (c *ValueEquationController) Initiate(k *knot.WebContext) interface{} {
	k.Config.OutputType = knot.OutputJson
	var e error
	csr, e := c.Ctx.Find(new(PlantModel), tk.M{}.Set("skip", 0).Set("limit", 0))
	defer csr.Close()
	PlantList := make([]PlantModel, 0)
	e = csr.Fetch(&PlantList, 0, false)
	if e != nil {
		return e.Error()
	}
	csr, e = c.Ctx.Find(new(PhaseModel), tk.M{}.Set("skip", 0).Set("limit", 0))
	PhaseList := make([]PhaseModel, 0)
	e = csr.Fetch(&PhaseList, 0, false)
	if e != nil {
		return e.Error()
	}
	csr, e = c.Ctx.Find(new(UnitModel), tk.M{}.Set("skip", 0).Set("limit", 0))
	UnitList := make([]UnitModel, 0)
	e = csr.Fetch(&UnitList, 0, false)
	if e != nil {
		return e.Error()
	}
	result := tk.M{}
	result.Set("PlantList", PlantList)
	result.Set("PhaseList", PhaseList)
	result.Set("UnitList", UnitList)
	return ResultInfo(result, e)
}
Beispiel #7
0
func (a *UserController) TestFindUserLdap(r *knot.WebContext) interface{} {
	r.Config.OutputType = knot.OutputJson
	payload := map[string]interface{}{}
	err := r.GetPayload(&payload)
	if err != nil {
		return helper.CreateResult(false, nil, err.Error())
	}

	addr := toolkit.ToString(payload["Address"])  //192.168.0.200:389
	basedn := toolkit.ToString(payload["BaseDN"]) //DC=eaciit,DC=local
	filter := toolkit.ToString(payload["Filter"]) //(&(objectclass=person)(objectclass=organizationalPerson)(cn=*))
	var attr []string

	err = toolkit.Serde(payload["Attribute"], &attr, "json")
	if err != nil {
		return helper.CreateResult(true, err, "error")
	}

	param := toolkit.M{}

	param.Set("username", toolkit.ToString(payload["Username"])) //Alip Sidik
	param.Set("password", toolkit.ToString(payload["Password"])) //Password.1
	// param.Set("attributes", []string{"cn", "givenName"})
	param.Set("attributes", attr)

	arrtkm, err := acl.FindDataLdap(addr, basedn, filter, param)
	if err != nil {
		return helper.CreateResult(true, err, "error")
	}
	return helper.CreateResult(true, arrtkm, "sukses")
}
Beispiel #8
0
func getresultobj(strsplits []string, tval interface{}, val toolkit.M) interface{} {
	var xval interface{}
	if val == nil {
		val = toolkit.M{}
	}

	switch {
	case len(strsplits) == 1:
		xval = tval
	case len(strsplits) > 1:
		tm := toolkit.M{}
		if val.Has(strsplits[1]) {
			tm, _ = toolkit.ToM(val[strsplits[1]])
		}
		xval = val.Set(strsplits[1], getresultobj(strsplits[1:], tval, tm))
	}

	return xval
	// if  {
	// 	val = tval
	// } else {
	// 	val = val.Set(k, v)
	// 	if val == nil {

	// 	} else {

	// 	}

	// 	val = getresultobj(strsplits[1:], tval)
	// }

	// return val
}
Beispiel #9
0
func saverechistory(key string, dt toolkit.M) (err error) {
	err = nil
	fullfilename := filepath.Join(toolkit.ToString(histConf.Get("recpath", "")), mapRecHistory[key])
	if EC_DATA_PATH != "" {
		fullfilename = filepath.Join(EC_DATA_PATH, "datagrabber", "historyrec", mapRecHistory[key])
	}
	// fmt.Println(fullfilename, " - Key - ", key, " - filename - ", mapRecHistory)
	cconfig := toolkit.M{"newfile": true, "useheader": true, "delimiter": ","}
	conn, err := prepareconnection("csv", fullfilename, "", "", "", cconfig)
	if err != nil {
		return
	}

	q := conn.NewQuery().SetConfig("multiexec", true).Insert()
	for k, v := range dt {
		if toolkit.TypeName(v) == "toolkit.M" {
			dt.Set(k, fmt.Sprintf("%v", v))
		}
	}

	err = q.Exec(toolkit.M{}.Set("data", dt))
	conn.Close()

	return
}
Beispiel #10
0
func (q *Query) generateIndex(filters []*dbox.Filter) (output []int, e error) {
	var n int = 0
	for {
		tdread, e := q.reader.Read()
		if e != nil && e != io.EOF {
			break
		}
		n++

		tm := toolkit.M{}

		for i, v := range tdread {
			tolower := strings.ToLower(q.headerColumn[i].name)
			tm.Set(tolower, v)
			if q.headerColumn[i].dataType == "int" {
				tm[tolower] = cast.ToInt(v, cast.RoundingAuto)
			} else if q.headerColumn[i].dataType == "float" {
				tm[tolower] = cast.ToF64(v, (len(v) - (strings.IndexAny(v, "."))), cast.RoundingAuto)
			}
		}

		match := dbox.MatchM(tm, filters)
		if (len(filters) == 0 || match) && len(tm) > 0 {
			output = append(output, n)
		}

		if e == io.EOF {
			break
		}
	}

	e = q.resetReader()
	return
}
func (s *ScenarioSimulation) Initiate(k *knot.WebContext) interface{} {
	k.Config.OutputType = knot.OutputJson
	//csr, e := s.DB().Find(new(PlantModel), tk.M{}.Set("skip", 0).Set("limit", 0))
	csr, e := s.DB().Connection.NewQuery().Select("Plant").From("MasterPlant").Cursor(nil)
	PlantList := make([]PlantModel, 0)
	e = csr.Fetch(&PlantList, 0, true)
	if e != nil {
		return e.Error()
	}

	//csr, e = s.DB().Find(new(UnitModel), tk.M{}.Set("skip", 0).Set("limit", 0))
	csr, e = s.DB().Connection.NewQuery().Select("Unit").From("MasterUnit").Cursor(nil)
	UnitList := make([]UnitModel, 0)
	e = csr.Fetch(&UnitList, 0, true)
	if e != nil {
		return e.Error()
	}

	defer csr.Close()

	result := tk.M{}
	result.Set("PlantList", PlantList)
	result.Set("UnitList", UnitList)
	return ResultInfo(result, e)
}
Beispiel #12
0
func (p *Page) SaveNewWidget(payload toolkit.M, widgetPath string) (*WidgetPage, error) {
	wp := new(WidgetPage)
	wp.ID = payload.Get("widgetPageId", "").(string)
	wp.WidgetID = payload.Get("widgetId", "").(string)
	widget := new(Widget)
	widget.ID = wp.WidgetID
	widget.GetById()
	wp.ConfigDefault = widget.Config

	extractDest := filepath.Join(widgetPath, widget.ID)
	path, err := GetWidgetPath(extractDest)
	if path == "" {
		return nil, errors.New("directory doesn't contains index.html")
	}
	if err != nil {
		return nil, err
	}
	getConfigFile := filepath.Join(path, "config-widget.json")
	result, err := GetJsonFile(getConfigFile)
	if err != nil {
		return nil, err
	}
	if result != nil { /*going to select dataSources field only from config-widget.json*/
		for _, value := range result[0].Get("dataSources").([]interface{}) {
			wp.DataSources = append(wp.DataSources, value.(map[string]interface{}))
		}
	}
	return wp, nil
}
Beispiel #13
0
func ReadVariable(f *dbox.Filter, in toolkit.M) *dbox.Filter {
	f.Field = strings.ToLower(f.Field)
	if (f.Op == "$and" || f.Op == "$or") && strings.Contains(reflect.TypeOf(f.Value).String(), "dbox.Filter") {
		fs := f.Value.([]*dbox.Filter)
		for i, ff := range fs {
			bf := ReadVariable(ff, in)
			fs[i] = bf
		}
		f.Value = fs
	} else {
		if reflect.TypeOf(f.Value).Kind() == reflect.Slice {
			fSlice := f.Value.([]interface{})
			// nilai fSlice : [@name1 @name2]
			for i := 0; i < len(fSlice); i++ {
				// nilai fSlice [i] : @name1
				if len(cast.ToString(f.Value)) > 0 && string(cast.ToString(fSlice[i])[0]) == "@" {
					fSlice[i] = in.Get(cast.ToString(fSlice[i]), "")
				}
			}
			f.Value = fSlice
		} else if len(cast.ToString(f.Value)) > 0 && string(cast.ToString(f.Value)[0]) == "@" {
			f.Value = in.Get(cast.ToString(f.Value), "")
		}
	}
	return f
}
Beispiel #14
0
func extractDataBulk(attrList []string, data toolkit.M, driverName string) string {
	var values string
	if data != nil {
		for i, attr := range attrList {
			val := data.Get(attr)
			var datatypelist = []string{"map", "invalid", "struct", "slice"}
			var value reflect.Value
			if val != nil {
				value = reflect.Zero(reflect.TypeOf(val))
			}
			if toolkit.HasMember(datatypelist, value.Kind().String()) {
				continue
			}
			stringValues := StringValue(val, driverName)
			if i == 0 {
				values = "(" + stringValues

			} else {
				values += ", " + stringValues

			}
		}
		values += ")"
	}
	return values
}
Beispiel #15
0
func (c *Coordinator) UpdateMetadata(in toolkit.M) *toolkit.Result {
	result := toolkit.NewResult()
	keys := []string{}
	bs := in.Get("keys", []byte{}).([]byte)
	toolkit.FromBytes(bs, "gob", &keys)
	return result
}
Beispiel #16
0
func (g *GetDatabase) ResultFromDatabase(dataSettingId string, out interface{}) error {

	c, e := dbox.NewConnection(g.desttype, &g.ConnectionInfo)
	if e != nil {
		return e
	}

	e = c.Connect()
	if e != nil {
		return e
	}

	defer c.Close()

	iQ := c.NewQuery()
	if g.CollectionSettings[dataSettingId].Collection != "" {
		iQ.From(g.CollectionSettings[dataSettingId].Collection)
	}

	for _, val := range g.CollectionSettings[dataSettingId].MapsColumns {
		iQ.Select(val.Source)
	}

	if len(g.CollectionSettings[dataSettingId].FilterCond) > 0 {
		iQ.Where(g.CollectionSettings[dataSettingId].filterDbox)
	}

	csr, e := iQ.Cursor(nil)

	if e != nil {
		return e
	}
	if csr == nil {
		return e
	}
	defer csr.Close()

	results := make([]toolkit.M, 0)
	e = csr.Fetch(&results, 0, false)
	if e != nil {
		return e
	}

	ms := []toolkit.M{}
	for _, val := range results {
		m := toolkit.M{}
		for _, column := range g.CollectionSettings[dataSettingId].MapsColumns {
			m.Set(column.Source, "")
			if val.Has(column.Destination) {
				m.Set(column.Source, val[column.Destination])
			}
		}
		ms = append(ms, m)
	}

	if edecode := toolkit.Unjson(toolkit.Jsonify(ms), out); edecode != nil {
		return edecode
	}
	return nil
}
Beispiel #17
0
func (p *PageController) LoadWidgetPageData(r *knot.WebContext) interface{} {
	r.Config.OutputType = knot.OutputJson

	payload := []toolkit.M{}

	if err := r.GetPayload(&payload); err != nil {
		return helper.CreateResult(false, nil, err.Error())
	}

	result := toolkit.M{}

	for _, each := range payload {
		filter := each.GetString("filter")
		namespace := each.GetString("namespace")
		fields := strings.Split(each.Get("fields").(string), ",")
		dsID := each.GetString("value")

		opt := toolkit.M{"fields": fields, "value": filter}
		data, err := helper.FetchDataFromDSWithFilter(dsID, 0, opt)
		if err != nil {
			return helper.CreateResult(false, nil, err.Error())
		}

		result.Set(namespace, data)
	}

	return helper.CreateResult(true, result, "")
}
Beispiel #18
0
func (c *Cursor) Fetch(result interface{}) (bool, error) {
	if !c.rows.Next() {
		return false, nil
	}

	e := c.rows.Scan(c.rowMemory...)

	if e != nil {
		return false, createError("Fetch", e.Error())
	}

	rowData := toolkit.M{}

	for i, each := range c.rowDataRaw {
		value := "NULL"

		if each != nil {
			value = string(each)
		}

		rowData.Set(c.columns[i], value)
	}

	*(result.(*toolkit.M)) = rowData

	return true, nil
}
Beispiel #19
0
func (c *Coordinator) Get(in toolkit.M) *toolkit.Result {
	result := toolkit.NewResult()
	result.SetErrorTxt("Get command is still under development")
	key := in.GetString("key")
	owner, table, datakey := ParseKey(key)
	key = MakeKey(owner, table, datakey)
	return result
}
Beispiel #20
0
func (a *ConfigurationController) Default(k *knot.WebContext) interface{} {
	k.Config.OutputType = knot.OutputTemplate
	data := tk.M{}
	d, _ := os.Getwd()
	d = strings.Replace(strings.Replace(d, "\\cli", "", -1), "/cli", "", -1)
	data.Set("data_dir", d+tk.PathSeparator+filepath.Join("data", "Output")+tk.PathSeparator)
	data.Set("log_dir", d+tk.PathSeparator+filepath.Join("data", "Log")+tk.PathSeparator)
	return data
}
Beispiel #21
0
func (a *controller) Hi(in toolkit.M) *toolkit.Result {
	r := toolkit.NewResult()
	name := in.GetString("name")
	r.SetBytes(struct {
		HelloMessage string
		TimeNow      time.Time
		Scores       []Score
	}{"Hello " + name, time.Now(), []Score{{"Bahasa Indonesia", 90}, {"Math", 85}}}, "gob")
	return r
}
Beispiel #22
0
func ACL() {
	var driver, host, db, user, pass string

	fmt.Println("Setup ACL database ==============")

	fmt.Print("  driver (mongo/json/csv/mysql) : ")
	fmt.Scanln(&driver)

	fmt.Print("  host (& port) : ")
	fmt.Scanln(&host)

	fmt.Print("  database name : ")
	fmt.Scanln(&db)

	fmt.Print("  username : "******"  password : "******"driver", driver)
	config.Set("host", host)
	config.Set("db", db)
	config.Set("user", user)
	config.Set("pass", pass)

	fmt.Println("ACL Configuration saved!")
	colonycore.SetConfig(colonycore.CONF_DB_ACL, config)
}
Beispiel #23
0
func (l *LoginController) ProcessLogin(r *knot.WebContext) interface{} {
	r.Config.OutputType = knot.OutputJson

	payload := toolkit.M{}
	err := r.GetPayload(&payload)

	switch {
	case err != nil:
		return helper.CreateResult(false, nil, err.Error())
	case !payload.Has("username") || !payload.Has("password"):
		return helper.CreateResult(false, nil, "username or password not found")
	case payload.Has("username") && len(toolkit.ToString(payload["username"])) == 0:
		return helper.CreateResult(false, nil, "username cannot empty")
	case payload.Has("password") && len(toolkit.ToString(payload["password"])) == 0:
		return helper.CreateResult(false, nil, "password cannot empty")
	}

	sessid, err := acl.Login(toolkit.ToString(payload["username"]), toolkit.ToString(payload["password"]))
	if err != nil {
		return helper.CreateResult(true, "", err.Error())
	}
	r.SetSession("sessionid", sessid)
	return helper.CreateResult(true, toolkit.M{}.Set("status", true), "Login Success")

}
Beispiel #24
0
func (q *Query) Exec(parm toolkit.M) (e error) {
	data := parm.Get("data")
	driverName := q.GetDriverDB()

	if toolkit.IsSlice(data) && driverName == "mssql" {
		e = q.insertBulk(parm)
	} else {
		_, e = q.ExecOut(parm)
	}
	return e
}
Beispiel #25
0
func (a *SessionController) GetSession(r *knot.WebContext) interface{} {
	var filter *dbox.Filter
	r.Config.OutputType = knot.OutputJson
	_ = a.InitialSetDatabase()

	payload := map[string]interface{}{}
	err := r.GetForms(&payload)
	if err != nil {
		return helper.CreateResult(false, nil, err.Error())
	}
	if strings.Contains(toolkit.TypeName(payload["find"]), "float") {
		payload["find"] = toolkit.ToInt(payload["find"], toolkit.RoundingAuto)
	}

	tSession := new(acl.Session)
	if find := toolkit.ToString(payload["find"]); find != "" {
		filter = new(dbox.Filter)
		filter = dbox.Contains("loginid", find)
	}
	take := toolkit.ToInt(payload["take"], toolkit.RoundingAuto)
	skip := toolkit.ToInt(payload["skip"], toolkit.RoundingAuto)

	// c, err := acl.Find(tAccess, filter, toolkit.M{}.Set("take", take).Set("skip", skip))
	// c, err := acl.Find(tSession, nil, toolkit.M{}.Set("take", payload["take"].(int)).Set("skip", payload["skip"].(int)))
	c, err := acl.Find(tSession, filter, toolkit.M{}.Set("take", take).Set("skip", skip))
	if err != nil {
		return helper.CreateResult(true, nil, err.Error())
	}

	data := toolkit.M{}
	arrm := make([]toolkit.M, 0, 0)
	err = c.Fetch(&arrm, 0, false)
	for i, val := range arrm {
		arrm[i].Set("duration", time.Since(val["created"].(time.Time)).Hours())
		arrm[i].Set("status", "ACTIVE")
		if val["expired"].(time.Time).Before(time.Now().UTC()) {
			arrm[i].Set("duration", val["expired"].(time.Time).Sub(val["created"].(time.Time)).Hours())
			arrm[i].Set("status", "EXPIRED")
		}
	}
	c.Close()

	c, err = acl.Find(tSession, filter, nil)

	data.Set("Datas", arrm)
	data.Set("total", c.Count())

	if err != nil {
		return helper.CreateResult(true, nil, err.Error())
	} else {
		return helper.CreateResult(true, data, "")
	}

}
Beispiel #26
0
func removeDuplicatesUnordered(elements toolkit.M, key []string) []string {
	for _, k := range key {
		elements.Unset(k)
	}

	result := []string{}
	for key, _ := range elements {
		result = append(result, key)
	}
	return result
}
Beispiel #27
0
func populateParmValue(inputM *toolkit.M, parms toolkit.M) {
	in := *inputM
	for k, _ := range in {
		if parms.Has(k) {
			in[k] = parms[k]
		} else {
			in[k] = ""
		}
	}
	*inputM = in
}
Beispiel #28
0
func generateWhereCondition(strwhere string) (oprstr string, sstr []string) {

	oprstr = "or"
	r := regexp.MustCompile(`^(?P<lastprocess01>(.*))(?P<firstprocess>(\(.*([Aa][Nn][Dd]|[Oo][Rr]).*\)))(?P<lastprocess02>(.*))$`)
	// ror := regexp.MustCompile(`(.*) (?P<oprandor>([Oo][Rr])) (.*)`)
	// rand := regexp.MustCompile(`(.*) (?P<oprandor>([Aa][Nn][Dd])) (.*)`)
	// if !r.MatchString(strwhere) {
	// 	r = ror
	// }

	// if !r.MatchString(strwhere) {
	// 	r = rand
	// }

	// tempalias := make(toolkit.M, 0, 0)
	tempalias := toolkit.M{}
	for r.MatchString(strwhere) {
		condpart := toolkit.M{}
		temparray := r.FindStringSubmatch(strwhere)

		for i, val := range r.SubexpNames() {
			if val != "" && temparray[i] != "" {
				condpart.Set(val, temparray[i])
			}
		}

		straliaskey := "@" + toolkit.GenerateRandomString("1234567890", 10)
		strwhere = strings.Replace(strwhere, condpart["firstprocess"].(string), straliaskey, -1)
		tempalias.Set(straliaskey, condpart["firstprocess"])
	}

	r = regexp.MustCompile(`(.*) (?P<oprandor>([Oo][Rr])) (.*)`)
	if !r.MatchString(strwhere) {
		r = regexp.MustCompile(`(.*) (?P<oprandor>([Aa][Nn][Dd])) (.*)`)
	}

	condpart := toolkit.M{}
	temparray := r.FindStringSubmatch(strwhere)
	// toolkit.Printf("Connection 319 : %#v\n", temparray)
	for i, val := range r.SubexpNames() {
		if val != "" && temparray[i] != "" {
			condpart.Set(val, temparray[i])
		}
	}

	sstr = strings.Split(strwhere, condpart["oprandor"].(string))
	if strings.ToLower(condpart["oprandor"].(string)) == "and" {
		oprstr = "and"
	}

	for key, val := range tempalias {
		for i, strval := range sstr {
			sstr[i] = strings.Replace(strval, key, val.(string), -1)
		}
	}

	return
}
Beispiel #29
0
func (c *DashboardController) GetData(k *knot.WebContext) interface{} {
	k.Config.OutputType = knot.OutputJson

	d := struct {
		StartDate string
		EndDate   string
		Plant     []string
	}{}

	e := k.GetPayload(&d)

	type ReturnValue struct {
		PlantList         []PowerPlantCoordinates
		PlantCapacityList []tk.M
	}

	var (
		Result ReturnValue
	)

	filter := tk.M{}
	curr, e := c.DB().Find(&PowerPlantCoordinates{}, filter)

	if e != nil {
	}

	e = curr.Fetch(&Result.PlantList, 0, false)

	if e != nil {
		return e.Error()
	}

	defer curr.Close()

	//selectedPeriod := d.StartDate
	selectedPeriod := time.Now().Year() - 1

	cursor, _ := c.DB().Connection.NewQuery().
		Select("PlantCode as _id").
		From("ValueEquation_Dashboard").
		Where(dbox.Eq("Year", selectedPeriod)).
		Aggr(dbox.AggrSum, "InstalledCapacity", "TotalCapacity").
		Group("PlantCode").
		Cursor(nil)

	defer cursor.Close()
	e = cursor.Fetch(&Result.PlantCapacityList, 0, false)

	result := tk.M{}
	result.Set("success", true)
	result.Set("Data", Result)
	return ResultInfo(result, e)
}
Beispiel #30
0
func (a *SessionController) GetSession(r *knot.WebContext) interface{} {
	r.Config.OutputType = knot.OutputJson
	_ = a.InitialSetDatabase()

	// payload := map[string]interface{}{}
	// err := r.GetPayload(&payload)
	// if err != nil {
	// 	return helper.CreateResult(false, nil, err.Error())
	// }

	tSession := new(acl.Session)

	data := toolkit.M{}

	arrm := make([]toolkit.M, 0, 0)
	// c, err := acl.Find(tSession, nil, toolkit.M{}.Set("take", payload["take"].(int)).Set("skip", payload["skip"].(int)))
	c, err := acl.Find(tSession, nil, toolkit.M{}.Set("take", 10).Set("skip", 0))
	if err != nil {
		return helper.CreateResult(true, nil, err.Error())
	}

	err = c.Fetch(&arrm, 0, false)
	for i, val := range arrm {
		tUser := new(acl.User)
		e := acl.FindByID(tUser, toolkit.ToString(val.Get("userid", "")))
		if e != nil {
			continue
		}
		arrm[i].Set("username", tUser.LoginID)
		arrm[i].Set("duration", time.Since(val["created"].(time.Time)).Hours())
		arrm[i].Set("status", "ACTIVE")
		if val["expired"].(time.Time).Before(time.Now().UTC()) {
			arrm[i].Set("duration", val["expired"].(time.Time).Sub(val["created"].(time.Time)).Hours())
			arrm[i].Set("status", "EXPIRED")
		}
		arrm[i].Set("username", tUser.LoginID)
		// toolkit.Printf("Debug date : %v : %v\n", toolkit.TypeName(val["created"]), val["created"].(time.Time))
	}
	c.Close()

	c, err = acl.Find(tSession, nil, nil)

	data.Set("Datas", arrm)
	data.Set("total", c.Count())
	// data.Set("total", 100)

	if err != nil {
		return helper.CreateResult(true, nil, err.Error())
	} else {
		return helper.CreateResult(true, data, "")
	}

}