コード例 #1
0
func (s *ScenarioSimulation) GetData(k *knot.WebContext) interface{} {
	k.Config.OutputType = knot.OutputJson
	status := ""
	msg := ""
	res := []*ValueEquation{}

	payloads := struct {
		StartPeriod         string
		EndPeriod           string
		SelectedPlant       []string
		SelectedUnit        []string
		SelectedSimulation  string
		SelectedDescription string
	}{}

	e := k.GetPayload(&payloads)
	if e != nil {
		s.WriteLog(e)
	}

	start, _ := time.Parse(time.RFC3339, payloads.StartPeriod)
	end, _ := time.Parse(time.RFC3339, payloads.EndPeriod)

	query := []*dbox.Filter{}
	query = append(query, dbox.Gte("Dates", start))
	query = append(query, dbox.Lte("Dates", end))

	if payloads.SelectedPlant != nil && len(payloads.SelectedPlant) > 0 {
		query = append(query, dbox.In("Plant", payloads.SelectedPlant))
	}

	if payloads.SelectedUnit != nil && len(payloads.SelectedUnit) > 0 {
		query = append(query, dbox.In("Unit", payloads.SelectedUnit))
	}
	csr, err := s.DB().Connection.NewQuery().From("ValueEquation").Select("Plant", "AvgNetGeneration", "VOMR", "TotalOutageDuration", "TotalDuration", "OperatingCost", "Revenue", "TotalLabourCost", "TotalMaterialCost", "TotalServicesCost", "TotalFuelCost").Where(query...).Cursor(nil)
	if err != nil {
		msg = err.Error()
		status = "NOK"
	} else {
		status = "OK"
	}
	err = csr.Fetch(&res, 0, true)
	defer csr.Close()

	result := tk.M{}
	result.Set("Status", status)
	result.Set("Message", msg)
	result.Set("Data", res)

	return result
}
コード例 #2
0
ファイル: getdatabase.go プロジェクト: arfian/sedotan
func filterCondition(cond toolkit.M) *dbox.Filter {
	fb := new(dbox.Filter)

	for key, val := range cond {
		if key == "$and" || key == "$or" {
			afb := []*dbox.Filter{}
			for _, sVal := range val.([]interface{}) {
				rVal := sVal.(map[string]interface{})
				mVal := toolkit.M{}
				for rKey, mapVal := range rVal {
					mVal.Set(rKey, mapVal)
				}

				afb = append(afb, filterCondition(mVal))
			}

			if key == "$and" {
				fb = dbox.And(afb...)
			} else {
				fb = dbox.Or(afb...)
			}

		} else {
			if reflect.ValueOf(val).Kind() == reflect.Map {
				mVal := val.(map[string]interface{})
				tomVal, _ := toolkit.ToM(mVal)
				switch {
				case tomVal.Has("$eq"):
					fb = dbox.Eq(key, tomVal["$eq"].(string))
				case tomVal.Has("$ne"):
					fb = dbox.Ne(key, tomVal["$ne"].(string))
				case tomVal.Has("$regex"):
					fb = dbox.Contains(key, tomVal["$regex"].(string))
				case tomVal.Has("$gt"):
					fb = dbox.Gt(key, tomVal["$gt"].(string))
				case tomVal.Has("$gte"):
					fb = dbox.Gte(key, tomVal["$gte"].(string))
				case tomVal.Has("$lt"):
					fb = dbox.Lt(key, tomVal["$lt"].(string))
				case tomVal.Has("$lte"):
					fb = dbox.Lte(key, tomVal["$lte"].(string))
				}
			} else {
				fb = dbox.Eq(key, val)
			}
		}
	}

	return fb
}
コード例 #3
0
func (m *ValueEquationComparison) GetData(ctx *orm.DataContext, k *knot.WebContext) (interface{}, error) {
	m.SetPayLoad(k)
	type DataValue struct {
		Revenue         float64 `json:'Revenue'`
		MaintenanceCost float64 `json:'MaintenanceCost'`
		OperatingCost   float64 `json:'OperatingCost'`
		NetGeneration   float64 `json:'NetGeneration'`
	}
	result, Result := tk.M{}, []DataValue{}
	c := ctx.Connection
	ve := ValueEquation{}
	query := []*dbox.Filter{}
	query = append(query, dbox.Gte("Dates", m.StartPeriod))
	query = append(query, dbox.Lte("Dates", m.EndPeriod))
	if m.SelectedPlant != nil && len(m.SelectedPlant) > 0 {
		query = append(query, dbox.In("Plant", m.SelectedPlant))
	}
	if m.SelectedUnit != nil && len(m.SelectedUnit) > 0 {
		query = append(query, dbox.In("Unit", m.SelectedUnit))
	}
	if m.SelectedUnitGroup != "ALL" {
		query = append(query, dbox.In("UnitGroup", m.SelectedUnitGroup))
	}

	csr, e := c.NewQuery().
		Where(query...).
		Aggr(dbox.AggrSum, "Revenue", "Revenue").
		Aggr(dbox.AggrSum, "MaintenanceCost", "MaintenanceCost").
		Aggr(dbox.AggrSum, "OperatingCost", "OperatingCost").
		Aggr(dbox.AggrSum, "NetGeneration", "NetGeneration").
		From(ve.TableName()).Cursor(nil)
	e = csr.Fetch(&Result, 0, false)
	if e != nil {
		return nil, e
	}
	csr.Close()
	result.Set("Index", m.Index)
	result.Set("DataValue", Result)
	return result, nil
}
コード例 #4
0
ファイル: jsons_test.go プロジェクト: rizalsmarts/golang-dbox
func TestFind(t *testing.T) {
	ms := []toolkit.M{}
	for i := 1; i <= 10; i++ {
		m := toolkit.M{}
		m.Set("_id", i)
		m.Set("random", toolkit.RandInt(100))
		ms = append(ms, m)
	}
	toolkit.Printf("Original Value\n%s\n", toolkit.JsonString(ms))

	indexes := dbox.Find(ms, []*dbox.Filter{
		//dbox.Or(dbox.Lt("random", 20), dbox.And(dbox.Gte("random", 60), dbox.Lte("random", 70)))})
		dbox.And(dbox.Gte("random", 30), dbox.Lte("random", 80))})

	records := []toolkit.M{}
	for _, v := range indexes {
		records = append(records, ms[v])
	}
	for _, r := range records {
		toolkit.Printf("Record: %s \n", toolkit.JsonString(r))
	}
	toolkit.Printf("Find %d records of %d records\n", len(indexes), len(ms))
}
コード例 #5
0
ファイル: getdatabase.go プロジェクト: novalagung/sedotan
func filterCondition(cond toolkit.M) *dbox.Filter {
	fb := new(dbox.Filter)

	for key, val := range cond {
		if key == "$and" || key == "$or" {
			afb := []*dbox.Filter{}
			for _, sVal := range val.([]interface{}) {
				rVal := sVal.(map[string]interface{})
				mVal := toolkit.M{}
				for rKey, mapVal := range rVal {
					mVal.Set(rKey, mapVal)
				}

				afb = append(afb, filterCondition(mVal))
			}

			if key == "$and" {
				fb = dbox.And(afb...)
			} else {
				fb = dbox.Or(afb...)
			}

		} else {
			if toolkit.TypeName(val) == "map[string]interface {}" {
				mVal := val.(map[string]interface{})
				tomVal, _ := toolkit.ToM(mVal)
				switch {
				case tomVal.Has("$eq"):
					fb = dbox.Eq(key, tomVal["$eq"])
				case tomVal.Has("$ne"):
					fb = dbox.Ne(key, tomVal["$ne"])
				case tomVal.Has("$regex"):
					fb = dbox.Contains(key, toolkit.ToString(tomVal["$regex"]))
				case tomVal.Has("$gt"):
					fb = dbox.Gt(key, tomVal["$gt"])
				case tomVal.Has("$gte"):
					fb = dbox.Gte(key, tomVal["$gte"])
				case tomVal.Has("$lt"):
					fb = dbox.Lt(key, tomVal["$lt"])
				case tomVal.Has("$lte"):
					fb = dbox.Lte(key, tomVal["$lte"])
				case tomVal.Has("$in"):
					tval := make([]interface{}, 0, 0)
					if toolkit.TypeName(tomVal["$in"]) == "[]interface {}" {
						for _, tin := range tomVal["$in"].([]interface{}) {
							tval = append(tval, tin)
						}
					} else {
						tval = append(tval, tomVal["$in"])
					}

					fb = dbox.In(key, tval...)
				case tomVal.Has("$nin"):
					tval := make([]interface{}, 0, 0)
					if toolkit.TypeName(tomVal["$nin"]) == "[]interface {}" {
						for _, tin := range tomVal["$nin"].([]interface{}) {
							tval = append(tval, tin)
						}
					} else {
						tval = append(tval, tomVal["$nin"])
					}

					fb = dbox.Nin(key, tval...)
				}
			} else {
				fb = dbox.Eq(key, val)
			}
		}
	}

	return fb
}
コード例 #6
0
func (m *HistoricalValueEquation) GetSummaryData(ctx *orm.DataContext, k *knot.WebContext) (interface{}, error) {
	m.SetPayLoad(k)
	type DataValue struct {
		ID              string
		Plant           string  `json:'Plant'`
		Unit            string  `json:'Unit'`
		Revenue         float64 `json:'Revenue'`
		MaintenanceCost float64 `json:'MaintenanceCost'`
		OperatingCost   float64 `json:'OperatingCost'`
	}
	result, DataChart, DataDetail := tk.M{}, []DataValue{}, []*DataValue{}
	c := ctx.Connection
	ve := new(ValueEquation)
	query := []*dbox.Filter{}
	query = append(query, dbox.Gte("Dates", m.StartPeriod))
	query = append(query, dbox.Lte("Dates", m.EndPeriod))

	csr, e := c.NewQuery().
		Where(query...).
		Select("Plant").
		Aggr(dbox.AggrSum, "Revenue", "Revenue").
		Aggr(dbox.AggrSum, "MaintenanceCost", "MaintenanceCost").
		Aggr(dbox.AggrSum, "OperatingCost", "OperatingCost").
		From(ve.TableName()).Group("Plant").Order("Plant").Cursor(nil)
	if e != nil {
		return nil, e
	}

	if csr != nil {
		e = csr.Fetch(&DataChart, 0, false)
	}
	if e != nil {
		return nil, e
	}
	csr.Close()
	result.Set("DataChart", DataChart)

	groupBy := "Plant"
	if m.Scope == "Plant" {
		groupBy = "Unit"
		if m.Selected != nil && len(m.Selected) > 0 {
			query = append(query, dbox.In("Plant", m.Selected))
		}
	}

	if m.Scope != "Unit" {
		csr, e := c.NewQuery().
			Where(query...).Select(groupBy).
			Aggr(dbox.AggrSum, "Revenue", "Revenue").
			Aggr(dbox.AggrSum, "MaintenanceCost", "MaintenanceCost").
			Aggr(dbox.AggrSum, "OperatingCost", "OperatingCost").
			From(ve.TableName()).Group(groupBy).Order(groupBy).Cursor(nil)
		if csr != nil {
			e = csr.Fetch(&DataDetail, 0, false)
		}
		csr.Close()
		if e != nil {
			return nil, e
		}
		for _, i := range DataDetail {
			if i.Unit != "" {
				i.ID = i.Unit
			} else {
				i.ID = i.Plant
			}
		}
	}

	result.Set("DataDetail", DataDetail)
	return result, nil
}
コード例 #7
0
ファイル: mor.go プロジェクト: yanda15/powerplant
// generateMORFlatCalculationSummary
func (m *GenMOR) generateMORFlatCalculationSummary() error {
	ctx := m.BaseController.Ctx
	c := ctx.Connection
	var (
		query []*dbox.Filter
	)
	tk.Println("Generating MOR Flat Calculation Summary..")
	Years := []int{2013, 2014, 2015}

	query = []*dbox.Filter{}
	query = append(query, dbox.Gte("TopElement", "Maintenance"))

	MORSummaryList := []MORSummary{}
	csr, e := c.NewQuery().Select("Element").From(new(MORSummary).TableName()).Where(query...).Group("Element").Cursor(nil)

	if e != nil {
		return e
	}

	e = csr.Fetch(&MORSummaryList, 0, false)
	if e != nil {
		return e
	}
	csr.Close()

	for _, year := range Years {
		query = []*dbox.Filter{}
		query = append(query, dbox.Gte("Period", time.Date(year, 1, 1, 0, 0, 0, 0, time.UTC)))
		query = append(query, dbox.Lt("Period", time.Date((year+1), 1, 1, 0, 0, 0, 0, time.UTC)))

		MaintenanceCostList := []MaintenanceCost{}
		csr, e := c.NewQuery().From(new(MaintenanceCost).TableName()).Where(query...).Cursor(nil)

		if e != nil {
			return e
		}

		e = csr.Fetch(&MaintenanceCostList, 0, false)
		if e != nil {
			return e
		}
		csr.Close()

		Plants := crowd.From(&MaintenanceCostList).Group(func(x interface{}) interface{} {
			return x.(MaintenanceCost).Plant
		}, nil).Exec().Result.Data().([]crowd.KV)

		for _, p := range Plants {
			plant := p.Key.(string)
			EqType := crowd.From(&MaintenanceCostList).Where(func(x interface{}) interface{} {
				return x.(MaintenanceCost).Plant == plant
			}).Group(func(x interface{}) interface{} {
				return x.(MaintenanceCost).EquipmentType
			}, nil).Exec().Result.Data().([]crowd.KV)

			for _, eqt := range EqType {
				eq := eqt.Key.(string)
				ActType := crowd.From(&MaintenanceCostList).Where(func(x interface{}) interface{} {
					o := x.(MaintenanceCost)
					return o.Plant == plant && o.EquipmentType == eq
				}).Group(func(x interface{}) interface{} {
					return x.(MaintenanceCost).MaintenanceActivityType
				}, nil).Exec().Result.Data().([]crowd.KV)

				for _, a := range ActType {
					act := a.Key.(string)
					OrderType := crowd.From(&MaintenanceCostList).Where(func(x interface{}) interface{} {
						o := x.(MaintenanceCost)
						return o.Plant == plant && o.EquipmentType == eq && o.MaintenanceActivityType == act
					}).Group(func(x interface{}) interface{} {
						return x.(MaintenanceCost).OrderType
					}, nil).Exec().Result.Data().([]crowd.KV)

					for _, o := range OrderType {
						order := o.Key.(string)
						for _, mor := range MORSummaryList {
							d := new(MORCalculationFlatSummary)
							d.PeriodYear = year
							d.OrderType = order
							if len(eq) == 1 {
								d.EquipmentType = "Other"
							} else {
								d.EquipmentType = eq
							}
							if len(eq) == 1 {
								d.EquipmentTypeDescription = "Other"
							} else {
								EqTypeDesc := crowd.From(&MaintenanceCostList).Where(func(x interface{}) interface{} {
									o := x.(MaintenanceCost)
									return o.Plant == plant && o.EquipmentType == eq
								}).Exec().Result.Data().([]MaintenanceCost)
								if len(EqTypeDesc) > 0 {
									d.EquipmentTypeDescription = EqTypeDesc[0].EquipmentTypeDesc
								}
							}

							d.ActivityType = act
							d.Plant = PlantNormalization(plant)
							d.Element = mor.Element
							d.MOCount = len(OrderType)

							switch d.Element {
							case "Internal Labor":
								d.Value = crowd.From(&MaintenanceCostList).Where(func(x interface{}) interface{} {
									o := x.(MaintenanceCost)
									return o.Plant == plant && o.EquipmentType == eq && o.MaintenanceActivityType == act
								}).Sum(func(x interface{}) interface{} {
									return x.(MaintenanceCost).InternalLaborActual
								}).Exec().Result.Sum
								break
							case "Internal Material":
								d.Value = crowd.From(&MaintenanceCostList).Where(func(x interface{}) interface{} {
									o := x.(MaintenanceCost)
									return o.Plant == plant && o.EquipmentType == eq && o.MaintenanceActivityType == act
								}).Sum(func(x interface{}) interface{} {
									return x.(MaintenanceCost).InternalMaterialActual
								}).Exec().Result.Sum
								break
							case "Direct Material":
								d.Value = crowd.From(&MaintenanceCostList).Where(func(x interface{}) interface{} {
									o := x.(MaintenanceCost)
									return o.Plant == plant && o.EquipmentType == eq && o.MaintenanceActivityType == act
								}).Sum(func(x interface{}) interface{} {
									return x.(MaintenanceCost).DirectMaterialActual
								}).Exec().Result.Sum
								break
							case "External Service":
								d.Value = crowd.From(&MaintenanceCostList).Where(func(x interface{}) interface{} {
									o := x.(MaintenanceCost)
									return o.Plant == plant && o.EquipmentType == eq && o.MaintenanceActivityType == act
								}).Sum(func(x interface{}) interface{} {
									return x.(MaintenanceCost).ExternalServiceActual
								}).Exec().Result.Sum
								break
							default:
								break
							}

							_, e := ctx.InsertOut(d)
							if e != nil {
								tk.Println(e)
								break
							}

						}
					}

				}
			}
		}

	}
	tk.Println(len(MORSummaryList))
	return nil
}
コード例 #8
0
func (d *DataSourceController) filterParse(where toolkit.M) *dbox.Filter {
	field := where.Get("field", "").(string)
	value := fmt.Sprintf("%v", where["value"])

	if key := where.Get("key", "").(string); key == "Eq" {
		valueInt, errv := strconv.Atoi(fmt.Sprintf("%v", where["value"]))
		if errv == nil {
			return dbox.Eq(field, valueInt)
		} else {
			return dbox.Eq(field, value)
		}
	} else if key == "Ne" {
		valueInt, errv := strconv.Atoi(fmt.Sprintf("%v", where["value"]))
		if errv == nil {
			return dbox.Ne(field, valueInt)
		} else {
			return dbox.Ne(field, value)
		}
	} else if key == "Lt" {
		valueInt, errv := strconv.Atoi(fmt.Sprintf("%v", where["value"]))
		if errv == nil {
			return dbox.Lt(field, valueInt)
		} else {
			return dbox.Lt(field, value)
		}
	} else if key == "Lte" {
		valueInt, errv := strconv.Atoi(fmt.Sprintf("%v", where["value"]))
		if errv == nil {
			return dbox.Lte(field, valueInt)
		} else {
			return dbox.Lte(field, value)
		}
	} else if key == "Gt" {
		valueInt, errv := strconv.Atoi(fmt.Sprintf("%v", where["value"]))
		if errv == nil {
			return dbox.Gt(field, valueInt)
		} else {
			return dbox.Gt(field, value)
		}
	} else if key == "Gte" {
		valueInt, errv := strconv.Atoi(fmt.Sprintf("%v", where["value"]))
		if errv == nil {
			return dbox.Gte(field, valueInt)
		} else {
			return dbox.Gte(field, value)
		}
	} else if key == "In" {
		valueArray := []interface{}{}
		for _, e := range strings.Split(value, ",") {
			valueArray = append(valueArray, strings.Trim(e, ""))
		}
		return dbox.In(field, valueArray...)
	} else if key == "Nin" {
		valueArray := []interface{}{}
		for _, e := range strings.Split(value, ",") {
			valueArray = append(valueArray, strings.Trim(e, ""))
		}
		return dbox.Nin(field, valueArray...)
	} else if key == "Contains" {
		return dbox.Contains(field, value)
	} else if key == "Or" {
		subs := where.Get("value", []interface{}{}).([]interface{})
		filtersToMerge := []*dbox.Filter{}
		for _, eachSub := range subs {
			eachWhere, _ := toolkit.ToM(eachSub)
			filtersToMerge = append(filtersToMerge, d.filterParse(eachWhere))
		}
		return dbox.Or(filtersToMerge...)
	} else if key == "And" {
		subs := where.Get("value", []interface{}{}).([]interface{})
		filtersToMerge := []*dbox.Filter{}
		for _, eachSub := range subs {
			eachWhere, _ := toolkit.ToM(eachSub)
			filtersToMerge = append(filtersToMerge, d.filterParse(eachWhere))
		}
		return dbox.And(filtersToMerge...)
	}

	return nil
}
コード例 #9
0
func (m *HistoricalValueEquation) GetDataQuality(ctx *orm.DataContext, k *knot.WebContext) (interface{}, error) {
	type DataValue struct {
		ID                       string
		Plant                    string  `json:'Plant'`
		Unit                     string  `json:'Unit'`
		Count                    float64 `json:'Count'`
		CapacityPayment_Data     float64 `json:'CapacityPayment_Data'`
		EnergyPayment_Data       float64 `json:'EnergyPayment_Data'`
		StartupPayment_Data      float64 `json:'StartupPayment_Data'`
		Penalty_Data             float64 `json:'Penalty_Data'`
		Incentive_Data           float64 `json:'Incentive_Data'`
		MaintenanceCost_Data     float64 `json:'MaintenanceCost_Data'`
		MaintenanceDuration_Data float64 `json:'MaintenanceDuration_Data'`
		PrimaryFuel1st_Data      float64 `json:'PrimaryFuel1st_Data'`
		PrimaryFuel2nd_Data      float64 `json:'PrimaryFuel2nd_Data'`
		BackupFuel_Data          float64 `json:'BackupFuel_Data'`
		FuelTransport_Data       float64 `json:'FuelTransport_Data'`
	}

	m.SetPayLoad(k)
	var e error = nil
	result := []*DataValue{}
	c := ctx.Connection
	vedq := ValueEquationDataQuality{}
	query := []*dbox.Filter{}
	query = append(query, dbox.Gte("Dates", m.StartPeriod))
	query = append(query, dbox.Lte("Dates", m.EndPeriod))
	groupBy := "Plant"
	switch m.Scope {
	case "Kingdom":
		break
	case "Plant":
		if m.Selected != nil && len(m.Selected) > 0 {
			query = append(query, dbox.In("Plant", m.Selected))
		}
		groupBy = "Unit"
		break
	case "Phase":
		if m.Selected != nil && len(m.Selected) > 0 {
			query = append(query, dbox.In("Phase", m.Selected))
		}
		break
	case "Unit":
		query = append(query, dbox.Eq("Plant", m.SelectedPlant))
		if m.Selected != nil && len(m.Selected) > 0 {
			query = append(query, dbox.In("Unit", m.Selected))
		}
		groupBy = "Unit"
		break
	default:
		break
	}

	if m.Scope == "Unit" || (m.Scope == "Plant" && m.Selected != nil && len(m.Selected) == 1) {
		query := []*dbox.Filter{}
		query = append(query, dbox.Gte("Dates", m.StartPeriod))
		query = append(query, dbox.Lte("Dates", m.EndPeriod))
		if m.Scope == "Unit" {
			query = append(query, dbox.Eq("Plant", m.SelectedPlant))
			if m.Selected != nil && len(m.Selected) > 0 {
				query = append(query, dbox.In("Unit", m.Selected))
			}
		} else {
			query = append(query, dbox.Eq("Plant", m.Selected[0]))
		}
		temp := []*ValueEquationDataQuality{}
		csr, e := ctx.Find(new(ValueEquationDataQuality), tk.M{}.Set("where", dbox.And(query...)))
		if csr != nil {
			e = csr.Fetch(&temp, 0, false)
		}
		csr.Close()
		if e != nil {
			return nil, e
		} else {
			m.GetValueEquationDocument(ctx, temp)
			return temp, e
		}
	} else {
		csr, e := c.NewQuery().
			Where(query...).Select(groupBy).
			Aggr(dbox.AggrSum, "1", "Count").
			Aggr(dbox.AggrSum, "CapacityPayment_Data", "CapacityPayment_Data").
			Aggr(dbox.AggrSum, "EnergyPayment_Data", "EnergyPayment_Data").
			Aggr(dbox.AggrSum, "StartupPayment_Data", "StartupPayment_Data").
			Aggr(dbox.AggrSum, "Penalty_Data", "Penalty_Data").
			Aggr(dbox.AggrSum, "Incentive_Data", "Incentive_Data").
			Aggr(dbox.AggrSum, "MaintenanceCost_Data", "MaintenanceCost_Data").
			Aggr(dbox.AggrSum, "MaintenanceDuration_Data", "MaintenanceDuration_Data").
			Aggr(dbox.AggrSum, "PrimaryFuel1st_Data", "PrimaryFuel1st_Data").
			Aggr(dbox.AggrSum, "PrimaryFuel2nd_Data", "PrimaryFuel2nd_Data").
			Aggr(dbox.AggrSum, "BackupFuel_Data", "BackupFuel_Data").
			Aggr(dbox.AggrSum, "FuelTransport_Data", "FuelTransport_Data").
			From(vedq.TableName()).Group(groupBy).Order(groupBy).Cursor(nil)
		if csr != nil {
			e = csr.Fetch(&result, 0, false)
		}
		csr.Close()
		if e != nil {
			return nil, e
		}
		for _, i := range result {
			if i.Unit != "" {
				i.ID = i.Unit
			} else {
				i.ID = i.Plant
			}
		}
	}
	return result, e
}
コード例 #10
0
func (m *HistoricalValueEquation) GetRevenueData(ctx *orm.DataContext, k *knot.WebContext) (interface{}, error) {
	type DataValue struct {
		ID              string
		Plant           string  `json:'Plant'`
		Unit            string  `json:'Unit'`
		CapacityPayment float64 `json:'CapacityPayment'`
		EnergyPayment   float64 `json:'EnergyPayment'`
		StartupPayment  float64 `json:'StartupPayment'`
		PenaltyAmount   float64 `json:'PenaltyAmount'`
		Incentive       float64 `json:'Incentive'`
		Revenue         float64 `json:'Revenue'`
	}

	m.SetPayLoad(k)
	result, DataChartRevenue, DataChartRevenueEx := tk.M{}, []*DataValue{}, []*DataValue{}
	c := ctx.Connection
	ve := ValueEquation{}
	query := []*dbox.Filter{}
	query = append(query, dbox.Gte("Dates", m.StartPeriod))
	query = append(query, dbox.Lte("Dates", m.EndPeriod))
	groupBy := "Plant"
	switch m.Scope {
	case "Kingdom":
		break
	case "Plant":
		if m.Selected != nil && len(m.Selected) > 0 {
			query = append(query, dbox.In("Plant", m.Selected))
		}
		groupBy = "Unit"
		break
	case "Phase":
		if m.Selected != nil && len(m.Selected) > 0 {
			query = append(query, dbox.In("Phase", m.Selected))
		}
		break
	case "Unit":
		query = append(query, dbox.Eq("Plant", m.SelectedPlant))
		if m.Selected != nil && len(m.Selected) > 0 {
			query = append(query, dbox.In("Unit", m.Selected))
		}
		groupBy = "Unit"
		break
	default:
		break
	}

	csr, e := c.NewQuery().
		Where(query...).
		Aggr(dbox.AggrSum, "CapacityPayment", "CapacityPayment").
		Aggr(dbox.AggrSum, "EnergyPayment", "EnergyPayment").
		Aggr(dbox.AggrSum, "StartupPayment", "StartupPayment").
		Aggr(dbox.AggrSum, "PenaltyAmount", "PenaltyAmount").
		Aggr(dbox.AggrSum, "Incentive", "Incentive").
		Aggr(dbox.AggrSum, "Revenue", "Revenue").
		From(ve.TableName()).Cursor(nil)
	if csr != nil {
		e = csr.Fetch(&DataChartRevenue, 0, false)
	}
	csr.Close()
	if e != nil {
		return nil, e
	}
	csr, e = c.NewQuery().
		Where(query...).Select(groupBy).
		Aggr(dbox.AggrSum, "CapacityPayment", "CapacityPayment").
		Aggr(dbox.AggrSum, "EnergyPayment", "EnergyPayment").
		Aggr(dbox.AggrSum, "StartupPayment", "StartupPayment").
		Aggr(dbox.AggrSum, "PenaltyAmount", "PenaltyAmount").
		Aggr(dbox.AggrSum, "Incentive", "Incentive").
		Aggr(dbox.AggrSum, "Revenue", "Revenue").
		From(ve.TableName()).Group(groupBy).Order(groupBy).Cursor(nil)
	if csr != nil {
		e = csr.Fetch(&DataChartRevenueEx, 0, false)
	}
	csr.Close()
	if e != nil {
		return nil, e
	}
	for _, i := range DataChartRevenueEx {
		if i.Unit != "" {
			i.ID = i.Unit
		} else {
			i.ID = i.Plant
		}
	}
	return result.Set("DataChartRevenue", DataChartRevenue).Set("DataChartRevenueEx", DataChartRevenueEx), e
}
コード例 #11
0
func (m *HistoricalValueEquation) GetOperatingData(ctx *orm.DataContext, k *knot.WebContext) (interface{}, error) {
	type DataValue struct {
		ID                string
		Plant             string  `json:'Plant'`
		Unit              string  `json:'Unit'`
		OperatingCost     float64 `json:'OperatingCost'`
		FuelTransportCost float64 `json:'FuelTransportCost'`
		Capacity          float64 `json:'Capacity'`
		NetGeneration     float64 `json:'NetGeneration'`
	}

	type DataTableType struct {
		IsPrimaryFuel         bool    `json:'IsPrimaryFuel'`
		FuelType              string  `json:'FuelType'`
		ConvertedFuelConsumed float64 `json:'ConvertedFuelConsumed'`
		FuelCostPerUnit       float64 `json:'FuelCostPerUnit'`
		FuelCost              float64 `json:'FuelCost'`
	}

	m.SetPayLoad(k)
	result, DataChart, DataTable, DataTotal, DataDetail := tk.M{}, []tk.M{}, []*DataTableType{}, []*DataValue{}, []*DataValue{}
	c := ctx.Connection
	ve := ValueEquation{}
	query := []*dbox.Filter{}
	query = append(query, dbox.Gte("Dates", m.StartPeriod))
	query = append(query, dbox.Lte("Dates", m.EndPeriod))
	groupBy := "Plant"
	switch m.Scope {
	case "Kingdom":
		break
	case "Plant":
		if m.Selected != nil && len(m.Selected) > 0 {
			query = append(query, dbox.In("Plant", m.Selected))
		}
		groupBy = "Unit"
		break
	case "Phase":
		if m.Selected != nil && len(m.Selected) > 0 {
			query = append(query, dbox.In("Phase", m.Selected))
		}
		break
	case "Unit":
		query = append(query, dbox.Eq("Plant", m.SelectedPlant))
		if m.Selected != nil && len(m.Selected) > 0 {
			query = append(query, dbox.In("Unit", m.Selected))
		}
		groupBy = "Unit"
		break
	default:
		break
	}

	// Getting "DataTable" - skip, need $unwind [ $Fuel ]
	tempValueEquation := []ValueEquation{}
	csr, e := c.NewQuery().
		Where(query...).Select("Id").
		From(ve.TableName()).Cursor(nil)
	if csr != nil {
		e = csr.Fetch(&tempValueEquation, 0, false)
	}
	csr.Close()
	VEId := []interface{}{}
	for _, i := range tempValueEquation {
		VEId = append(VEId, i.Id)
	}

	csr, e = c.NewQuery().
		Where(query...).
		Aggr(dbox.AggrSum, "OperatingCost", "OperatingCost").
		Aggr(dbox.AggrSum, "FuelTransportCost", "FuelTransportCost").
		From(ve.TableName()).Cursor(nil)
	if csr != nil {
		e = csr.Fetch(&DataTotal, 0, false)
	}
	csr.Close()
	if e != nil {
		return nil, e
	}

	if m.Scope != "Unit" {
		csr, e = c.NewQuery().
			Where(query...).Select(groupBy).
			Aggr(dbox.AggrSum, "Capacity", "Capacity").
			Aggr(dbox.AggrSum, "NetGeneration", "NetGeneration").
			Aggr(dbox.AggrSum, "OperatingCost", "OperatingCost").
			From(ve.TableName()).Group(groupBy).Order(groupBy).Cursor(nil)
		if csr != nil {
			e = csr.Fetch(&DataDetail, 0, false)
		}
		csr.Close()
		if e != nil {
			return nil, e
		}
		for _, i := range DataDetail {
			if i.Unit != "" {
				i.ID = i.Unit
			} else {
				i.ID = i.Plant
			}
		}
	}

	query = append(query[0:0], dbox.In("VEId", VEId...))
	csr, e = c.NewQuery().
		Where(query...).
		Select("IsPrimaryFuel", "FuelType").
		Aggr(dbox.AggrSum, "ConvertedFuelConsumed", "ConvertedFuelConsumed").
		Aggr(dbox.AggrSum, "FuelCostPerUnit", "FuelCostPerUnit").
		Aggr(dbox.AggrSum, "FuelCost", "FuelCost").
		From(new(ValueEquationFuel).TableName()).Group("IsPrimaryFuel", "FuelType").Order("IsPrimaryFuel", "FuelType").Cursor(nil)
	if csr != nil {
		e = csr.Fetch(&DataTable, 0, false)
	}
	csr.Close()
	if e != nil {
		return nil, e
	}

	result.Set("DataChart", DataChart).Set("DataTable", DataTable).Set("DataTotal", DataTotal).Set("DataDetail", DataDetail)
	return result, e
}
コード例 #12
0
func (m *HistoricalValueEquation) GetMaintenanceData(ctx *orm.DataContext, k *knot.WebContext) (interface{}, error) {
	m.SetPayLoad(k)
	type DataValue struct {
		ID            string
		DataSource    string  `json:'DataSource'`
		WorkOrderType string  `json:'WorkOrderType'`
		Plant         string  `json:'Plant'`
		Unit          string  `json:'Unit'`
		LaborCost     float64 `json:'LaborCost'`
		MaterialCost  float64 `json:'MaterialCost'`
		ServiceCost   float64 `json:'ServiceCost'`
	}

	result, DataMainEx, DataOrder, DataChart, DataTable, Temp, IDList := tk.M{}, []*DataValue{}, []*DataValue{}, []tk.M{}, []DataValue{}, []tk.M{}, []interface{}{}
	c := ctx.Connection
	query := []*dbox.Filter{}
	query = append(query, dbox.Gte("Dates", m.StartPeriod))
	query = append(query, dbox.Lte("Dates", m.EndPeriod))
	groupBy := "Plant"
	switch m.Scope {
	case "Kingdom":
		break
	case "Plant":
		if m.Selected != nil && len(m.Selected) > 0 {
			query = append(query, dbox.In("Plant", m.Selected))
		}
		groupBy = "Unit"
		break
	case "Phase":
		if m.Selected != nil && len(m.Selected) > 0 {
			query = append(query, dbox.In("Phase", m.Selected))
		}
		break
	case "Unit":
		query = append(query, dbox.Eq("Plant", m.SelectedPlant))
		if m.Selected != nil && len(m.Selected) > 0 {
			query = append(query, dbox.In("Unit", m.Selected))
		}
		groupBy = "Unit"
		break
	default:
		break
	}

	// Get DataMainEx
	csr, e := c.NewQuery().
		Where(query...).
		Select(groupBy).
		Aggr(dbox.AggrSum, "TotalLabourCost", "LaborCost").
		Aggr(dbox.AggrSum, "TotalMaterialCost", "MaterialCost").
		Aggr(dbox.AggrSum, "TotalServicesCost", "ServiceCost").
		From(new(ValueEquation).TableName()).Group(groupBy).Order(groupBy).Cursor(nil)
	if e != nil {
		return nil, e
	}
	if csr != nil {
		e = csr.Fetch(&DataMainEx, 0, false)
	}
	csr.Close()
	if e != nil {
		return nil, e
	}
	for _, i := range DataMainEx {
		if i.Unit != "" {
			i.ID = i.Unit
		} else {
			i.ID = i.Plant
		}
	}

	csr, e = c.NewQuery().
		Where(query...).Select("Id").
		From(new(ValueEquation).TableName()).Cursor(nil)
	if e != nil {
		return nil, e
	}
	if csr != nil {
		e = csr.Fetch(&Temp, 0, false)
	}
	csr.Close()
	if e != nil {
		return nil, e
	}
	for _, i := range Temp {
		IDList = append(IDList, i.GetInt("id"))
	}

	query = []*dbox.Filter{}
	query = append(query, dbox.In("VEId", IDList...))

	// Get DataTable
	csr, e = c.NewQuery().
		Where(query...).
		Select("DataSource", "WorkOrderType").
		Aggr(dbox.AggrSum, "LaborCost", "LaborCost").
		Aggr(dbox.AggrSum, "MaterialCost", "MaterialCost").
		Aggr(dbox.AggrSum, "ServiceCost", "ServiceCost").
		From(new(ValueEquationDetails).TableName()).Group("DataSource", "WorkOrderType").
		Order("DataSource").
		Cursor(nil)
	if e != nil {
		return nil, e
	}
	if csr != nil {
		e = csr.Fetch(&DataTable, 0, false)
	}
	csr.Close()
	if e != nil {
		return nil, e
	}

	// Get DataOrder - For Visualisation
	csr, e = c.NewQuery().
		Where(query...).
		Select("WorkOrderType").
		From(new(ValueEquationTop10).TableName()).Group("WorkOrderType").Cursor(nil)
	if e != nil {
		return nil, e
	}
	if csr != nil {
		e = csr.Fetch(&DataOrder, 0, false)
	}
	csr.Close()
	if e != nil {
		return nil, e
	}
	for _, i := range DataOrder {
		if i.Unit != "" {
			i.ID = i.Unit
		} else {
			i.ID = i.Plant
		}
	}

	// Data Chart - set for empty, if you want to add it. its available on the previous version while its still using beego.
	result.Set("DataMainEx", DataMainEx).Set("DataOrder", DataOrder).Set("DataChart", DataChart).Set("DataTable", DataTable)
	return result, nil
}
コード例 #13
0
ファイル: woListSummary.go プロジェクト: yanda15/powerplant
// generateDurationIntervalSummary ...
func (d *GenWOListSummary) generateDurationIntervalSummary() error {
	years := [3]int{2013, 2014, 2015}

	c := d.Ctx.Connection

	csr, e := c.NewQuery().From(new(TempMstPlant).TableName()).Cursor(nil)

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

	MstPlantData := []tk.M{}
	e = csr.Fetch(&MstPlantData, 0, false)

	for _, year := range years {
		query := []*dbox.Filter{}

		yearFirst := strconv.Itoa(year)
		yearFirst = yearFirst + "-01-01 00:00:00.000"

		yearLast := strconv.Itoa(year + 1)
		yearLast = yearLast + "-01-01 00:00:00.000"

		query = append(query, dbox.And(dbox.Gte("ActualStart", yearFirst), dbox.Lte("ActualFinish", yearLast)))

		csr1, e := c.NewQuery().From(new(WOList).TableName()).Where(query...).Order("ActualStart").Cursor(nil)

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

		datas := []tk.M{}
		e = csr1.Fetch(&datas, 0, false)

		if len(datas) > 0 {
			for _, data := range datas {
				woles := new(WOListSummary)
				woles.PeriodYear = year
				woles.OrderType = data.GetString("type")
				woles.FunctionalLocation = data.GetString("functionallocation")

				query = nil
				query = append(query, dbox.Eq("FunctionalLocationCode", data.GetString("functionallocation")))

				csr2, e := c.NewQuery().From(new(FunctionalLocation).TableName()).Where(query...).Select("CatProf").Cursor(nil)

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

				tempResult := []tk.M{}
				e = csr2.Fetch(&tempResult, 0, false)

				if len(tempResult) > 0 {
					woles.EquipmentType = tempResult[0].GetString("catprof")
				}

				woles.MainenanceOrderCode = data.GetString("ordercode")
				woles.NotificationCode = data.GetString("notificationcode")

				query = nil
				query = append(query, dbox.Eq("FunctionalLocationCode", data.GetString("plant")))

				csr3, e := c.NewQuery().From(new(FunctionalLocation).TableName()).Where(query...).Select("Description").Cursor(nil)

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

				tempResult = []tk.M{}
				e = csr3.Fetch(&tempResult, 0, false)

				if len(tempResult) > 0 {
					woles.Plant = tempResult[0].GetString("description")
				}

				woles.PlanStart, e = time.Parse(time.RFC3339, data["scheduledstart"].(string))

				if e != nil {
					return e
				}

				woles.PlanEnd, e = time.Parse(time.RFC3339, data["scheduledfinish"].(string))

				if e != nil {
					return e
				}

				subTime := woles.PlanEnd.Sub(woles.PlanStart)
				woles.PlanDuration = subTime.Hours()

				woles.ActualStart, e = time.Parse(time.RFC3339, data.GetString("actualstart"))
				if e != nil {
					return e
				}

				woles.ActualEnd, e = time.Parse(time.RFC3339, data.GetString("actualfinish"))
				if e != nil {
					return e
				}

				subTime = woles.ActualEnd.Sub(woles.ActualStart)
				woles.ActualDuration = subTime.Hours()

				actualstartPart := strings.Split(woles.ActualStart.String(), " ")
				actualstartPart = []string{actualstartPart[0], actualstartPart[1]}
				query = nil
				query = append(query, dbox.Lt("ActualFinish", strings.Join(actualstartPart, " ")))
				query = append(query, dbox.Eq("FunctionalLocation", woles.FunctionalLocation))
				csr4, e := c.NewQuery().Select("ActualFinish").From(new(WOList).TableName()).Order("-ActualFinish").Where(query...).Cursor(nil)

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

				tempResult = []tk.M{}
				e = csr4.Fetch(&tempResult, 0, false)

				if len(tempResult) > 0 {
					woles.LastMaintenanceEnd, e = time.Parse(time.RFC3339, tempResult[0].GetString("actualfinish"))
				}

				if woles.ActualStart.String() != "" && woles.LastMaintenanceEnd.String() != "" {
					subTime = woles.ActualStart.Sub(woles.LastMaintenanceEnd)
					woles.LastMaintenanceInterval = subTime.Seconds() / 86400
				}

				woles.Cost = data.GetFloat64("actualcost")
				plantTypes := crowd.From(&MstPlantData).Where(func(x interface{}) interface{} {
					return x.(tk.M).GetString("plantcode") == data.GetString("plant")
				}).Exec().Result.Data().([]tk.M)

				if len(plantTypes) > 0 {
					woles.PlantType = plantTypes[0].GetString("plantcode")
				}

				for {
					e = d.Ctx.Insert(woles)
					if e == nil {
						break
					} else {
						d.Ctx.Connection.Connect()
					}
				}
			}
		}
	}
	return nil
}
コード例 #14
0
// generatePreventiveCorrectiveSummary
func (s *GenPreventiveCorrectiveSummary) generatePreventiveCorrectiveSummary() error {
	var e error
	ctx := s.BaseController.Ctx
	c := ctx.Connection

	years := [3]int{2013, 2014, 2015}
	sintax := "select Distinct(Element) from MORSummary"
	csr, e := c.NewQuery().Command("freequery", tk.M{}.Set("syntax", sintax)).Cursor(nil)
	defer csr.Close()

	if e != nil {
		return e
	}

	MROElements := []tk.M{}
	e = csr.Fetch(&MROElements, 0, false)

	csr1, e := c.NewQuery().From(new(MasterEquipmentType).TableName()).Cursor(nil)
	defer csr1.Close()

	if e != nil {
		return e
	}

	query := []*dbox.Filter{}

	for _, year := range years {
		yearFirst := strconv.Itoa(year)
		yearFirst = yearFirst + "-01-01 00:00:00.000"

		yearLast := strconv.Itoa(year + 1)
		yearLast = yearLast + "-01-01 00:00:00.000"

		query = append(query, dbox.And(dbox.Gte("Period", yearFirst), dbox.Lte("Period", yearLast)))

		csr2, e := c.NewQuery().From(new(MaintenanceCost).TableName()).Where(query...).Cursor(nil)
		defer csr2.Close()

		if e != nil {
			return e
		}

		datas := []tk.M{}
		e = csr2.Fetch(&datas, 0, false)

		Plants := crowd.From(&datas).Group(func(x interface{}) interface{} {
			return x.(tk.M).GetString("plant")
		}, nil).Exec().Result.Data().([]crowd.KV)

		if len(Plants) > 0 {
			for _, p := range Plants {
				plant := p.Key.(string)
				EqType := crowd.From(&datas).Where(func(x interface{}) interface{} {
					period := x.(tk.M).GetString("period")
					return strings.Contains(period, strconv.Itoa(year)) && x.(tk.M).GetString("plant") == plant
				}).Exec().Result.Data().([]tk.M)

				if len(EqType) > 0 {
					EquipmentTypes := crowd.From(&EqType).Group(func(x interface{}) interface{} {
						return x.(tk.M).GetString("equipmenttype")
					}, nil).Exec().Result.Data().([]crowd.KV)

					for _, eq := range EquipmentTypes {
						EquipmentType := eq.Key.(string)
						ActType := crowd.From(&EqType).Where(func(x interface{}) interface{} {
							return x.(tk.M).GetString("equipmenttype") == EquipmentType
						}).Exec().Result.Data().([]tk.M)

						if len(ActType) > 0 {
							MaintActivityTypes := crowd.From(&ActType).Group(func(x interface{}) interface{} {
								return x.(tk.M).GetString("maintenanceactivitytype")
							}, nil).Exec().Result.Data().([]crowd.KV)

							for _, act := range MaintActivityTypes {
								MaintActivityType := act.Key.(string)

								OrderType := crowd.From(&ActType).Where(func(x interface{}) interface{} {
									return x.(tk.M).GetString("maintenanceactivitytype") == MaintActivityType
								}).Exec().Result.Data().([]tk.M)

								if len(OrderType) > 0 {
									OrderTypes := crowd.From(&OrderType).Group(func(x interface{}) interface{} {
										return x.(tk.M).GetString("ordertype")
									}, nil).Exec().Result.Data().([]crowd.KV)

									for _, order := range OrderTypes {
										OrderTypeString := order.Key.(string)
										OrderNo := crowd.From(&OrderType).Where(func(x interface{}) interface{} {
											return x.(tk.M).GetString("ordertype") == OrderTypeString
										}).Exec().Result.Data().([]tk.M)
										if len(OrderNo) > 0 {
											Equipment := crowd.From(&OrderNo).Group(func(x interface{}) interface{} {
												return x.(tk.M).GetString("equipment")
											}, nil).Exec().Result.Data().([]crowd.KV)

											for _, eqNo := range Equipment {
												eqNoString := eqNo.Key.(string)
												for _, element := range MROElements {
													_ = element
													pcs := new(PreventiveCorrectiveSummary)
													pcs.PeriodYear = year
													pcs.OrderType = OrderTypeString
													pcs.EquipmentNo = eqNoString

													equipmentDescription := crowd.From(&OrderNo).Where(func(x interface{}) interface{} {
														return x.(tk.M).GetString("equipment") == eqNoString
													}).Exec().Result.Data().([]tk.M)

													if len(equipmentDescription) > 0 {
														pcs.EquipmentDescription = equipmentDescription[0].GetString("equipmentdesc")
													}

													if len(EquipmentTypes) == 1 {
														pcs.EquipmentType = "Other"
														pcs.EquipmentTypeDescription = "Other"
													} else {
														pcs.EquipmentType = EquipmentType
														pcs.EquipmentTypeDescription = equipmentDescription[0].GetString("equipmenttypedesc")
													}

													pcs.ActivityType = MaintActivityType
													pcs.Plant = PlantNormalization(plant)
													pcs.Element = element.GetString("element")

													result := float64(len(equipmentDescription) / len(MROElements))
													pcs.MOCount = int(Round(result, .5, 2))

													switch element.GetString("element") {
													case "Internal Labor":
														pcs.Value = crowd.From(&equipmentDescription).Sum(func(x interface{}) interface{} {
															return x.(tk.M).GetFloat64("internallaboractual")
														}).Exec().Result.Sum
														break
													case "Internal Material":
														pcs.Value = crowd.From(&equipmentDescription).Sum(func(x interface{}) interface{} {
															return x.(tk.M).GetFloat64("internalmaterialactual")
														}).Exec().Result.Sum
														break
													case "Direct Material":
														pcs.Value = crowd.From(&equipmentDescription).Sum(func(x interface{}) interface{} {
															return x.(tk.M).GetFloat64("directmaterialactual")
														}).Exec().Result.Sum
														break
													case "External Service":
														pcs.Value = crowd.From(&equipmentDescription).Sum(func(x interface{}) interface{} {
															return x.(tk.M).GetFloat64("externalserviceactual")
														}).Exec().Result.Sum
														break
													}

													_, e := ctx.InsertOut(pcs)

													if e != nil {
														log.Println(e.Error())
													}
												}
											}
										}
									}
								}
							}
						}
					}
				}
			}
		}
	}

	return e
}
コード例 #15
0
func (m *HistoricalValueEquation) GetPerformanceData(ctx *orm.DataContext, k *knot.WebContext) (interface{}, error) {
	type DataValue struct {
		ID            string
		Plant         string  `json:'Plant'`
		Unit          string  `json:'Unit'`
		NetGeneration float64 `json:'NetGeneration'`
		PrctWAF       float64 `json:'PrctWAF'`
	}
	m.SetPayLoad(k)
	var e error = nil
	result := []*DataValue{}
	c := ctx.Connection
	ve := ValueEquation{}
	query := []*dbox.Filter{}
	query = append(query, dbox.Gte("Dates", m.StartPeriod))
	query = append(query, dbox.Lte("Dates", m.EndPeriod))
	groupBy := "Plant"
	switch m.Scope {
	case "Kingdom":
		break
	case "Plant":
		if m.Selected != nil && len(m.Selected) > 0 {
			query = append(query, dbox.In("Plant", m.Selected))
		}
		groupBy = "Unit"
		break
	case "Phase":
		if m.Selected != nil && len(m.Selected) > 0 {
			query = append(query, dbox.In("Phase", m.Selected))
		}
		break
	case "Unit":
		query = append(query, dbox.Eq("Plant", m.SelectedPlant))
		if m.Selected != nil && len(m.Selected) > 0 {
			query = append(query, dbox.In("Unit", m.Selected))
		}
		groupBy = "Unit"
		break
	default:
		break
	}

	csr, e := c.NewQuery().
		Where(query...).Select(groupBy).
		Aggr(dbox.AggrSum, "NetGeneration", "NetGeneration").
		Aggr(dbox.AggrAvr, "PrctWAF", "PrctWAF").
		From(ve.TableName()).Group(groupBy).Order(groupBy).Cursor(nil)
	if csr != nil {
		e = csr.Fetch(&result, 0, false)
	}
	csr.Close()
	if e != nil {
		return nil, e
	}
	for _, i := range result {
		if i.Unit != "" {
			i.ID = i.Unit
		} else {
			i.ID = i.Plant
		}
	}
	return result, e
}
コード例 #16
0
ファイル: dataBrowser.go プロジェクト: yanda15/powerplant
func doGenerateMaintenanceDataBrowser(wg *sync.WaitGroup, d *GenDataBrowser, plant PowerPlantCoordinates) {
	var e error
	ctx := d.BaseController.Ctx
	c := ctx.Connection

	saveDatas := []orm.IModel{}
	plantCodeStr := plant.PlantCode
	dataCount := 0

	tmpPlantCondition := conditions.Get(plantCodeStr)
	if tmpPlantCondition != nil {
		plantCondition := tmpPlantCondition.(tk.M)

		length := plantCondition.GetInt("length")
		dets := plantCondition.Get("det").([]tk.M)
		dets = append(dets, tk.M{})

		turbinesCodes := []string{}
		genIDTempTable := tk.GenerateRandomString("", 20)

		detsLen := len(dets) - 1

		tk.Printf("detsLen: %v \n", detsLen)

		for i, det := range dets {
			freeQuery := false
			tk.Println(i)
			tk.Printf("dets: %#v \n", det)
			assets := []FunctionalLocation{}
			systemAssets := []FunctionalLocation{}
			desc := det.GetString("desc")

			query := []*dbox.Filter{}
			query = append(query, dbox.Contains("FunctionalLocationCode", plantCodeStr))
			query = append(query, dbox.Eq("PIPI", plantCodeStr))

			queryStr := "select * from FunctionalLocation where FunctionalLocationCode like('%" + plantCodeStr + "%') and PIPI = '" + plantCodeStr + "' "

			if i == 0 {
				query = append(query, dbox.Contains("Description", desc))
				if plantCodeStr == "2220" {
					query = append(query, dbox.Lte("LEN(FunctionalLocationCode)", length))
				} else {
					query = append(query, dbox.Eq("LEN(FunctionalLocationCode)", length))
				}
			} else if i == 1 && detsLen == 2 {
				query = append(query, dbox.Contains("Description", desc))
				if plantCodeStr == "2220" {
					query = append(query, dbox.Lte("LEN(FunctionalLocationCode)", length))
				} else {
					query = append(query, dbox.Eq("LEN(FunctionalLocationCode)", length))
				}
			} else {
				tk.Printf("turbinesCodes: %v \n", len(turbinesCodes))
				if len(turbinesCodes) > 1 {
					maxLength := 1000
					maxLoop := tk.ToInt(tk.ToFloat64(len(turbinesCodes)/maxLength, 0, tk.RoundingUp), tk.RoundingUp)

					for i := 0; i <= maxLoop; i++ {
						datas := []string{}

						if i != maxLoop {
							datas = turbinesCodes[i*maxLength : (i*maxLength)+maxLength]

						} else {
							datas = turbinesCodes[i*maxLength:]
						}

						tmpNotIn := []orm.IModel{}
						for _, val := range datas {
							tmpData := new(GenDataBrowserNotInTmp)
							tmpData.ID = genIDTempTable
							tmpData.FLCode = val
							tmpNotIn = append(tmpNotIn, tmpData)
						}
						// tk.Printf("tmpNotIn: %v \n", len(tmpNotIn))
						e = ctx.InsertBulk(tmpNotIn)
						ErrorHandler(e, "generateMaintenanceDataBrowser")
					}

					queryStr = queryStr + " and FunctionalLocationCode not in(select flcode from GenDataBrowserNotInTmp where ID = '" + genIDTempTable + "')"
					freeQuery = true
				}
			}

			if freeQuery {
				csrDet, e := c.NewQuery().Command("freequery", tk.M{}.Set("syntax", queryStr)).Cursor(nil)
				ErrorHandler(e, "generateMaintenanceDataBrowser")

				e = csrDet.Fetch(&assets, 0, false)
				ErrorHandler(e, "generateMaintenanceDataBrowser")
				csrDet.Close()
			} else {
				csrDet, e := c.NewQuery().From(new(FunctionalLocation).TableName()).Where(dbox.And(query...)).Cursor(nil)
				ErrorHandler(e, "generateMaintenanceDataBrowser")

				e = csrDet.Fetch(&assets, 0, false)
				ErrorHandler(e, "generateMaintenanceDataBrowser")
				csrDet.Close()
			}

			tk.Printf("-- assets: %v \n", len(assets))

			if len(assets) > 0 {
				relatedAssets := []FunctionalLocation{}

				for _, asset := range assets {

					if plantCodeStr == "2110" {
						if len(asset.FunctionalLocationCode) <= 13 {
							query = []*dbox.Filter{}
							query = append(query,
								dbox.And(
									dbox.Eq("PG", "MP1"),
									dbox.Eq("PIPI", plantCodeStr),
									dbox.Contains("FunctionalLocationCode", asset.FunctionalLocationCode),
									dbox.And(
										dbox.Lte("LEN(FunctionalLocationCode)", 13),
										dbox.Gte("LEN(FunctionalLocationCode)", 12),
									),
								),
							)

							csrDet, e := c.NewQuery().From(new(FunctionalLocation).TableName()).Where(query...).Cursor(nil)
							ErrorHandler(e, "generateMaintenanceDataBrowser")
							e = csrDet.Fetch(&systemAssets, 0, false)
							ErrorHandler(e, "generateMaintenanceDataBrowser")
							csrDet.Close()
						}

						if systemAssets == nil || len(systemAssets) == 0 {
							query = []*dbox.Filter{}

							if i != 2 {
								query = append(query, dbox.Contains("FunctionalLocationCode", asset.FunctionalLocationCode))
							} else {
								query = append(query, dbox.Eq("FunctionalLocationCode", asset.FunctionalLocationCode))
							}

							csrDet, e := c.NewQuery().From(new(FunctionalLocation).TableName()).Where(query...).Cursor(nil)
							ErrorHandler(e, "generateMaintenanceDataBrowser")
							e = csrDet.Fetch(&relatedAssets, 0, false)
							ErrorHandler(e, "generateMaintenanceDataBrowser")
							csrDet.Close()

							for _, relasset := range relatedAssets {
								isTurbineSystem := false
								if relasset.FunctionalLocationCode == asset.FunctionalLocationCode && i != 2 {
									isTurbineSystem = true
								}

								newEquipment := d.getNewEquipmentType(relasset.ObjectType, isTurbineSystem)

								if newEquipment != "" {

									if i != 2 {
										turbinesCodes = append(turbinesCodes, relasset.FunctionalLocationCode)
									}

									for _, year := range years {
										data := DataBrowser{}
										data.PeriodYear = year
										data.FunctionalLocation = relasset.FunctionalLocationCode
										data.FLDescription = relasset.Description
										data.IsTurbine = false

										// tk.Printf("%v | %v | ", relasset.FunctionalLocationCode, i)

										if relasset.FunctionalLocationCode == asset.FunctionalLocationCode && i != 2 {
											data.IsTurbine = true
											// tk.Println(" isTurbine: TRUE")
										} else {
											// tk.Println(" isTurbine: FALSE")
											data.TurbineParent = asset.FunctionalLocationCode
										}

										data.AssetType = "Other"

										if i == 0 {
											data.AssetType = "Steam"
										} else if i == 1 {
											data.AssetType = "Gas"
										}

										data.EquipmentType = newEquipment
										data.EquipmentTypeDescription = newEquipment
										data.Plant = plant
										data.PlantCode = plant.PlantCode

										if data.IsTurbine {
											info := GeneralInfo{}
											substr := ""
											substrValInt := 0
											if data.AssetType == "Steam" {
												substrValInt = 1
												substr = "ST"
											} else if data.AssetType == "Gas" {
												substrValInt = 2
											}

											if substrValInt != 0 {
												tmpInfo := crowd.From(&generalInfos).Where(func(x interface{}) interface{} {
													y := x.(GeneralInfo)
													substr = substr + data.FunctionalLocation[len(data.FunctionalLocation)-substrValInt:]
													return strings.Contains(strings.ToLower(strings.Trim(y.Plant, " ")), strings.ToLower(plant.PlantName)) && y.Unit == substr
												}).Exec().Result.Data().([]GeneralInfo)
												if len(tmpInfo) > 0 {
													info = tmpInfo[0]
												}

												if info.Id != "" {
													data.TInfShortName = info.Unit
													data.TInfManufacturer = info.Manufacturer
													data.TInfModel = info.Model
													data.TInfUnitType = info.UnitType
													data.TInfInstalledCapacity = info.InstalledCapacity
													data.TInfOperationalCapacity = info.OperationalCapacity
													data.TInfPrimaryFuel = info.PrimaryFuel1
													data.TInfPrimaryFuel2 = info.PrimaryFuel2Startup
													data.TInfBackupFuel = info.BackupFuel
													data.TInfHeatRate = info.HeatRate
													data.TInfEfficiency = info.Efficiency

													commDate, e := time.Parse("01/02/2006", "01/01"+tk.ToString(info.CommissioningDate))
													ErrorHandler(e, "generateMaintenanceDataBrowser")
													data.TInfCommisioningDate = commDate

													if info.RetirementPlan != "" {
														retirementPlanStr := strings.Split(info.RetirementPlan, "(")[0]
														retirementPlan, e := time.Parse("01/02/2006", "01/01"+retirementPlanStr)
														ErrorHandler(e, "generateMaintenanceDataBrowser")
														data.TInfRetirementPlan = retirementPlan
													}

													installedMWH := crowd.From(&generalInfoDetails).Where(func(x interface{}) interface{} {
														y := x.(GeneralInfoDetails)
														return y.GenID == info.Id && y.Type == "InstalledMWH" && y.Year == year
													}).Exec().Result.Data().([]GeneralInfoDetails)[0]

													data.TInfInstalledMWH = installedMWH.Value

													actualEnergyGeneration := crowd.From(&generalInfoDetails).Where(func(x interface{}) interface{} {
														y := x.(GeneralInfoDetails)
														return y.GenID == info.Id && y.Type == "ActualEnergyGeneration" && y.Year == year
													}).Exec().Result.Data().([]GeneralInfoDetails)[0]

													data.TInfActualEnergyGeneration = actualEnergyGeneration.Value

													capacityFactor := crowd.From(&generalInfoDetails).Where(func(x interface{}) interface{} {
														y := x.(GeneralInfoDetails)
														return y.GenID == info.Id && y.Type == "CapacityFactor" && y.Year == year
													}).Exec().Result.Data().([]GeneralInfoDetails)[0]

													data.TInfCapacityFactor = capacityFactor.Value

													actualFuelConsumption := crowd.From(&generalInfoActualFuelConsumption).Where(func(x interface{}) interface{} {
														y := x.(GeneralInfoActualFuelConsumption)
														return y.GenID == info.Id && y.Year == year
													}).Exec().Result.Data().([]GeneralInfoActualFuelConsumption)[0]

													data.TInfActualFuelConsumption_CrudeBarrel = actualFuelConsumption.CrudeBarrel
													data.TInfActualFuelConsumption_DieselBarrel = actualFuelConsumption.DieselBarrel
													data.TInfActualFuelConsumption_GASMMSCF = actualFuelConsumption.GASMMSCF
													data.TInfActualFuelConsumption_HFOBarrel = actualFuelConsumption.HFOBarrel

													fuelCostCrowd := crowd.From(&fuelCosts).Where(func(x interface{}) interface{} {
														y := x.(FuelCost)
														unitID := strings.Replace(
															strings.Replace(
																strings.Replace(
																	strings.Replace(y.UnitId, ".", "", -1), " 0", "", -1), " ", "", -1), "C.C ", "", -1)

														return y.Year == year && y.Plant == data.Plant.PlantName && unitID == data.TInfShortName
													})

													data.TInfUpdateEnergyGeneration = fuelCostCrowd.Sum(func(x interface{}) interface{} {
														y := x.(FuelCost)
														return y.EnergyNetProduction
													}).Exec().Result.Data().(float64)

													data.TInfUpdateFuelConsumption = fuelCostCrowd.Sum(func(x interface{}) interface{} {
														y := x.(FuelCost)
														return y.PrimaryFuelConsumed
													}).Exec().Result.Data().(float64)
												}
											}
											// Vibrations handled by sql query
										}

										// Maintenance handled by sql query
										// FailureNotifications handled by sql query
										// MROElements handled by sql query
										// Operationals handled by sql query

										// e = ctx.Insert(&data)
										saveDatas = append(saveDatas, &data)
										dataCount++
										if len(saveDatas) == 1000 {
											mugen.Lock()
											e = ctx.InsertBulk(saveDatas)
											mugen.Unlock()
											ErrorHandler(e, "generateMaintenanceDataBrowser")
											tk.Printf("%v : %v \n", plantCodeStr, dataCount)

											saveDatas = []orm.IModel{}
										}

										/*ErrorHandler(e, "generateMaintenanceDataBrowser")
										tk.Println("save 1")*/
									}
								}
							}

						} else {
							// with system assets
							if i != 2 {
								turbinesCodes = append(turbinesCodes, asset.FunctionalLocationCode)
							}

							for _, year := range years {
								data := DataBrowser{}
								data.PeriodYear = year
								data.FunctionalLocation = asset.FunctionalLocationCode
								data.FLDescription = asset.Description
								data.IsTurbine = false
								data.IsSystem = false

								// tk.Printf("%v | %v | ", asset.FunctionalLocationCode, i)

								if asset.FunctionalLocationCode == asset.FunctionalLocationCode && i != 2 {
									data.IsTurbine = true
									data.IsSystem = true
									// tk.Println(" isTurbine: TRUE")
								} else {
									// tk.Println(" isTurbine: FALSE")
									data.TurbineParent = asset.FunctionalLocationCode
									data.SystemParent = asset.FunctionalLocationCode
								}

								data.AssetType = "Other"

								if i == 0 {
									data.AssetType = "Steam"
								} else if i == 1 {
									data.AssetType = "Gas"
								}

								data.EquipmentType = "System"
								data.EquipmentTypeDescription = "System"
								data.Plant = plant
								data.PlantCode = plant.PlantCode

								if data.IsTurbine {
									info := GeneralInfo{}
									substr := ""
									substrValInt := 0
									if data.AssetType == "Steam" {
										substrValInt = 1
										substr = "ST"
									} else if data.AssetType == "Gas" {
										substrValInt = 2
									}

									if substrValInt != 0 {
										tmpInfo := crowd.From(&generalInfos).Where(func(x interface{}) interface{} {
											y := x.(GeneralInfo)
											substr = substr + data.FunctionalLocation[len(data.FunctionalLocation)-substrValInt:]
											return strings.Contains(strings.ToLower(strings.Trim(y.Plant, " ")), strings.ToLower(plant.PlantName)) && y.Unit == substr
										}).Exec().Result.Data().([]GeneralInfo)
										if len(tmpInfo) > 0 {
											info = tmpInfo[0]
										}

										if info.Id != "" {
											data.TInfShortName = info.Unit
											data.TInfManufacturer = info.Manufacturer
											data.TInfModel = info.Model
											data.TInfUnitType = info.UnitType
											data.TInfInstalledCapacity = info.InstalledCapacity
											data.TInfOperationalCapacity = info.OperationalCapacity
											data.TInfPrimaryFuel = info.PrimaryFuel1
											data.TInfPrimaryFuel2 = info.PrimaryFuel2Startup
											data.TInfBackupFuel = info.BackupFuel
											data.TInfHeatRate = info.HeatRate
											data.TInfEfficiency = info.Efficiency

											commDate, e := time.Parse("01/02/2006", "01/01"+tk.ToString(info.CommissioningDate))
											ErrorHandler(e, "generateMaintenanceDataBrowser")
											data.TInfCommisioningDate = commDate

											if info.RetirementPlan != "" {
												retirementPlanStr := strings.Split(info.RetirementPlan, "(")[0]
												retirementPlan, e := time.Parse("01/02/2006", "01/01"+retirementPlanStr)
												ErrorHandler(e, "generateMaintenanceDataBrowser")
												data.TInfRetirementPlan = retirementPlan
											}

											installedMWH := crowd.From(&generalInfoDetails).Where(func(x interface{}) interface{} {
												y := x.(GeneralInfoDetails)
												return y.GenID == info.Id && y.Type == "InstalledMWH" && y.Year == year
											}).Exec().Result.Data().([]GeneralInfoDetails)[0]

											data.TInfInstalledMWH = installedMWH.Value

											actualEnergyGeneration := crowd.From(&generalInfoDetails).Where(func(x interface{}) interface{} {
												y := x.(GeneralInfoDetails)
												return y.GenID == info.Id && y.Type == "ActualEnergyGeneration" && y.Year == year
											}).Exec().Result.Data().([]GeneralInfoDetails)[0]

											data.TInfActualEnergyGeneration = actualEnergyGeneration.Value

											capacityFactor := crowd.From(&generalInfoDetails).Where(func(x interface{}) interface{} {
												y := x.(GeneralInfoDetails)
												return y.GenID == info.Id && y.Type == "CapacityFactor" && y.Year == year
											}).Exec().Result.Data().([]GeneralInfoDetails)[0]

											data.TInfCapacityFactor = capacityFactor.Value

											actualFuelConsumption := crowd.From(&generalInfoActualFuelConsumption).Where(func(x interface{}) interface{} {
												y := x.(GeneralInfoActualFuelConsumption)
												return y.GenID == info.Id && y.Year == year
											}).Exec().Result.Data().([]GeneralInfoActualFuelConsumption)[0]

											data.TInfActualFuelConsumption_CrudeBarrel = actualFuelConsumption.CrudeBarrel
											data.TInfActualFuelConsumption_DieselBarrel = actualFuelConsumption.DieselBarrel
											data.TInfActualFuelConsumption_GASMMSCF = actualFuelConsumption.GASMMSCF
											data.TInfActualFuelConsumption_HFOBarrel = actualFuelConsumption.HFOBarrel

											fuelCostCrowd := crowd.From(&fuelCosts).Where(func(x interface{}) interface{} {
												y := x.(FuelCost)
												unitID := strings.Replace(
													strings.Replace(
														strings.Replace(
															strings.Replace(y.UnitId, ".", "", -1), " 0", "", -1), " ", "", -1), "C.C ", "", -1)

												return y.Year == year && y.Plant == data.Plant.PlantName && unitID == data.TInfShortName
											})

											data.TInfUpdateEnergyGeneration = fuelCostCrowd.Sum(func(x interface{}) interface{} {
												y := x.(FuelCost)
												return y.EnergyNetProduction
											}).Exec().Result.Data().(float64)

											data.TInfUpdateFuelConsumption = fuelCostCrowd.Sum(func(x interface{}) interface{} {
												y := x.(FuelCost)
												return y.PrimaryFuelConsumed
											}).Exec().Result.Data().(float64)
										}
									}
									// Vibrations handled by sql query
								}

								// Maintenance handled by sql query
								// FailureNotifications handled by sql query
								// MROElements handled by sql query
								// Operationals handled by sql query

								// e = ctx.Insert(&data)
								// dataCount++
								saveDatas = append(saveDatas, &data)
								dataCount++
								if len(saveDatas) == 1000 {
									mugen.Lock()
									e = ctx.InsertBulk(saveDatas)
									mugen.Unlock()
									ErrorHandler(e, "generateMaintenanceDataBrowser")
									tk.Printf("%v : %v \n", plantCodeStr, dataCount)

									saveDatas = []orm.IModel{}
								}

								/*ErrorHandler(e, "generateMaintenanceDataBrowser")
								tk.Println("save 2")*/

							}

							for _, sysAsset := range systemAssets {
								query = []*dbox.Filter{}

								if i != 2 {
									query = append(query, dbox.Contains("FunctionalLocationCode", sysAsset.FunctionalLocationCode))
								} else {
									query = append(query, dbox.Eq("FunctionalLocationCode", sysAsset.FunctionalLocationCode))
								}

								csrDet, e := c.NewQuery().From(new(FunctionalLocation).TableName()).Where(query...).Cursor(nil)
								ErrorHandler(e, "generateMaintenanceDataBrowser")
								e = csrDet.Fetch(&relatedAssets, 0, false)
								ErrorHandler(e, "generateMaintenanceDataBrowser")
								csrDet.Close()

								for _, relasset := range relatedAssets {
									isTurbineSystem := false
									if (relasset.FunctionalLocationCode == asset.FunctionalLocationCode || relasset.FunctionalLocationCode == sysAsset.FunctionalLocationCode) && i != 2 {
										isTurbineSystem = true
									}

									newEquipment := d.getNewEquipmentType(relasset.ObjectType, isTurbineSystem)

									if newEquipment != "" {

										if i != 2 {
											turbinesCodes = append(turbinesCodes, relasset.FunctionalLocationCode)
										}

										for _, year := range years {
											data := DataBrowser{}
											data.PeriodYear = year
											data.FunctionalLocation = relasset.FunctionalLocationCode
											data.FLDescription = relasset.Description
											data.IsTurbine = false
											data.IsSystem = false

											// tk.Printf("%v | %v | ", relasset.FunctionalLocationCode, i)

											if relasset.FunctionalLocationCode == sysAsset.FunctionalLocationCode && i != 2 {
												data.IsTurbine = true
												data.IsSystem = true
												// tk.Println(" isTurbine: TRUE")
											} else {
												// tk.Println(" isTurbine: FALSE")
												data.TurbineParent = asset.FunctionalLocationCode
												data.SystemParent = asset.FunctionalLocationCode
											}

											data.AssetType = "Other"

											if i == 0 {
												data.AssetType = "Steam"
											} else if i == 1 {
												data.AssetType = "Gas"
											}

											data.EquipmentType = newEquipment
											data.EquipmentTypeDescription = newEquipment
											data.Plant = plant
											data.PlantCode = plant.PlantCode

											if data.IsTurbine {
												info := GeneralInfo{}
												substr := ""
												substrValInt := 0
												if data.AssetType == "Steam" {
													substrValInt = 1
													substr = "ST"
												} else if data.AssetType == "Gas" {
													substrValInt = 2
												}

												if substrValInt != 0 {
													tmpInfo := crowd.From(&generalInfos).Where(func(x interface{}) interface{} {
														y := x.(GeneralInfo)
														substr = substr + data.FunctionalLocation[len(data.FunctionalLocation)-substrValInt:]
														return strings.Contains(strings.ToLower(strings.Trim(y.Plant, " ")), strings.ToLower(plant.PlantName)) && y.Unit == substr
													}).Exec().Result.Data().([]GeneralInfo)
													if len(tmpInfo) > 0 {
														info = tmpInfo[0]
													}

													if info.Id != "" {
														data.TInfShortName = info.Unit
														data.TInfManufacturer = info.Manufacturer
														data.TInfModel = info.Model
														data.TInfUnitType = info.UnitType
														data.TInfInstalledCapacity = info.InstalledCapacity
														data.TInfOperationalCapacity = info.OperationalCapacity
														data.TInfPrimaryFuel = info.PrimaryFuel1
														data.TInfPrimaryFuel2 = info.PrimaryFuel2Startup
														data.TInfBackupFuel = info.BackupFuel
														data.TInfHeatRate = info.HeatRate
														data.TInfEfficiency = info.Efficiency

														commDate, e := time.Parse("01/02/2006", "01/01"+tk.ToString(info.CommissioningDate))
														ErrorHandler(e, "generateMaintenanceDataBrowser")
														data.TInfCommisioningDate = commDate

														if info.RetirementPlan != "" {
															retirementPlanStr := strings.Split(info.RetirementPlan, "(")[0]
															retirementPlan, e := time.Parse("01/02/2006", "01/01"+retirementPlanStr)
															ErrorHandler(e, "generateMaintenanceDataBrowser")
															data.TInfRetirementPlan = retirementPlan
														}

														installedMWH := crowd.From(&generalInfoDetails).Where(func(x interface{}) interface{} {
															y := x.(GeneralInfoDetails)
															return y.GenID == info.Id && y.Type == "InstalledMWH" && y.Year == year
														}).Exec().Result.Data().([]GeneralInfoDetails)[0]

														data.TInfInstalledMWH = installedMWH.Value

														actualEnergyGeneration := crowd.From(&generalInfoDetails).Where(func(x interface{}) interface{} {
															y := x.(GeneralInfoDetails)
															return y.GenID == info.Id && y.Type == "ActualEnergyGeneration" && y.Year == year
														}).Exec().Result.Data().([]GeneralInfoDetails)[0]

														data.TInfActualEnergyGeneration = actualEnergyGeneration.Value

														capacityFactor := crowd.From(&generalInfoDetails).Where(func(x interface{}) interface{} {
															y := x.(GeneralInfoDetails)
															return y.GenID == info.Id && y.Type == "CapacityFactor" && y.Year == year
														}).Exec().Result.Data().([]GeneralInfoDetails)[0]

														data.TInfCapacityFactor = capacityFactor.Value

														actualFuelConsumption := crowd.From(&generalInfoActualFuelConsumption).Where(func(x interface{}) interface{} {
															y := x.(GeneralInfoActualFuelConsumption)
															return y.GenID == info.Id && y.Year == year
														}).Exec().Result.Data().([]GeneralInfoActualFuelConsumption)[0]

														data.TInfActualFuelConsumption_CrudeBarrel = actualFuelConsumption.CrudeBarrel
														data.TInfActualFuelConsumption_DieselBarrel = actualFuelConsumption.DieselBarrel
														data.TInfActualFuelConsumption_GASMMSCF = actualFuelConsumption.GASMMSCF
														data.TInfActualFuelConsumption_HFOBarrel = actualFuelConsumption.HFOBarrel

														fuelCostCrowd := crowd.From(&fuelCosts).Where(func(x interface{}) interface{} {
															y := x.(FuelCost)
															unitID := strings.Replace(
																strings.Replace(
																	strings.Replace(
																		strings.Replace(y.UnitId, ".", "", -1), " 0", "", -1), " ", "", -1), "C.C ", "", -1)

															return y.Year == year && y.Plant == data.Plant.PlantName && unitID == data.TInfShortName
														})

														data.TInfUpdateEnergyGeneration = fuelCostCrowd.Sum(func(x interface{}) interface{} {
															y := x.(FuelCost)
															return y.EnergyNetProduction
														}).Exec().Result.Data().(float64)

														data.TInfUpdateFuelConsumption = fuelCostCrowd.Sum(func(x interface{}) interface{} {
															y := x.(FuelCost)
															return y.PrimaryFuelConsumed
														}).Exec().Result.Data().(float64)
													}
												}
												// Vibrations handled by sql query
											}

											// Maintenance handled by sql query
											// FailureNotifications handled by sql query
											// MROElements handled by sql query
											// Operationals handled by sql query

											// e = ctx.Insert(&data)
											saveDatas = append(saveDatas, &data)
											dataCount++
											if len(saveDatas) == 1000 {
												mugen.Lock()
												e = ctx.InsertBulk(saveDatas)
												mugen.Unlock()
												ErrorHandler(e, "generateMaintenanceDataBrowser")
												tk.Printf("%v : %v \n", plantCodeStr, dataCount)

												saveDatas = []orm.IModel{}
											}

											/*ErrorHandler(e, "generateMaintenanceDataBrowser")
											tk.Println("save 3")*/
										}
									}
								}
							}
						}
					} else {
						// another plant(s)

						query = []*dbox.Filter{}

						if i != detsLen {
							query = append(query, dbox.Contains("FunctionalLocationCode", asset.FunctionalLocationCode))
						} else {
							query = append(query, dbox.Eq("FunctionalLocationCode", asset.FunctionalLocationCode))
						}

						csrDet, e := c.NewQuery().From(new(FunctionalLocation).TableName()).Where(query...).Cursor(nil)
						ErrorHandler(e, "generateMaintenanceDataBrowser")
						e = csrDet.Fetch(&relatedAssets, 0, false)
						ErrorHandler(e, "generateMaintenanceDataBrowser")
						csrDet.Close()
						tk.Printf("-- related assets: %v \n", len(relatedAssets))

						for _, relasset := range relatedAssets {
							isTurbineSystem := false
							if relasset.FunctionalLocationCode == asset.FunctionalLocationCode && i != detsLen {
								isTurbineSystem = true
							}

							newEquipment := ""
							newEquipment = d.getNewEquipmentType(relasset.ObjectType, isTurbineSystem)

							if newEquipment != "" {

								if i != detsLen {
									turbinesCodes = append(turbinesCodes, relasset.FunctionalLocationCode)
								}

								for _, year := range years {
									_ = year
									data := DataBrowser{}
									data.PeriodYear = year
									data.FunctionalLocation = relasset.FunctionalLocationCode
									data.FLDescription = relasset.Description
									data.IsTurbine = false

									if relasset.FunctionalLocationCode == asset.FunctionalLocationCode && i != detsLen {
										data.IsTurbine = true
									} else {
										data.TurbineParent = asset.FunctionalLocationCode
									}

									data.AssetType = "Other"

									if i == 0 {
										data.AssetType = "Steam"
									} else if i == 1 && detsLen > 1 {
										data.AssetType = "Gas"
									}

									data.EquipmentType = newEquipment
									data.EquipmentTypeDescription = newEquipment
									data.Plant = plant
									data.PlantCode = plant.PlantCode

									if data.IsTurbine {
										info := GeneralInfo{}
										substr := ""
										substrValInt := 0
										if data.AssetType == "Steam" {
											// substrValInt = 1
											substrValInt = 2
											substr = "ST" + substr
										} else if data.AssetType == "Gas" {
											substrValInt = 2
											substr = "GT" + substr
										}

										if substrValInt != 0 {
											tmpInfo := crowd.From(&generalInfos).Where(func(x interface{}) interface{} {
												y := x.(GeneralInfo)
												substr = data.FunctionalLocation[len(data.FunctionalLocation)-substrValInt:]
												return strings.Contains(strings.ToLower(strings.Trim(y.Plant, " ")), strings.ToLower(plant.PlantName)) && y.Unit == substr
											}).Exec().Result.Data().([]GeneralInfo)
											if len(tmpInfo) > 0 {
												info = tmpInfo[0]
											}

											if info.Id != "" {
												data.TInfShortName = info.Unit
												data.TInfManufacturer = info.Manufacturer
												data.TInfModel = info.Model
												data.TInfUnitType = info.UnitType
												data.TInfInstalledCapacity = info.InstalledCapacity
												data.TInfOperationalCapacity = info.OperationalCapacity
												data.TInfPrimaryFuel = info.PrimaryFuel1
												data.TInfPrimaryFuel2 = info.PrimaryFuel2Startup
												data.TInfBackupFuel = info.BackupFuel
												data.TInfHeatRate = info.HeatRate
												data.TInfEfficiency = info.Efficiency

												commDate, e := time.Parse("01/02/2006", "01/01"+tk.ToString(info.CommissioningDate))
												ErrorHandler(e, "generateMaintenanceDataBrowser")

												data.TInfCommisioningDate = commDate

												if info.RetirementPlan != "" {
													retirementPlanStr := strings.Split(info.RetirementPlan, "(")[0]
													retirementPlan, e := time.Parse("01/02/2006", "01/01"+retirementPlanStr)
													ErrorHandler(e, "generateMaintenanceDataBrowser")
													data.TInfRetirementPlan = retirementPlan
												}

												installedMWH := crowd.From(&generalInfoDetails).Where(func(x interface{}) interface{} {
													y := x.(GeneralInfoDetails)
													return y.GenID == info.Id && y.Type == "InstalledMWH" && y.Year == year
												}).Exec().Result.Data().([]GeneralInfoDetails)[0]

												data.TInfInstalledMWH = installedMWH.Value

												actualEnergyGeneration := crowd.From(&generalInfoDetails).Where(func(x interface{}) interface{} {
													y := x.(GeneralInfoDetails)
													return y.GenID == info.Id && y.Type == "ActualEnergyGeneration" && y.Year == year
												}).Exec().Result.Data().([]GeneralInfoDetails)[0]

												data.TInfActualEnergyGeneration = actualEnergyGeneration.Value

												capacityFactor := crowd.From(&generalInfoDetails).Where(func(x interface{}) interface{} {
													y := x.(GeneralInfoDetails)
													return y.GenID == info.Id && y.Type == "CapacityFactor" && y.Year == year
												}).Exec().Result.Data().([]GeneralInfoDetails)[0]

												data.TInfCapacityFactor = capacityFactor.Value

												actualFuelConsumption := crowd.From(&generalInfoActualFuelConsumption).Where(func(x interface{}) interface{} {
													y := x.(GeneralInfoActualFuelConsumption)
													return y.GenID == info.Id && y.Year == year
												}).Exec().Result.Data().([]GeneralInfoActualFuelConsumption)[0]

												data.TInfActualFuelConsumption_CrudeBarrel = actualFuelConsumption.CrudeBarrel
												data.TInfActualFuelConsumption_DieselBarrel = actualFuelConsumption.DieselBarrel
												data.TInfActualFuelConsumption_GASMMSCF = actualFuelConsumption.GASMMSCF
												data.TInfActualFuelConsumption_HFOBarrel = actualFuelConsumption.HFOBarrel

												fuelCostCrowd := crowd.From(&fuelCosts).Where(func(x interface{}) interface{} {
													y := x.(FuelCost)
													unitID := strings.Replace(
														strings.Replace(
															strings.Replace(
																strings.Replace(y.UnitId, ".", "", -1), " 0", "", -1), " ", "", -1), "C.C ", "", -1)

													return y.Year == year && y.Plant == data.Plant.PlantName && unitID == data.TInfShortName
												})

												data.TInfUpdateEnergyGeneration = fuelCostCrowd.Sum(func(x interface{}) interface{} {
													y := x.(FuelCost)
													return y.EnergyNetProduction
												}).Exec().Result.Data().(float64)

												data.TInfUpdateFuelConsumption = fuelCostCrowd.Sum(func(x interface{}) interface{} {
													y := x.(FuelCost)
													return y.PrimaryFuelConsumed
												}).Exec().Result.Data().(float64)
											}
										}
										// Vibrations handled by sql query
									}

									// Maintenance handled by sql query
									// FailureNotifications handled by sql query
									// MROElements handled by sql query
									// Operationals handled by sql query

									// e = ctx.Insert(&data)
									saveDatas = append(saveDatas, &data)
									dataCount++
									if len(saveDatas) == 1000 {
										mugen.Lock()
										e = ctx.InsertBulk(saveDatas)
										mugen.Unlock()
										ErrorHandler(e, "generateMaintenanceDataBrowser")
										tk.Printf("%v : %v \n", plantCodeStr, dataCount)

										saveDatas = []orm.IModel{}
									}

									/*ErrorHandler(e, "generateMaintenanceDataBrowser")
									tk.Println("save 4")*/
								}
							}
						}
					}

				}
			}
		}

		e = c.NewQuery().Delete().From(new(GenDataBrowserNotInTmp).TableName()).SetConfig("multiexec", true).Where(dbox.Eq("ID", genIDTempTable)).Exec(nil)

		if len(saveDatas) > 0 {
			e = ctx.InsertBulk(saveDatas)
			ErrorHandler(e, "generateMaintenanceDataBrowser")
			tk.Printf("%v : %v \n", plantCodeStr, dataCount)
		}

	}

	mugen.Lock()
	dataCounts.Set(plantCodeStr, dataCount)
	mugen.Unlock()

	wg.Done()
}
コード例 #17
0
func (m *HistoricalValueEquation) GetAssetWorkData(ctx *orm.DataContext, k *knot.WebContext) (interface{}, error) {
	type DataValue struct {
		ID                 string
		Plant              string  `json:'Plant'`
		Unit               string  `json:'Unit'`
		ValueEquationCost  float64 `json:'ValueEquationCost'`
		MaxPowerGeneration float64 `json:'MaxPowerGeneration'`
		PotentialRevenue   float64 `json:'PotentialRevenue'`
		NetGeneration      float64 `json:'NetGeneration'`
		Revenue            float64 `json:'Revenue'`
		ForcedOutages      float64 `json:'ForcedOutages'`
		ForcedOutagesLoss  float64 `json:'ForcedOutagesLoss'`
		UnforcedOutages    float64 `json:'UnforcedOutages'`

		UnforcedOutagesLoss float64 `json:'UnforcedOutagesLoss'`
		TotalLabourCost     float64 `json:'TotalLabourCost'`
		TotalMaterialCost   float64 `json:'TotalMaterialCost'`
		TotalServicesCost   float64 `json:'TotalServicesCost'`
		MaintenanceCost     float64 `json:'MaintenanceCost'`
		OperatingCost       float64 `json:'OperatingCost'`
	}

	m.SetPayLoad(k)
	var e error = nil
	result := []*DataValue{}
	c := ctx.Connection
	ve := ValueEquation{}
	query := []*dbox.Filter{}
	query = append(query, dbox.Gte("Dates", m.StartPeriod))
	query = append(query, dbox.Lte("Dates", m.EndPeriod))
	groupBy := "Plant"
	switch m.Scope {
	case "Kingdom":
		break
	case "Plant":
		if m.Selected != nil && len(m.Selected) > 0 {
			query = append(query, dbox.In("Plant", m.Selected))
		}
		groupBy = "Unit"
		break
	case "Phase":
		if m.Selected != nil && len(m.Selected) > 0 {
			query = append(query, dbox.In("Phase", m.Selected))
		}
		break
	case "Unit":
		query = append(query, dbox.Eq("Plant", m.SelectedPlant))
		if m.Selected != nil && len(m.Selected) > 0 {
			query = append(query, dbox.In("Unit", m.Selected))
		}
		groupBy = "Unit"
		break
	default:
		break
	}

	csr, e := c.NewQuery().
		Where(query...).Select(groupBy).
		Aggr(dbox.AggrSum, "ValueEquationCost", "ValueEquationCost").
		Aggr(dbox.AggrSum, "MaxPowerGeneration", "MaxPowerGeneration").
		Aggr(dbox.AggrSum, "PotentialRevenue", "PotentialRevenue").
		Aggr(dbox.AggrSum, "NetGeneration", "NetGeneration").
		Aggr(dbox.AggrSum, "Revenue", "Revenue").
		Aggr(dbox.AggrSum, "ForcedOutages", "ForcedOutages").
		Aggr(dbox.AggrSum, "ForcedOutagesLoss", "ForcedOutagesLoss").
		Aggr(dbox.AggrSum, "UnforcedOutages", "UnforcedOutages").
		Aggr(dbox.AggrSum, "UnforcedOutagesLoss", "UnforcedOutagesLoss").
		Aggr(dbox.AggrSum, "TotalLabourCost", "TotalLabourCost").
		Aggr(dbox.AggrSum, "TotalMaterialCost", "TotalMaterialCost").
		Aggr(dbox.AggrSum, "TotalServicesCost", "TotalServicesCost").
		Aggr(dbox.AggrSum, "MaintenanceCost", "MaintenanceCost").
		Aggr(dbox.AggrSum, "OperatingCost", "OperatingCost").
		From(ve.TableName()).Group(groupBy).Order(groupBy).Cursor(nil)
	if csr != nil {
		e = csr.Fetch(&result, 0, false)
	}
	csr.Close()
	if e != nil {
		return nil, e
	}
	for _, i := range result {
		if i.Unit != "" {
			i.ID = i.Unit
		} else {
			i.ID = i.Plant
		}
	}
	return result, e
}
コード例 #18
0
func (s *GenWODurationSummary) generateDurationCostWorkOrderSummary() error {
	ctx := s.BaseController.Ctx
	c := ctx.Connection
	var (
		query []*dbox.Filter
	)
	tk.Println("Generating Duration Cost Work Order Summary..")
	Years := []int{2013, 2014, 2015}
	query = []*dbox.Filter{}

	EqTypes := []MappedEquipmentType{}
	csr, e := c.NewQuery().From(new(MappedEquipmentType).TableName()).Cursor(nil)
	defer csr.Close()

	if e != nil {
		return e
	}

	e = csr.Fetch(&EqTypes, 0, false)
	if e != nil {
		return e
	}
	for _, year := range Years {
		query = []*dbox.Filter{}
		query = append(query, dbox.Gte("Period", time.Date(year, 1, 1, 0, 0, 0, 0, time.UTC)))
		query = append(query, dbox.Lt("Period", time.Date((year+1), 1, 1, 0, 0, 0, 0, time.UTC)))

		MaintenanceCostByHours := []MaintenanceCostByHour{}
		csr, e := c.NewQuery().From(new(MaintenanceCostByHour).TableName()).Where(query...).Cursor(nil)
		if e != nil {
			return e
		}
		e = csr.Fetch(&MaintenanceCostByHours, 0, false)
		if e != nil {
			return e
		}
		csr.Close()

		MaintenanceCostList := []MaintenanceCost{}
		csr, e = c.NewQuery().From(new(MaintenanceCost).TableName()).Where(query...).Cursor(nil)
		if e != nil {
			return e
		}
		e = csr.Fetch(&MaintenanceCostList, 0, false)
		if e != nil {
			return e
		}
		csr.Close()

		Plants := crowd.From(&MaintenanceCostByHours).Group(func(x interface{}) interface{} {
			return x.(MaintenanceCostByHour).Plant
		}, nil).Exec().Result.Data().([]crowd.KV)

		for _, p := range Plants {
			plant := p.Key.(string)
			EqType := crowd.From(&MaintenanceCostByHours).Where(func(x interface{}) interface{} {
				return x.(MaintenanceCostByHour).Plant == plant
			}).Group(func(x interface{}) interface{} {
				return x.(MaintenanceCostByHour).EquipmentType
			}, nil).Exec().Result.Data().([]crowd.KV)

			for _, eqt := range EqType {
				eq := eqt.Key.(string)
				ActType := crowd.From(&MaintenanceCostByHours).Where(func(x interface{}) interface{} {
					o := x.(MaintenanceCostByHour)
					return o.Plant == plant && o.EquipmentType == eq
				}).Group(func(x interface{}) interface{} {
					return x.(MaintenanceCostByHour).MaintenanceActivityType
				}, nil).Exec().Result.Data().([]crowd.KV)

				for _, a := range ActType {
					act := a.Key.(string)
					OrderType := crowd.From(&MaintenanceCostByHours).Where(func(x interface{}) interface{} {
						o := x.(MaintenanceCostByHour)
						return o.Plant == plant && o.EquipmentType == eq && o.MaintenanceActivityType == act
					}).Group(func(x interface{}) interface{} {
						return x.(MaintenanceCostByHour).OrderType
					}, nil).Exec().Result.Data().([]crowd.KV)

					for _, o := range OrderType {
						order := o.Key.(string)
						d := new(WODurationSummary)
						d.PeriodYear = year
						d.OrderType = order
						if len(eq) == 1 {
							d.EquipmentType = "Other"
						} else {
							d.EquipmentType = eq
						}
						if len(eq) == 1 {
							d.EquipmentTypeDescription = "Other"
						} else {
							EqTypeDesc := crowd.From(&MaintenanceCostByHours).Where(func(x interface{}) interface{} {
								o := x.(MaintenanceCostByHour)
								return o.Plant == plant && o.EquipmentType == eq
							}).Exec().Result.Data().([]MaintenanceCostByHour)
							if len(EqTypeDesc) > 0 {
								d.EquipmentTypeDescription = EqTypeDesc[0].EquipmentTypeDesc
							}
						}

						d.ActivityType = act
						d.Plant = PlantNormalization(plant)
						d.PlanValue = crowd.From(&MaintenanceCostByHours).Where(func(x interface{}) interface{} {
							o := x.(MaintenanceCostByHour)
							return o.Plant == plant && o.EquipmentType == eq && o.MaintenanceActivityType == act
						}).Sum(func(x interface{}) interface{} {
							return x.(MaintenanceCostByHour).PlanVal
						}).Exec().Result.Sum
						d.ActualValue = crowd.From(&MaintenanceCostByHours).Where(func(x interface{}) interface{} {
							o := x.(MaintenanceCostByHour)
							return o.Plant == plant && o.EquipmentType == eq && o.MaintenanceActivityType == act
						}).Sum(func(x interface{}) interface{} {
							return x.(MaintenanceCostByHour).Actual
						}).Exec().Result.Sum
						d.WOCount = len(OrderType)
						d.Cost = crowd.From(&MaintenanceCostList).Where(func(x interface{}) interface{} {
							o := x.(MaintenanceCost)
							return o.Plant == plant && o.EquipmentType == eq && o.MaintenanceActivityType == act
						}).Sum(func(x interface{}) interface{} {
							return x.(MaintenanceCost).PeriodTotalActual
						}).Exec().Result.Sum
						_, e := ctx.InsertOut(d)
						tk.Println("#")
						if e != nil {
							tk.Println(e)
							break
						}

					}

				}
			}
		}
	}
	return e
}
コード例 #19
0
ファイル: dataflow.go プロジェクト: eaciit/colony-manager
func (a *DataFlowController) GetDataMonitoring(r *knot.WebContext) interface{} {
	r.Config.OutputType = knot.OutputJson

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

	status := tk.ToString(payload["status"])

	filters := []*dbox.Filter{}
	var filter *dbox.Filter
	filter = new(dbox.Filter)

	if strings.Contains(strings.ToLower(status), "run") {
		filters = append(filters, dbox.Eq("status", "RUN"))
	} else {
		filters = append(filters, dbox.Ne("status", "RUN"))
	}

	take := tk.ToInt(payload["take"], tk.RoundingAuto)
	skip := tk.ToInt(payload["skip"], tk.RoundingAuto)

	start := tk.ToString(payload["startdate"])
	end := tk.ToString(payload["enddate"])

	search := tk.ToString(payload["search"])

	startdate := time.Now()
	enddate := time.Now()

	if start != "" {
		startdate, _ = time.Parse(time.RFC3339, start)
		filters = append(filters, dbox.Gte("startdate", startdate))
		startdate = startdate.AddDate(0, 0, 1)
		startdate = startdate.Add(time.Duration(-1) * time.Second)
		filters = append(filters, dbox.Lte("startdate", startdate))
	}

	if end != "" && !strings.Contains(strings.ToLower(status), "run") {
		enddate, _ = time.Parse(time.RFC3339, end)
		filters = append(filters, dbox.Gte("enddate", enddate))
		enddate = enddate.AddDate(0, 0, 1)
		enddate = enddate.Add(time.Duration(-1) * time.Second)
		filters = append(filters, dbox.Lte("enddate", enddate))
	}

	if search != "" {
		filters = append(filters, dbox.Or(dbox.Contains("flow.name", search), dbox.Contains("flow.description", search)))
	}

	filter = dbox.And(filters...)
	dataDs := []colonycore.DataFlowProcess{}
	cursor, err := colonycore.Finds(new(colonycore.DataFlowProcess), tk.M{}.Set("where", filter).Set("take", take).Set("skip", skip).Set("order", []string{"-startdate"}))
	cursorCount, _ := colonycore.Finds(new(colonycore.DataFlowProcess), tk.M{}.Set("where", filter))
	res := tk.M{}
	if cursor != nil {
		cursor.Fetch(&dataDs, 0, false)
		defer cursor.Close()
		defer cursorCount.Close()
		res.Set("total", cursorCount.Count())
	} else {
		res.Set("total", 0)
	}

	if err != nil && cursor != nil {
		return helper.CreateResult(false, nil, err.Error())
	}

	res.Set("data", dataDs)

	return helper.CreateResult(true, res, "success")
}