task.go 75.6 KB
Newer Older
brent's avatar
brent committed
1 2 3
package controllers

import (
brent's avatar
brent committed
4
	"ai_developer_admin/libs/cronjob"
brent's avatar
brent committed
5 6 7 8
	"ai_developer_admin/libs/mysql"
	"ai_developer_admin/libs/odysseus"
	"ai_developer_admin/libs/postgres"
	"ai_developer_admin/libs/redis"
brent's avatar
brent committed
9
	"ai_developer_admin/libs/utils"
brent's avatar
brent committed
10 11 12
	"ai_developer_admin/models"
	"encoding/json"
	"fmt"
brent's avatar
brent committed
13
	"github.com/beego/beego/orm"
brent's avatar
brent committed
14
	"github.com/beego/beego/v2/core/logs"
brent's avatar
brent committed
15
	"github.com/odysseus/cache/model"
brent's avatar
brent committed
16
	"net/http"
brent's avatar
brent committed
17
	"sort"
brent's avatar
brent committed
18
	"strconv"
brent's avatar
brent committed
19
	"strings"
brent's avatar
brent committed
20 21 22 23
	"time"
)

var format = "2006-01-02T15:04:05.000000Z"
brent's avatar
brent committed
24
var layout = "2006-01-02T15:04:05"
brent's avatar
brent committed
25 26 27 28 29 30 31 32 33 34 35

type TaskController struct {
	MainController
}

func (server *TaskController) Bills() {
	info, err := server.Check()
	if err != nil {
		server.respond(http.StatusUnauthorized, err.Error())
		return
	}
brent's avatar
brent committed
36

brent's avatar
brent committed
37 38 39 40
	body := server.Ctx.Input.RequestBody
	appRequest := models.AppRequest{}
	err = json.Unmarshal(body, &appRequest) //解析body中数据
	logs.Debug("appRequest", appRequest)
brent's avatar
brent committed
41

brent's avatar
brent committed
42
	currentTime := time.Now()
brent's avatar
brent committed
43
	if appRequest.EndTime == "" {
brent's avatar
brent committed
44
		endTime := time.Date(currentTime.Year(), currentTime.Month(), currentTime.Day(), 23, 59, 59, 0, time.UTC)
brent's avatar
brent committed
45
		appRequest.EndTime = fmt.Sprintf(endTime.Format(format))
brent's avatar
brent committed
46
	}
brent's avatar
brent committed
47
	if appRequest.StartTime == "" {
brent's avatar
brent committed
48 49 50
		temp := fmt.Sprintf("-%dh", 24*7)
		m, _ := time.ParseDuration(temp)
		tempTime := currentTime.Add(m)
brent's avatar
brent committed
51
		tempTime = time.Date(tempTime.Year(), tempTime.Month(), tempTime.Day(), 0, 0, 0, 0, time.UTC)
brent's avatar
brent committed
52
		appRequest.StartTime = fmt.Sprintf(tempTime.Format(format))
brent's avatar
brent committed
53
	}
brent's avatar
brent committed
54 55
	startTimeIn, _ := time.Parse(layout, appRequest.StartTime)
	endTimeIn, _ := time.Parse(layout, appRequest.EndTime)
brent's avatar
brent committed
56 57 58 59 60 61 62
	if appRequest.Page == 0 {
		appRequest.Page = 1
	}
	if appRequest.Size == 0 {
		appRequest.Size = 10
	}
	offset := (appRequest.Page - 1) * appRequest.Size
brent's avatar
brent committed
63
	size := appRequest.Page * appRequest.Size
brent's avatar
brent committed
64

brent's avatar
brent committed
65
	if endTimeIn.Before(startTimeIn) {
brent's avatar
brent committed
66
		server.respond(models.BusinessFailed, "Start time cannot be greater than end time")
brent's avatar
brent committed
67 68
		return
	}
brent's avatar
brent committed
69 70
	startTime := fmt.Sprintf(startTimeIn.Format(format))
	endTime := fmt.Sprintf(endTimeIn.Format(format))
brent's avatar
brent committed
71

brent's avatar
brent committed
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
	countQB, _ := orm.NewQueryBuilder("mysql")
	countQB.Select("count(*)").
		From("bills").Where("worker_acc != ''")

	queryQB, _ := orm.NewQueryBuilder("mysql")
	queryQB.Select("sum(fee) AS fee", "time").
		From("bills").Where("worker_acc != ''")

	//Where("worker_acc != ''")
	if info.Role != 1 && info.Role != 2 {
		countQB.And(fmt.Sprintf("uid = '%d'", info.UserID))
		queryQB.And(fmt.Sprintf("uid = '%d'", info.UserID))
	}
	countQB.And(fmt.Sprintf("time >= '%s'", startTime)).And(fmt.Sprintf("time <= '%s'", endTime))
	queryQB.And(fmt.Sprintf("time >= '%s'", startTime)).And(fmt.Sprintf("time <= '%s'", endTime))
	sql := fmt.Sprintf("%s SAMPLE BY 1M ALIGN TO CALENDAR;", countQB.String())

brent's avatar
brent committed
89
	total, err := postgres.QueryTotal(sql)
brent's avatar
brent committed
90 91 92 93
	if err != nil {
		server.respond(models.BusinessFailed, err.Error())
		return
	}
brent's avatar
brent committed
94 95 96 97 98 99 100 101 102 103 104 105 106
	logs.Debug("total = %d", total)
	var responseTasks []models.Bills
	if total == 0 {
		responseData := struct {
			Total int64       `json:"total"`
			Data  interface{} `json:"data,omitempty"`
		}{
			Total: total,
			Data:  responseTasks,
		}
		server.respond(http.StatusOK, "", responseData)
		return
	}
brent's avatar
brent committed
107

brent's avatar
brent committed
108 109
	queryQB.OrderBy("time").Desc()
	sql = fmt.Sprintf("%s SAMPLE BY 1M ALIGN TO CALENDAR LIMIT %d,%d;", queryQB.String(), offset, size)
brent's avatar
brent committed
110 111 112 113 114 115 116 117 118 119 120 121 122
	counts, err := postgres.CountTasks(sql)
	if err != nil {
		server.respond(models.BusinessFailed, err.Error())
		return
	}
	responseData := struct {
		Total int64       `json:"total"`
		Data  interface{} `json:"data,omitempty"`
	}{
		Total: total,
		Data:  counts,
	}
	server.respond(http.StatusOK, "", responseData)
brent's avatar
brent committed
123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142
}

func (server *TaskController) BillDetails() {
	info, err := server.Check()
	if err != nil {
		server.respond(http.StatusUnauthorized, err.Error())
		return
	}
	body := server.Ctx.Input.RequestBody
	appRequest := models.AppRequest{}
	err = json.Unmarshal(body, &appRequest) //解析body中数据
	logs.Debug("appRequest", appRequest)

	if appRequest.Page == 0 {
		appRequest.Page = 1
	}
	if appRequest.Size == 0 {
		appRequest.Size = 10
	}
	offset := (appRequest.Page - 1) * appRequest.Size
brent's avatar
brent committed
143
	size := appRequest.Page * appRequest.Size
brent's avatar
brent committed
144

brent's avatar
brent committed
145 146
	countQB, _ := orm.NewQueryBuilder("mysql")
	countQB.Select("count(*)").
brent's avatar
brent committed
147 148
		From("bills").Where("worker_acc != ''").
		And("uid != '0'")
brent's avatar
brent committed
149 150 151

	queryQB, _ := orm.NewQueryBuilder("mysql")
	queryQB.Select("id", "fee", "type", "time", "result").
brent's avatar
brent committed
152
		From("bills").Where("worker_acc != ''").
brent's avatar
brent committed
153
		And("uid != '0'")
brent's avatar
brent committed
154 155 156 157 158 159

	if info.Role != 1 && info.Role != 2 {
		countQB.And(fmt.Sprintf("uid = '%d'", info.UserID))
		queryQB.And(fmt.Sprintf("uid = '%d'", info.UserID))
	}

brent's avatar
brent committed
160 161
	if appRequest.StartTime != "" && appRequest.EndTime != "" {
		temp, _ := time.Parse(layout, appRequest.StartTime)
brent's avatar
brent committed
162
		startTime := fmt.Sprintf(temp.Format(format))
brent's avatar
brent committed
163
		temp, _ = time.Parse(layout, appRequest.EndTime)
brent's avatar
brent committed
164 165 166 167 168 169 170 171 172 173 174 175 176
		endTime := fmt.Sprintf(temp.Format(format))
		countQB.And(fmt.Sprintf("time >= '%s'", startTime)).And(fmt.Sprintf("time <= '%s'", endTime))
		queryQB.And(fmt.Sprintf("time >= '%s'", startTime)).And(fmt.Sprintf("time <= '%s'", endTime))
	}
	if appRequest.FeeCondition != 0 {
		if appRequest.FeeCondition == int(models.FeeFree) {
			countQB.And("fee <= 0")
			queryQB.And("fee <= 0")
		}
		if appRequest.FeeCondition == int(models.FeeBased) {
			countQB.And("fee > 0")
			queryQB.And("fee > 0")
		}
brent's avatar
brent committed
177
	}
brent's avatar
brent committed
178

brent's avatar
brent committed
179
	sql := countQB.String()
brent's avatar
brent committed
180
	total, err := postgres.QueryTotal(sql)
brent's avatar
brent committed
181 182 183 184
	if err != nil {
		server.respond(models.BusinessFailed, err.Error())
		return
	}
brent's avatar
brent committed
185
	logs.Debug("total = %d", total)
brent's avatar
brent committed
186
	var responseTasks []models.Bills
brent's avatar
brent committed
187 188 189 190 191 192 193 194 195 196 197 198
	if total == 0 {
		responseData := struct {
			Total int64       `json:"total"`
			Data  interface{} `json:"data,omitempty"`
		}{
			Total: total,
			Data:  responseTasks,
		}
		server.respond(http.StatusOK, "", responseData)
		return
	}

brent's avatar
brent committed
199 200 201
	//qb.OrderBy("time").Desc().Offset(int(offset)).Limit(int(size))
	queryQB.OrderBy("time").Desc()
	sql = fmt.Sprintf("%s LIMIT %d,%d;", queryQB.String(), offset, size)
brent's avatar
brent committed
202 203 204 205 206
	data, err := postgres.QueryBills(sql)
	if err != nil {
		server.respond(models.BusinessFailed, err.Error())
		return
	}
brent's avatar
brent committed
207 208 209 210 211 212 213 214
	for _, task := range data {
		apiPath := ""
		desc := ""
		taskId, err := strconv.Atoi(task.Type)
		if err == nil {
			taskType, err1 := odysseus.GetTaskType(int64(taskId))
			if err1 == nil {
				apiPath = taskType.ApiPath
brent's avatar
brent committed
215
				//desc = taskType.Desc
brent's avatar
brent committed
216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232
			}
		}

		balance, _ := odysseus.GetUserBalance(int64(info.UserID))

		reTask := models.Bills{
			Id:      task.Id,
			Type:    "txt2Img",
			Fee:     task.Fee,
			Time:    task.Time,
			Result:  task.Result,
			ApiPath: apiPath,
			Desc:    desc,
			Balance: balance,
		}
		responseTasks = append(responseTasks, reTask)
	}
brent's avatar
brent committed
233 234 235 236 237 238 239 240
	responseData := struct {
		Total int64       `json:"total"`
		Data  interface{} `json:"data,omitempty"`
	}{
		Total: total,
		Data:  responseTasks,
	}
	server.respond(http.StatusOK, "", responseData)
brent's avatar
brent committed
241 242 243 244 245 246 247 248 249 250 251 252
}

func (server *TaskController) Tasks() {
	//info, err := server.Check()
	//if err != nil {
	//	server.respond(http.StatusUnauthorized, err.Error())
	//	return
	//}

	body := server.Ctx.Input.RequestBody
	appRequest := models.AppRequest{}
	err := json.Unmarshal(body, &appRequest) //解析body中数据
brent's avatar
brent committed
253
	logs.Debug("appRequest", appRequest, string(body))
brent's avatar
brent committed
254 255 256 257 258 259 260 261

	if appRequest.Page == 0 {
		appRequest.Page = 1
	}
	if appRequest.Size == 0 {
		appRequest.Size = 10
	}
	offset := (appRequest.Page - 1) * appRequest.Size
brent's avatar
brent committed
262
	size := appRequest.Page * appRequest.Size
brent's avatar
brent committed
263
	if appRequest.StartTime == "" && appRequest.EndTime != "" {
brent's avatar
brent committed
264
		server.respond(models.MissingParameter, "Missing start time")
brent's avatar
brent committed
265 266
		return
	}
brent's avatar
brent committed
267
	if appRequest.StartTime != "" && appRequest.EndTime == "" {
brent's avatar
brent committed
268
		server.respond(models.MissingParameter, "Missing end time")
brent's avatar
brent committed
269 270
		return
	}
brent's avatar
brent committed
271 272 273 274 275 276 277 278 279

	countQB, _ := orm.NewQueryBuilder("mysql")
	countQB.Select("count(*)").
		From("bills").Where("worker_acc != ''")

	queryQB, _ := orm.NewQueryBuilder("mysql")
	queryQB.Select("id", "fee", "type", "time", "exec_duration", "workload", "profit_acc", "worker_acc", "result").
		From("bills").Where("worker_acc != ''")

brent's avatar
brent committed
280
	if appRequest.StartTime != "" && appRequest.EndTime != "" {
brent's avatar
brent committed
281 282 283 284 285
		start, _ := time.Parse(layout, appRequest.StartTime)
		startTime := fmt.Sprintf(start.Format(format))
		end, _ := time.Parse(layout, appRequest.EndTime)
		endTime := fmt.Sprintf(end.Format(format))
		if end.Before(start) {
brent's avatar
brent committed
286
			server.respond(models.BusinessFailed, "Start time cannot be greater than end time")
brent's avatar
brent committed
287
			return
brent's avatar
brent committed
288
		}
brent's avatar
brent committed
289 290
		countQB.And(fmt.Sprintf("time >= '%s'", startTime)).And(fmt.Sprintf("time <= '%s'", endTime))
		queryQB.And(fmt.Sprintf("time >= '%s'", startTime)).And(fmt.Sprintf("time <= '%s'", endTime))
brent's avatar
brent committed
291 292
	}
	if appRequest.ProfitAcc != "" {
brent's avatar
brent committed
293 294
		countQB.And(fmt.Sprintf("profit_acc = '%s'", appRequest.ProfitAcc))
		queryQB.And(fmt.Sprintf("profit_acc = '%s'", appRequest.ProfitAcc))
brent's avatar
brent committed
295 296
	}
	if appRequest.WorkerAcc != "" {
brent's avatar
brent committed
297 298
		countQB.And(fmt.Sprintf("worker_acc = '%s'", appRequest.WorkerAcc))
		queryQB.And(fmt.Sprintf("worker_acc = '%s'", appRequest.WorkerAcc))
brent's avatar
brent committed
299 300
	}

brent's avatar
brent committed
301
	sql := countQB.String()
brent's avatar
brent committed
302
	total, err := postgres.QueryTotal(sql)
brent's avatar
brent committed
303 304 305 306
	if err != nil {
		server.respond(models.BusinessFailed, err.Error())
		return
	}
brent's avatar
brent committed
307
	logs.Debug("total = %d", total)
brent's avatar
brent committed
308
	var responseTasks []models.Bills
brent's avatar
brent committed
309 310 311 312 313 314 315 316 317 318 319 320
	if total == 0 {
		responseData := struct {
			Total int64       `json:"total"`
			Data  interface{} `json:"data,omitempty"`
		}{
			Total: total,
			Data:  responseTasks,
		}
		server.respond(http.StatusOK, "", responseData)
		return
	}

brent's avatar
brent committed
321 322
	queryQB.OrderBy("time").Desc()
	sql = fmt.Sprintf("%s LIMIT %d,%d;", queryQB.String(), offset, size)
brent's avatar
brent committed
323 324 325 326 327 328
	data, err := postgres.QueryBills(sql)
	if err != nil {
		server.respond(models.BusinessFailed, err.Error())
		return
	}

brent's avatar
brent committed
329 330
	for _, task := range data {
		apiPath := ""
brent's avatar
brent committed
331 332 333 334
		model := ""
		baseModel := ""
		kind := 1
		typeDe := 1
brent's avatar
brent committed
335 336
		taskId, err := strconv.Atoi(task.Type)
		if err == nil {
brent's avatar
brent committed
337 338
			taskType, _ := odysseus.GetTaskType(int64(taskId))
			if taskType != nil {
brent's avatar
brent committed
339
				apiPath = taskType.ApiPath
brent's avatar
brent committed
340 341 342 343
				model = taskType.Model
				baseModel = taskType.BaseModel
				kind = taskType.Kind
				typeDe = taskType.Type
brent's avatar
brent committed
344 345 346 347 348
			}
		}

		reTask := models.Bills{
			Id:        task.Id,
brent's avatar
brent committed
349
			Type:      models.ModelType(typeDe).String(),
brent's avatar
brent committed
350 351 352
			Time:      task.Time,
			Result:    task.Result,
			ApiPath:   apiPath,
brent's avatar
brent committed
353 354
			Model:     model,
			BaseModel: baseModel,
brent's avatar
brent committed
355
			Kind:      models.TaskKind(kind).EnString(),
brent's avatar
brent committed
356
			//Desc:      desc,
brent's avatar
brent committed
357 358 359 360 361 362
			Workload:  task.Workload,
			ProfitAcc: task.ProfitAcc,
			WorkerAcc: task.WorkerAcc,
		}
		responseTasks = append(responseTasks, reTask)
	}
brent's avatar
brent committed
363 364 365 366 367 368 369 370
	responseData := struct {
		Total int64       `json:"total"`
		Data  interface{} `json:"data,omitempty"`
	}{
		Total: total,
		Data:  responseTasks,
	}
	server.respond(http.StatusOK, "", responseData)
brent's avatar
brent committed
371 372
}

brent's avatar
brent committed
373 374 375 376 377
func (server *TaskController) TasksPerDay() {
	body := server.Ctx.Input.RequestBody
	appRequest := models.AppRequest{}
	err := json.Unmarshal(body, &appRequest) //解析body中数据
	logs.Debug("appRequest", appRequest)
brent's avatar
brent committed
378 379 380 381
	//if err != nil {
	//	server.respond(models.NoRequestBody, err.Error())
	//	return
	//}
brent's avatar
brent committed
382
	if appRequest.StartTime == "" && appRequest.EndTime != "" {
brent's avatar
brent committed
383
		server.respond(models.MissingParameter, "Missing start time")
brent's avatar
brent committed
384 385 386
		return
	}
	if appRequest.StartTime != "" && appRequest.EndTime == "" {
brent's avatar
brent committed
387
		server.respond(models.MissingParameter, "Missing end time")
brent's avatar
brent committed
388 389 390 391 392 393 394 395
		return
	}
	tempLayout := layout
	if appRequest.EndTime == "" && appRequest.StartTime == "" {
		tempLayout = format
	}
	currentTime := time.Now()
	if appRequest.EndTime == "" {
brent's avatar
brent committed
396
		endTime := time.Date(currentTime.Year(), currentTime.Month(), currentTime.Day(), 23, 59, 59, 0, time.UTC)
brent's avatar
brent committed
397 398 399 400 401 402
		appRequest.EndTime = fmt.Sprintf(endTime.Format(format))
	}
	if appRequest.StartTime == "" {
		temp := fmt.Sprintf("-%dh", 24*7)
		m, _ := time.ParseDuration(temp)
		tempTime := currentTime.Add(m)
brent's avatar
brent committed
403
		tempTime = time.Date(tempTime.Year(), tempTime.Month(), tempTime.Day(), 0, 0, 0, 0, time.UTC)
brent's avatar
brent committed
404 405 406 407 408 409
		appRequest.StartTime = fmt.Sprintf(tempTime.Format(format))
	}
	startTimeIn, _ := time.Parse(tempLayout, appRequest.StartTime)
	endTimeIn, _ := time.Parse(tempLayout, appRequest.EndTime)

	if endTimeIn.Before(startTimeIn) {
brent's avatar
brent committed
410
		server.respond(models.BusinessFailed, "Start time cannot be greater than end time")
brent's avatar
brent committed
411 412
		return
	}
brent's avatar
brent committed
413 414
	startTimeIn = time.Date(startTimeIn.Year(), startTimeIn.Month(), startTimeIn.Day(), 0, 0, 0, 0, time.UTC)
	endTimeIn = time.Date(endTimeIn.Year(), endTimeIn.Month(), endTimeIn.Day(), 23, 59, 59, 0, time.UTC)
brent's avatar
brent committed
415

brent's avatar
brent committed
416 417 418 419 420 421 422 423 424 425 426 427
	startTime := fmt.Sprintf(startTimeIn.Format(format))
	endTime := fmt.Sprintf(endTimeIn.Format(format))

	countQB, _ := orm.NewQueryBuilder("mysql")
	countQB.Select("count(*)", "time").
		From("bills").Where("worker_acc != ''")

	//queryQB, _ := orm.NewQueryBuilder("mysql")
	//queryQB.Select("sum(fee) AS fee", "time").
	//	From("bills").Where("worker_acc != ''")
	countQB.And(fmt.Sprintf("time >= '%s'", startTime)).And(fmt.Sprintf("time <= '%s'", endTime))
	//queryQB.And(fmt.Sprintf("time >= '%s'", startTime)).And(fmt.Sprintf("time <= '%s'", endTime))
brent's avatar
brent committed
428
	if appRequest.ProfitAcc != "" {
brent's avatar
brent committed
429 430
		countQB.And(fmt.Sprintf("profit_acc = '%s'", appRequest.ProfitAcc))
		//queryQB.And(fmt.Sprintf("profit_acc = '%s'", appRequest.ProfitAcc))
brent's avatar
brent committed
431 432
	}
	if appRequest.WorkerAcc != "" {
brent's avatar
brent committed
433 434
		countQB.And(fmt.Sprintf("worker_acc = '%s'", appRequest.WorkerAcc))
		//queryQB.And(fmt.Sprintf("worker_acc = '%s'", appRequest.WorkerAcc))
brent's avatar
brent committed
435
	}
brent's avatar
brent committed
436
	sql := fmt.Sprintf("%s SAMPLE BY 1d ALIGN TO CALENDAR;", countQB.String())
brent's avatar
brent committed
437

brent's avatar
brent committed
438
	endDateIn := time.Date(endTimeIn.Year(), endTimeIn.Month(), endTimeIn.Day(), 0, 0, 0, 0, time.UTC)
brent's avatar
brent committed
439 440
	endDate := fmt.Sprintf(endDateIn.Format(format))
	dates := utils.SplitDate(startTime, endDate, format)
brent's avatar
brent committed
441 442

	//sql := fmt.Sprintf("SELECT time,count(*) FROM bills WHERE worker_acc != '' and time >= '%s' and time <= '%s' %s SAMPLE BY 1d ALIGN TO CALENDAR;", startTime, endTime, timeCondition)
brent's avatar
brent committed
443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459
	counts, err := postgres.CountTasks(sql)
	if err != nil {
		server.respond(models.BusinessFailed, err.Error())
		return
	}
	for _, value := range dates {
		tempDate := findTime(counts, value)
		if tempDate != nil {
			reTask := models.TaskCount{
				Type:    "0",
				Time:    *tempDate,
				Count:   "0",
				ApiPath: "",
			}
			counts = append(counts, reTask)
		}
	}
brent's avatar
brent committed
460 461 462
	sort.Slice(counts, func(i, j int) bool {
		return counts[i].Time.Before(counts[j].Time)
	})
brent's avatar
brent committed
463 464 465
	server.respond(http.StatusOK, "", counts)
}

brent's avatar
brent committed
466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483
func (server *TaskController) UserTasks() {
	info, err := server.Check()
	if err != nil {
		server.respond(http.StatusUnauthorized, err.Error())
		return
	}
	body := server.Ctx.Input.RequestBody
	appRequest := models.AppRequest{}
	err = json.Unmarshal(body, &appRequest) //解析body中数据
	logs.Debug("appRequest", appRequest)

	if appRequest.Page == 0 {
		appRequest.Page = 1
	}
	if appRequest.Size == 0 {
		appRequest.Size = 10
	}
	offset := (appRequest.Page - 1) * appRequest.Size
brent's avatar
brent committed
484
	size := appRequest.Page * appRequest.Size
brent's avatar
brent committed
485

brent's avatar
brent committed
486 487 488 489 490 491 492 493 494 495 496
	countQB, _ := orm.NewQueryBuilder("mysql")
	countQB.Select("count(*)").
		From("tasks")

	queryQB, _ := orm.NewQueryBuilder("mysql")
	queryQB.Select("id", "type", "time", "fee", "in_len").
		From("tasks")
	if info.Role != 1 && info.Role != 2 {
		countQB.Where(fmt.Sprintf("uid = '%d'", info.UserID))
		queryQB.Where(fmt.Sprintf("uid = '%d'", info.UserID))
	}
brent's avatar
brent committed
497 498
	if appRequest.StartTime != "" && appRequest.EndTime != "" {
		temp, _ := time.Parse(layout, appRequest.StartTime)
brent's avatar
brent committed
499
		startTime := fmt.Sprintf(temp.Format(format))
brent's avatar
brent committed
500
		temp, _ = time.Parse(layout, appRequest.EndTime)
brent's avatar
brent committed
501 502 503 504 505 506 507 508
		endTime := fmt.Sprintf(temp.Format(format))
		if info.Role == 1 || info.Role == 2 {
			countQB.Where(fmt.Sprintf("time >= '%s'", startTime)).And(fmt.Sprintf("time <= '%s'", endTime))
			queryQB.Where(fmt.Sprintf("time >= '%s'", startTime)).And(fmt.Sprintf("time <= '%s'", endTime))
		} else {
			countQB.And(fmt.Sprintf("time >= '%s'", startTime)).And(fmt.Sprintf("time <= '%s'", endTime))
			queryQB.And(fmt.Sprintf("time >= '%s'", startTime)).And(fmt.Sprintf("time <= '%s'", endTime))
		}
brent's avatar
brent committed
509
	}
brent's avatar
brent committed
510 511 512 513 514 515 516 517

	sql := countQB.String()

	//sql := fmt.Sprintf("%s SAMPLE BY 1d ALIGN TO CALENDAR;", countQB.String())
	//sql := fmt.Sprintf("SELECT count(*) FROM tasks WHERE uid='%d'%s%s;", info.UserID, cond, timeCondition)
	//if info.Role == 1 || info.Role == 2 {
	//	sql = fmt.Sprintf("SELECT count(*) FROM tasks WHERE %s;", timeCondition)
	//}
brent's avatar
brent committed
518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534
	total, err := postgres.QueryTotal(sql)
	if err != nil {
		server.respond(models.BusinessFailed, err.Error())
		return
	}
	var responseTasks []models.Bills
	if total == 0 {
		responseData := struct {
			Total int64       `json:"total"`
			Data  interface{} `json:"data,omitempty"`
		}{
			Total: total,
			Data:  responseTasks,
		}
		server.respond(http.StatusOK, "", responseData)
		return
	}
brent's avatar
brent committed
535 536 537

	queryQB.OrderBy("time").Desc()
	sql = fmt.Sprintf("%s  LIMIT %d,%d;", queryQB.String(), offset, size)
brent's avatar
brent committed
538
	//qb.Select("id", "type", "time", "fee", "in_len").From("tasks").Where("uid=?").And("time>='?'").And("time<='?").OrderBy("time").Desc().Offset(int(offset)).Limit(int(appRequest.Size))
brent's avatar
brent committed
539 540 541 542
	//sql = fmt.Sprintf("SELECT id,type,time,fee,in_len FROM tasks WHERE uid='%d'%s%s ORDER BY time DESC LIMIT %d,%d;", info.UserID, cond, timeCondition, offset, size)
	//if info.Role == 1 || info.Role == 2 {
	//	sql = fmt.Sprintf("SELECT id,type,time,fee,in_len FROM tasks WHERE %s ORDER BY time DESC LIMIT %d,%d;", timeCondition, offset, size)
	//}
brent's avatar
brent committed
543 544 545 546 547 548
	tasks, err := postgres.QueryBills(sql)
	if err != nil {
		server.respond(models.BusinessFailed, err.Error())
		return
	}
	if len(tasks) <= 0 {
brent's avatar
brent committed
549
		server.respond(models.BusinessFailed, "no data")
brent's avatar
brent committed
550 551
		return
	}
brent's avatar
brent committed
552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569
	ids := ""
	for _, value := range tasks {
		ids = ids + "'" + value.Id + "'" + ","
	}
	ids = ids[:len(ids)-1]
	queryBillQB, _ := orm.NewQueryBuilder("mysql")
	queryBillQB.Select("id", "result", "time", "fee", "out_len", "task_duration").
		From("bills").Where(fmt.Sprintf("id IN(%s)", ids)).OrderBy("time").Desc()
	sql = fmt.Sprintf("%s LIMIT %d,%d;", queryBillQB.String(), offset, size)

	//first := tasks[0]
	//logs.Debug("first = ", first.Time)
	//fmt.Printf("time = %s\n", first.Time)
	//fmt.Printf("format = %s\n", first.Time.Format(format))
	//startTime = fmt.Sprintf(first.Time.Format(format))
	//last := tasks[len(tasks)-1]
	//endTime = fmt.Sprintf(last.Time.Format(format))
	//timeCondition = fmt.Sprintf(" and  time >= '%s' and time <= '%s'", endTime, startTime)
brent's avatar
brent committed
570 571 572

	//qb.Select("id", "out_len", "time", "fee", "result", "duration").From("bills").Where("uid=?").And("time>='?'").And("time<='?").OrderBy("time").Desc().Offset(int(offset)).Limit(int(appRequest.Size))

brent's avatar
brent committed
573
	//sql = fmt.Sprintf("SELECT id,time,fee,out_len,result,task_duration  FROM bills %s ORDER BY time DESC LIMIT %d,%d;", timeCondition, offset, size)
brent's avatar
brent committed
574 575 576 577 578 579
	bills, err := postgres.QueryBills(sql)
	if err != nil {
		server.respond(models.BusinessFailed, err.Error())
		return
	}

brent's avatar
brent committed
580
	for _, task := range tasks {
brent's avatar
brent committed
581 582 583 584 585 586 587
		apiPath := ""
		desc := ""
		taskId, err := strconv.Atoi(task.Type)
		if err == nil {
			taskType, err1 := odysseus.GetTaskType(int64(taskId))
			if err1 == nil {
				apiPath = taskType.ApiPath
brent's avatar
brent committed
588
				//desc = taskType.Desc
brent's avatar
brent committed
589 590 591
			}
		}

brent's avatar
brent committed
592 593
		bill := findBills(bills, task.Id)

brent's avatar
brent committed
594 595 596 597 598
		reTask := models.Bills{
			Id:           task.Id,
			Type:         task.Type,
			Time:         task.Time,
			InLen:        task.InLen,
brent's avatar
brent committed
599 600 601 602
			OutLen:       bill.OutLen,
			TaskDuration: bill.TaskDuration,
			Result:       bill.Result,
			Fee:          bill.Fee,
brent's avatar
brent committed
603 604 605 606 607 608
			ApiPath:      apiPath,
			Desc:         desc,
		}
		responseTasks = append(responseTasks, reTask)
	}

brent's avatar
brent committed
609 610 611 612 613 614 615 616
	responseData := struct {
		Total int64       `json:"total"`
		Data  interface{} `json:"data,omitempty"`
	}{
		Total: total,
		Data:  responseTasks,
	}
	server.respond(http.StatusOK, "", responseData)
brent's avatar
brent committed
617 618
}

brent's avatar
brent committed
619 620 621 622 623 624 625 626 627
func findBills(bills []models.Bills, id string) models.Bills {
	for _, value := range bills {
		if strings.Compare(value.Id, id) == 0 {
			return value
		}
	}
	return models.Bills{}
}

brent's avatar
brent committed
628 629 630 631 632 633 634 635 636 637
func (server *TaskController) UserTasksPerDay() {
	info, err := server.Check()
	if err != nil {
		server.respond(http.StatusUnauthorized, err.Error())
		return
	}
	body := server.Ctx.Input.RequestBody
	appRequest := models.AppRequest{}
	err = json.Unmarshal(body, &appRequest) //解析body中数据
	logs.Debug("appRequest", appRequest)
brent's avatar
brent committed
638 639 640 641
	//if err != nil {
	//	server.respond(models.NoRequestBody, err.Error())
	//	return
	//}
brent's avatar
brent committed
642
	if appRequest.StartTime == "" && appRequest.EndTime != "" {
brent's avatar
brent committed
643
		server.respond(models.MissingParameter, "Missing start time")
brent's avatar
brent committed
644 645 646
		return
	}
	if appRequest.StartTime != "" && appRequest.EndTime == "" {
brent's avatar
brent committed
647
		server.respond(models.MissingParameter, "Missing end time")
brent's avatar
brent committed
648 649 650 651 652 653
		return
	}
	tempLayout := layout
	if appRequest.EndTime == "" && appRequest.StartTime == "" {
		tempLayout = format
	}
brent's avatar
brent committed
654
	currentTime := time.Now()
brent's avatar
brent committed
655
	if appRequest.EndTime == "" {
brent's avatar
brent committed
656
		endTime := time.Date(currentTime.Year(), currentTime.Month(), currentTime.Day(), 23, 59, 59, 0, time.UTC)
brent's avatar
brent committed
657
		appRequest.EndTime = fmt.Sprintf(endTime.Format(format))
brent's avatar
brent committed
658
	}
brent's avatar
brent committed
659
	if appRequest.StartTime == "" {
brent's avatar
brent committed
660 661 662
		temp := fmt.Sprintf("-%dh", 24*7)
		m, _ := time.ParseDuration(temp)
		tempTime := currentTime.Add(m)
brent's avatar
brent committed
663
		tempTime = time.Date(tempTime.Year(), tempTime.Month(), tempTime.Day(), 0, 0, 0, 0, time.UTC)
brent's avatar
brent committed
664
		appRequest.StartTime = fmt.Sprintf(tempTime.Format(format))
brent's avatar
brent committed
665
	}
brent's avatar
brent committed
666 667
	startTimeIn, _ := time.Parse(tempLayout, appRequest.StartTime)
	endTimeIn, _ := time.Parse(tempLayout, appRequest.EndTime)
brent's avatar
brent committed
668

brent's avatar
brent committed
669
	if endTimeIn.Before(startTimeIn) {
brent's avatar
brent committed
670
		server.respond(models.BusinessFailed, "Start time cannot be greater than end time")
brent's avatar
brent committed
671 672 673
		return
	}

brent's avatar
brent committed
674 675
	startTime := fmt.Sprintf(startTimeIn.Format(format))
	endTime := fmt.Sprintf(endTimeIn.Format(format))
brent's avatar
brent committed
676 677 678 679 680 681 682 683 684

	countQB, _ := orm.NewQueryBuilder("mysql")
	countQB.Select("count(*)", "time").
		From("tasks").Where(fmt.Sprintf("time >= '%s'", startTime)).And(fmt.Sprintf("time <= '%s'", endTime))
	if info.Role != 1 && info.Role != 2 {
		countQB.And(fmt.Sprintf("uid = %d", info.UserID))
	}
	sql := fmt.Sprintf("%s SAMPLE BY 1d ALIGN TO CALENDAR;", countQB.String())

brent's avatar
brent committed
685
	endDateIn := time.Date(endTimeIn.Year(), endTimeIn.Month(), endTimeIn.Day(), 0, 0, 0, 0, time.UTC)
brent's avatar
brent committed
686 687
	endDate := fmt.Sprintf(endDateIn.Format(format))
	dates := utils.SplitDate(startTime, endDate, format)
brent's avatar
brent committed
688 689 690 691
	//sql := fmt.Sprintf("SELECT time,count(*) FROM tasks WHERE uid='%d' and time >= '%s' and time <= '%s' SAMPLE BY 1d ALIGN TO CALENDAR;", info.UserID, startTime, endTime)
	//if info.Role == 1 || info.Role == 2 {
	//	sql = fmt.Sprintf("SELECT time,count(*) FROM tasks WHERE time >= '%s' and time <= '%s' SAMPLE BY 1d ALIGN TO CALENDAR;", startTime, endTime)
	//}
brent's avatar
brent committed
692 693 694 695 696
	counts, err := postgres.CountTasks(sql)
	if err != nil {
		server.respond(models.BusinessFailed, err.Error())
		return
	}
brent's avatar
brent committed
697 698 699 700 701 702 703 704 705 706 707 708
	for _, value := range dates {
		tempDate := findTime(counts, value)
		if tempDate != nil {
			reTask := models.TaskCount{
				Type:    "0",
				Time:    *tempDate,
				Count:   "0",
				ApiPath: "",
			}
			counts = append(counts, reTask)
		}
	}
brent's avatar
brent committed
709 710 711
	sort.Slice(counts, func(i, j int) bool {
		return counts[i].Time.Before(counts[j].Time)
	})
brent's avatar
brent committed
712 713 714
	server.respond(http.StatusOK, "", counts)
}

brent's avatar
brent committed
715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788
func (server *TaskController) UserTasksPerPeriod() {
	info, err := server.Check()
	if err != nil {
		server.respond(http.StatusUnauthorized, err.Error())
		return
	}
	body := server.Ctx.Input.RequestBody
	appRequest := models.AppRequest{}
	err = json.Unmarshal(body, &appRequest) //解析body中数据
	logs.Debug("appRequest", appRequest)
	//if err != nil {
	//	server.respond(models.NoRequestBody, err.Error())
	//	return
	//}
	period := 7
	if appRequest.Period != 0 {
		period = appRequest.Period
	}
	if period != 365 {
		period = period - 1
	}
	currentTime := time.Now()
	end := time.Date(currentTime.Year(), currentTime.Month(), currentTime.Day(), 23, 59, 59, 0, time.UTC)
	temp := fmt.Sprintf("-%dh", 24*period)
	m, _ := time.ParseDuration(temp)
	tempTime := currentTime.Add(m)
	tempTime = time.Date(tempTime.Year(), tempTime.Month(), tempTime.Day(), 0, 0, 0, 0, time.UTC)

	startTime := fmt.Sprintf(tempTime.Format(format))
	endTime := fmt.Sprintf(end.Format(format))

	countQB, _ := orm.NewQueryBuilder("mysql")
	countQB.Select("count(*)", "time").
		From("tasks").Where(fmt.Sprintf("time >= '%s'", startTime)).And(fmt.Sprintf("time <= '%s'", endTime))
	if info.Role != 1 && info.Role != 2 {
		countQB.And(fmt.Sprintf("uid = %d", info.UserID))
	}
	sql := fmt.Sprintf("%s SAMPLE BY 1d ALIGN TO CALENDAR;", countQB.String())

	endDateIn := time.Date(end.Year(), end.Month(), end.Day(), 0, 0, 0, 0, time.UTC)
	endDate := fmt.Sprintf(endDateIn.Format(format))
	dates := utils.SplitDate(startTime, endDate, format)

	if period == 365 {
		sql = fmt.Sprintf("%s SAMPLE BY 1M ALIGN TO CALENDAR;", countQB.String())
		if tempTime.Day() != 1 {
			tempTime = tempTime.AddDate(0, 1, 0)
		}
		dates = utils.YearMonthRange(tempTime, endDateIn, format)
	}

	counts, err := postgres.CountTasks(sql)
	if err != nil {
		server.respond(models.BusinessFailed, err.Error())
		return
	}
	for _, value := range dates {
		tempDate := findTime(counts, value)
		if tempDate != nil {
			reTask := models.TaskCount{
				Type:    "0",
				Time:    *tempDate,
				Count:   "0",
				ApiPath: "",
			}
			counts = append(counts, reTask)
		}
	}
	sort.Slice(counts, func(i, j int) bool {
		return counts[i].Time.Before(counts[j].Time)
	})
	server.respond(http.StatusOK, "", counts)
}

brent's avatar
brent committed
789 790 791 792 793 794 795 796 797 798
func (server *TaskController) UserTaskTypePerDay() {
	info, err := server.Check()
	if err != nil {
		server.respond(http.StatusUnauthorized, err.Error())
		return
	}
	body := server.Ctx.Input.RequestBody
	appRequest := models.AppRequest{}
	err = json.Unmarshal(body, &appRequest) //解析body中数据
	logs.Debug("appRequest", appRequest)
brent's avatar
brent committed
799 800 801 802
	//if err != nil {
	//	server.respond(models.NoRequestBody, err.Error())
	//	return
	//}
brent's avatar
brent committed
803
	if appRequest.StartTime == "" && appRequest.EndTime != "" {
brent's avatar
brent committed
804
		server.respond(models.MissingParameter, "Missing start time")
brent's avatar
brent committed
805 806 807
		return
	}
	if appRequest.StartTime != "" && appRequest.EndTime == "" {
brent's avatar
brent committed
808
		server.respond(models.MissingParameter, "Missing end time")
brent's avatar
brent committed
809 810 811 812 813 814
		return
	}
	tempLayout := layout
	if appRequest.EndTime == "" && appRequest.StartTime == "" {
		tempLayout = format
	}
brent's avatar
brent committed
815
	currentTime := time.Now()
brent's avatar
brent committed
816
	if appRequest.EndTime == "" {
brent's avatar
brent committed
817
		endTime := time.Date(currentTime.Year(), currentTime.Month(), currentTime.Day(), 23, 59, 59, 0, time.UTC)
brent's avatar
brent committed
818
		appRequest.EndTime = fmt.Sprintf(endTime.Format(format))
brent's avatar
brent committed
819
	}
brent's avatar
brent committed
820
	if appRequest.StartTime == "" {
brent's avatar
brent committed
821 822 823
		temp := fmt.Sprintf("-%dh", 24*7)
		m, _ := time.ParseDuration(temp)
		tempTime := currentTime.Add(m)
brent's avatar
brent committed
824
		tempTime = time.Date(tempTime.Year(), tempTime.Month(), tempTime.Day(), 0, 0, 0, 0, time.UTC)
brent's avatar
brent committed
825
		appRequest.StartTime = fmt.Sprintf(tempTime.Format(format))
brent's avatar
brent committed
826
	}
brent's avatar
brent committed
827 828 829
	startTimeIn, _ := time.Parse(tempLayout, appRequest.StartTime)
	endTimeIn, _ := time.Parse(tempLayout, appRequest.EndTime)
	if endTimeIn.Before(startTimeIn) {
brent's avatar
brent committed
830
		server.respond(models.BusinessFailed, "Start time cannot be greater than end time")
brent's avatar
brent committed
831 832 833
		return
	}

brent's avatar
brent committed
834 835
	startTime := fmt.Sprintf(startTimeIn.Format(format))
	endTime := fmt.Sprintf(endTimeIn.Format(format))
brent's avatar
brent committed
836 837 838 839 840 841 842 843 844

	countQB, _ := orm.NewQueryBuilder("mysql")
	countQB.Select("count(*)", "time", "type").
		From("tasks").Where(fmt.Sprintf("time >= '%s'", startTime)).And(fmt.Sprintf("time <= '%s'", endTime))
	if info.Role != 1 && info.Role != 2 {
		countQB.And(fmt.Sprintf("uid = %d", info.UserID))
	}
	sql := fmt.Sprintf("%s SAMPLE BY 1d ALIGN TO CALENDAR;", countQB.String())

brent's avatar
brent committed
845
	endDateIn := time.Date(endTimeIn.Year(), endTimeIn.Month(), endTimeIn.Day(), 0, 0, 0, 0, time.UTC)
brent's avatar
brent committed
846 847
	endDate := fmt.Sprintf(endDateIn.Format(format))
	dates := utils.SplitDate(startTime, endDate, format)
brent's avatar
brent committed
848 849 850 851
	//sql := fmt.Sprintf("SELECT type, time,count(*) FROM tasks WHERE uid='%d' and time >= '%s' and time <= '%s' SAMPLE BY 1d ALIGN TO CALENDAR;", info.UserID, startTime, endTime)
	//if info.Role == 1 || info.Role == 2 {
	//	sql = fmt.Sprintf("SELECT type, time,count(*) FROM tasks WHERE time >= '%s' and time <= '%s' SAMPLE BY 1d ALIGN TO CALENDAR;", startTime, endTime)
	//}
brent's avatar
brent committed
852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875
	counts, err := postgres.CountTasks(sql)
	if err != nil {
		server.respond(models.BusinessFailed, err.Error())
		return
	}
	var responseTasks []models.TaskCount
	for _, task := range counts {
		apiPath := ""
		taskId, err := strconv.Atoi(task.Type)
		if err == nil {
			taskType, err1 := odysseus.GetTaskType(int64(taskId))
			if err1 == nil {
				apiPath = taskType.ApiPath
			}
		}

		reTask := models.TaskCount{
			Type:    task.Type,
			Time:    task.Time,
			Count:   task.Count,
			ApiPath: apiPath,
		}
		responseTasks = append(responseTasks, reTask)
	}
brent's avatar
brent committed
876 877 878 879 880 881 882 883 884 885 886 887
	for _, value := range dates {
		tempDate := findTime(responseTasks, value)
		if tempDate != nil {
			reTask := models.TaskCount{
				Type:    "0",
				Time:    *tempDate,
				Count:   "0",
				ApiPath: "",
			}
			responseTasks = append(responseTasks, reTask)
		}
	}
brent's avatar
brent committed
888 889 890
	sort.Slice(responseTasks, func(i, j int) bool {
		return responseTasks[i].Time.Before(responseTasks[j].Time)
	})
brent's avatar
brent committed
891

brent's avatar
brent committed
892 893 894
	server.respond(http.StatusOK, "", responseTasks)
}

brent's avatar
brent committed
895 896 897 898 899 900 901 902 903 904
func findTime(tasks []models.TaskCount, date string) *time.Time {
	t, _ := time.Parse(format, date)
	for _, value := range tasks {
		if utils.InSameDay(t, value.Time) {
			return nil
		}
	}
	return &t
}

brent's avatar
brent committed
905 906 907 908 909 910 911 912 913 914
func (server *TaskController) UserTaskTypePercentage() {
	info, err := server.Check()
	if err != nil {
		server.respond(http.StatusUnauthorized, err.Error())
		return
	}
	body := server.Ctx.Input.RequestBody
	appRequest := models.AppRequest{}
	err = json.Unmarshal(body, &appRequest) //解析body中数据
	logs.Debug("appRequest", appRequest)
brent's avatar
brent committed
915 916 917 918
	//if err != nil {
	//	server.respond(models.NoRequestBody, err.Error())
	//	return
	//}
brent's avatar
brent committed
919
	if appRequest.StartTime == "" && appRequest.EndTime != "" {
brent's avatar
brent committed
920
		server.respond(models.MissingParameter, "Missing start time")
brent's avatar
brent committed
921 922 923
		return
	}
	if appRequest.StartTime != "" && appRequest.EndTime == "" {
brent's avatar
brent committed
924
		server.respond(models.MissingParameter, "Missing end time")
brent's avatar
brent committed
925 926 927 928 929 930
		return
	}
	tempLayout := layout
	if appRequest.EndTime == "" && appRequest.StartTime == "" {
		tempLayout = format
	}
brent's avatar
brent committed
931 932 933 934 935 936 937
	period := 7
	if appRequest.Period != 0 {
		period = appRequest.Period
	}
	if period != 365 {
		period = period - 1
	}
brent's avatar
brent committed
938
	currentTime := time.Now()
brent's avatar
brent committed
939
	if appRequest.EndTime == "" {
brent's avatar
brent committed
940
		endTime := time.Date(currentTime.Year(), currentTime.Month(), currentTime.Day(), 23, 59, 59, 0, time.UTC)
brent's avatar
brent committed
941
		appRequest.EndTime = fmt.Sprintf(endTime.Format(format))
brent's avatar
brent committed
942
	}
brent's avatar
brent committed
943
	if appRequest.StartTime == "" {
brent's avatar
brent committed
944
		temp := fmt.Sprintf("-%dh", 24*period)
brent's avatar
brent committed
945 946
		m, _ := time.ParseDuration(temp)
		tempTime := currentTime.Add(m)
brent's avatar
brent committed
947
		tempTime = time.Date(tempTime.Year(), tempTime.Month(), tempTime.Day(), 0, 0, 0, 0, time.UTC)
brent's avatar
brent committed
948
		appRequest.StartTime = fmt.Sprintf(tempTime.Format(format))
brent's avatar
brent committed
949
	}
brent's avatar
brent committed
950 951
	startTimeIn, _ := time.Parse(tempLayout, appRequest.StartTime)
	endTimeIn, _ := time.Parse(tempLayout, appRequest.EndTime)
brent's avatar
brent committed
952

brent's avatar
brent committed
953
	if endTimeIn.Before(startTimeIn) {
brent's avatar
brent committed
954
		server.respond(models.BusinessFailed, "Start time cannot be greater than end time")
brent's avatar
brent committed
955 956 957
		return
	}

brent's avatar
brent committed
958 959
	startTime := fmt.Sprintf(startTimeIn.Format(format))
	endTime := fmt.Sprintf(endTimeIn.Format(format))
brent's avatar
brent committed
960 961 962 963 964 965 966 967 968 969 970 971 972
	countQB, _ := orm.NewQueryBuilder("mysql")
	countQB.Select("count(type)", "type").
		From("tasks").Where(fmt.Sprintf("time >= '%s'", startTime)).And(fmt.Sprintf("time <= '%s'", endTime))
	if info.Role != 1 && info.Role != 2 {
		countQB.And(fmt.Sprintf("uid = %d", info.UserID))
	}
	countQB.GroupBy("type")
	sql := countQB.String()

	//sql := fmt.Sprintf("SELECT type, count(type) FROM tasks WHERE uid='%d' and time >= '%s' and time <= '%s' GROUP BY type;", info.UserID, startTime, endTime)
	//if info.Role == 1 || info.Role == 2 {
	//	sql = fmt.Sprintf("SELECT type, count(type) FROM tasks WHERE time >= '%s' and time <= '%s' GROUP BY type;", startTime, endTime)
	//}
brent's avatar
brent committed
973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009
	counts, err := postgres.CountTasks(sql)
	if err != nil {
		server.respond(models.BusinessFailed, err.Error())
		return
	}
	var responseTasks []models.TaskCount
	for _, task := range counts {
		apiPath := ""
		taskId, err := strconv.Atoi(task.Type)
		if err == nil {
			taskType, err1 := odysseus.GetTaskType(int64(taskId))
			if err1 == nil {
				apiPath = taskType.ApiPath
			}
		}

		reTask := models.TaskCount{
			Type:    task.Type,
			Time:    task.Time,
			Count:   task.Count,
			ApiPath: apiPath,
		}
		responseTasks = append(responseTasks, reTask)
	}
	server.respond(http.StatusOK, "", responseTasks)
}

func (server *TaskController) UserFeePerDay() {
	info, err := server.Check()
	if err != nil {
		server.respond(http.StatusUnauthorized, err.Error())
		return
	}
	body := server.Ctx.Input.RequestBody
	appRequest := models.AppRequest{}
	err = json.Unmarshal(body, &appRequest) //解析body中数据
	logs.Debug("appRequest", appRequest)
brent's avatar
brent committed
1010 1011 1012 1013
	//if err != nil {
	//	server.respond(models.NoRequestBody, err.Error())
	//	return
	//}
brent's avatar
brent committed
1014
	if appRequest.StartTime == "" && appRequest.EndTime != "" {
brent's avatar
brent committed
1015
		server.respond(models.MissingParameter, "Missing start time")
brent's avatar
brent committed
1016 1017 1018
		return
	}
	if appRequest.StartTime != "" && appRequest.EndTime == "" {
brent's avatar
brent committed
1019
		server.respond(models.MissingParameter, "Missing end time")
brent's avatar
brent committed
1020 1021 1022 1023 1024 1025
		return
	}
	tempLayout := layout
	if appRequest.EndTime == "" && appRequest.StartTime == "" {
		tempLayout = format
	}
brent's avatar
brent committed
1026
	currentTime := time.Now()
brent's avatar
brent committed
1027
	if appRequest.EndTime == "" {
brent's avatar
brent committed
1028
		endTime := time.Date(currentTime.Year(), currentTime.Month(), currentTime.Day(), 23, 59, 59, 0, time.UTC)
brent's avatar
brent committed
1029
		appRequest.EndTime = fmt.Sprintf(endTime.Format(format))
brent's avatar
brent committed
1030
	}
brent's avatar
brent committed
1031
	if appRequest.StartTime == "" {
brent's avatar
brent committed
1032 1033 1034
		temp := fmt.Sprintf("-%dh", 24*7)
		m, _ := time.ParseDuration(temp)
		tempTime := currentTime.Add(m)
brent's avatar
brent committed
1035
		tempTime = time.Date(tempTime.Year(), tempTime.Month(), tempTime.Day(), 0, 0, 0, 0, time.UTC)
brent's avatar
brent committed
1036
		appRequest.StartTime = fmt.Sprintf(tempTime.Format(format))
brent's avatar
brent committed
1037
	}
brent's avatar
brent committed
1038 1039
	startTimeIn, _ := time.Parse(tempLayout, appRequest.StartTime)
	endTimeIn, _ := time.Parse(tempLayout, appRequest.EndTime)
brent's avatar
brent committed
1040

brent's avatar
brent committed
1041
	if endTimeIn.Before(startTimeIn) {
brent's avatar
brent committed
1042
		server.respond(models.BusinessFailed, "Start time cannot be greater than end time")
brent's avatar
brent committed
1043 1044 1045
		return
	}

brent's avatar
brent committed
1046 1047
	startTime := fmt.Sprintf(startTimeIn.Format(format))
	endTime := fmt.Sprintf(endTimeIn.Format(format))
brent's avatar
brent committed
1048 1049 1050 1051 1052 1053 1054 1055 1056

	countQB, _ := orm.NewQueryBuilder("mysql")
	countQB.Select("time", "sum(fee) AS fee").
		From("bills").Where(fmt.Sprintf("time >= '%s'", startTime)).And(fmt.Sprintf("time <= '%s'", endTime))
	if info.Role != 1 && info.Role != 2 {
		countQB.And(fmt.Sprintf("uid = %d", info.UserID))
	}
	sql := fmt.Sprintf("%s SAMPLE BY 1d ALIGN TO CALENDAR;", countQB.String())

brent's avatar
brent committed
1057
	endDateIn := time.Date(endTimeIn.Year(), endTimeIn.Month(), endTimeIn.Day(), 0, 0, 0, 0, time.UTC)
brent's avatar
brent committed
1058 1059
	endDate := fmt.Sprintf(endDateIn.Format(format))
	dates := utils.SplitDate(startTime, endDate, format)
brent's avatar
brent committed
1060

brent's avatar
brent committed
1061 1062 1063 1064
	//sql := fmt.Sprintf("SELECT time,sum(fee) AS fee FROM bills WHERE uid='%d' and time >= '%s' and time <= '%s' SAMPLE BY 1d ALIGN TO CALENDAR;", info.UserID, startTime, endTime)
	//if info.Role == 1 || info.Role == 2 {
	//	sql = fmt.Sprintf("SELECT time,sum(fee) AS fee FROM bills WHERE time >= '%s' and time <= '%s' SAMPLE BY 1d ALIGN TO CALENDAR;", startTime, endTime)
	//}
brent's avatar
brent committed
1065 1066 1067 1068 1069
	counts, err := postgres.CountTasks(sql)
	if err != nil {
		server.respond(models.BusinessFailed, err.Error())
		return
	}
brent's avatar
brent committed
1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081
	for _, value := range dates {
		tempDate := findTime(counts, value)
		if tempDate != nil {
			reTask := models.TaskCount{
				Type:    "0",
				Time:    *tempDate,
				Count:   "0",
				ApiPath: "",
			}
			counts = append(counts, reTask)
		}
	}
brent's avatar
brent committed
1082 1083 1084
	sort.Slice(counts, func(i, j int) bool {
		return counts[i].Time.Before(counts[j].Time)
	})
brent's avatar
brent committed
1085 1086 1087
	server.respond(http.StatusOK, "", counts)
}

brent's avatar
brent committed
1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115
func (server *TaskController) UserFee() {
	info, err := server.Check()
	if err != nil {
		server.respond(http.StatusUnauthorized, err.Error())
		return
	}
	body := server.Ctx.Input.RequestBody
	appRequest := models.AppRequest{}
	err = json.Unmarshal(body, &appRequest) //解析body中数据
	logs.Debug("appRequest", appRequest)
	//if err != nil {
	//	server.respond(models.NoRequestBody, err.Error())
	//	return
	//}
	//if appRequest.StartTime == "" && appRequest.EndTime != "" {
	//	server.respond(models.MissingParameter, "缺少开始时间")
	//	return
	//}
	//if appRequest.StartTime != "" && appRequest.EndTime == "" {
	//	server.respond(models.MissingParameter, "缺少结束时间")
	//	return
	//}
	//tempLayout := layout
	//if appRequest.EndTime == "" && appRequest.StartTime == "" {
	//	tempLayout = format
	//}
	//currentTime := time.Now()
	//if appRequest.EndTime == "" {
brent's avatar
brent committed
1116
	//	endTime := time.Date(currentTime.Year(), currentTime.Month(), currentTime.Day(), 23, 59, 59, 0, time.UTC)
brent's avatar
brent committed
1117 1118 1119 1120 1121 1122
	//	appRequest.EndTime = fmt.Sprintf(endTime.Format(format))
	//}
	//if appRequest.StartTime == "" {
	//	temp := fmt.Sprintf("-%dh", 24*7)
	//	m, _ := time.ParseDuration(temp)
	//	tempTime := currentTime.Add(m)
brent's avatar
brent committed
1123
	//	tempTime = time.Date(tempTime.Year(), tempTime.Month(), tempTime.Day(), 0, 0, 0, 0, time.UTC)
brent's avatar
brent committed
1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145
	//	appRequest.StartTime = fmt.Sprintf(tempTime.Format(format))
	//}
	//startTimeIn, _ := time.Parse(tempLayout, appRequest.StartTime)
	//endTimeIn, _ := time.Parse(tempLayout, appRequest.EndTime)
	//
	//if endTimeIn.Before(startTimeIn) {
	//	server.respond(models.BusinessFailed, "起始时间不能大于结束时间")
	//	return
	//}
	//
	//startTime := fmt.Sprintf(startTimeIn.Format(format))
	//endTime := fmt.Sprintf(endTimeIn.Format(format))

	countQB, _ := orm.NewQueryBuilder("mysql")
	countQB.Select("sum(fee) AS fee").
		From("bills")
	if info.Role != 1 && info.Role != 2 {
		countQB.Where(fmt.Sprintf("uid = %d", info.UserID))
	}
	//sql := fmt.Sprintf("%s SAMPLE BY 1d ALIGN TO CALENDAR;", countQB.String())
	sql := countQB.String()

brent's avatar
brent committed
1146
	//endDateIn := time.Date(endTimeIn.Year(), endTimeIn.Month(), endTimeIn.Day(), 0, 0, 0, 0, time.UTC)
brent's avatar
brent committed
1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158
	//endDate := fmt.Sprintf(endDateIn.Format(format))
	//dates := utils.SplitDate(startTime, endDate, format)

	//sql := fmt.Sprintf("SELECT time,sum(fee) AS fee FROM bills WHERE uid='%d' and time >= '%s' and time <= '%s' SAMPLE BY 1d ALIGN TO CALENDAR;", info.UserID, startTime, endTime)
	//if info.Role == 1 || info.Role == 2 {
	//	sql = fmt.Sprintf("SELECT time,sum(fee) AS fee FROM bills WHERE time >= '%s' and time <= '%s' SAMPLE BY 1d ALIGN TO CALENDAR;", startTime, endTime)
	//}
	counts, err := postgres.CountTasks(sql)
	if err != nil {
		server.respond(models.BusinessFailed, err.Error())
		return
	}
brent's avatar
brent committed
1159 1160 1161 1162 1163 1164 1165 1166 1167 1168
	fee := int64(0)
	for _, value := range counts {
		fee, _ = strconv.ParseInt(value.Fee, 10, 64)
	}
	fee = fee / 1000000
	data := struct {
		Fee int64 `json:"fee"`
	}{
		Fee: fee,
	}
brent's avatar
brent committed
1169 1170 1171
	//sort.Slice(counts, func(i, j int) bool {
	//	return counts[i].Time.Before(counts[j].Time)
	//})
brent's avatar
brent committed
1172
	server.respond(http.StatusOK, "", data)
brent's avatar
brent committed
1173 1174
}

brent's avatar
brent committed
1175 1176 1177 1178 1179 1180 1181 1182 1183 1184
func (server *TaskController) UserTaskTypeFeePerDay() {
	info, err := server.Check()
	if err != nil {
		server.respond(http.StatusUnauthorized, err.Error())
		return
	}
	body := server.Ctx.Input.RequestBody
	appRequest := models.AppRequest{}
	err = json.Unmarshal(body, &appRequest) //解析body中数据
	logs.Debug("appRequest", appRequest)
brent's avatar
brent committed
1185 1186 1187 1188
	//if err != nil {
	//	server.respond(models.NoRequestBody, err.Error())
	//	return
	//}
brent's avatar
brent committed
1189
	if appRequest.StartTime == "" && appRequest.EndTime != "" {
brent's avatar
brent committed
1190
		server.respond(models.MissingParameter, "Missing start time")
brent's avatar
brent committed
1191 1192 1193
		return
	}
	if appRequest.StartTime != "" && appRequest.EndTime == "" {
brent's avatar
brent committed
1194
		server.respond(models.MissingParameter, "Missing end time")
brent's avatar
brent committed
1195 1196 1197 1198 1199 1200
		return
	}
	tempLayout := layout
	if appRequest.EndTime == "" && appRequest.StartTime == "" {
		tempLayout = format
	}
brent's avatar
brent committed
1201
	currentTime := time.Now()
brent's avatar
brent committed
1202
	if appRequest.EndTime == "" {
brent's avatar
brent committed
1203
		endTime := time.Date(currentTime.Year(), currentTime.Month(), currentTime.Day(), 23, 59, 59, 0, time.UTC)
brent's avatar
brent committed
1204
		appRequest.EndTime = fmt.Sprintf(endTime.Format(format))
brent's avatar
brent committed
1205
	}
brent's avatar
brent committed
1206
	if appRequest.StartTime == "" {
brent's avatar
brent committed
1207 1208 1209
		temp := fmt.Sprintf("-%dh", 24*7)
		m, _ := time.ParseDuration(temp)
		tempTime := currentTime.Add(m)
brent's avatar
brent committed
1210
		tempTime = time.Date(tempTime.Year(), tempTime.Month(), tempTime.Day(), 0, 0, 0, 0, time.UTC)
brent's avatar
brent committed
1211
		appRequest.StartTime = fmt.Sprintf(tempTime.Format(format))
brent's avatar
brent committed
1212
	}
brent's avatar
brent committed
1213 1214
	startTimeIn, _ := time.Parse(tempLayout, appRequest.StartTime)
	endTimeIn, _ := time.Parse(tempLayout, appRequest.EndTime)
brent's avatar
brent committed
1215

brent's avatar
brent committed
1216
	if endTimeIn.Before(startTimeIn) {
brent's avatar
brent committed
1217
		server.respond(models.BusinessFailed, "Start time cannot be greater than end time")
brent's avatar
brent committed
1218 1219 1220
		return
	}

brent's avatar
brent committed
1221 1222
	startTime := fmt.Sprintf(startTimeIn.Format(format))
	endTime := fmt.Sprintf(endTimeIn.Format(format))
brent's avatar
brent committed
1223 1224 1225 1226 1227 1228 1229 1230 1231

	countQB, _ := orm.NewQueryBuilder("mysql")
	countQB.Select("time", "sum(fee) AS fee", "type").
		From("bills").Where(fmt.Sprintf("time >= '%s'", startTime)).And(fmt.Sprintf("time <= '%s'", endTime))
	if info.Role != 1 && info.Role != 2 {
		countQB.And(fmt.Sprintf("uid = %d", info.UserID))
	}
	sql := fmt.Sprintf("%s SAMPLE BY 1d ALIGN TO CALENDAR;", countQB.String())

brent's avatar
brent committed
1232
	endDateIn := time.Date(endTimeIn.Year(), endTimeIn.Month(), endTimeIn.Day(), 0, 0, 0, 0, time.UTC)
brent's avatar
brent committed
1233 1234
	endDate := fmt.Sprintf(endDateIn.Format(format))
	dates := utils.SplitDate(startTime, endDate, format)
brent's avatar
brent committed
1235

brent's avatar
brent committed
1236 1237 1238 1239
	//sql := fmt.Sprintf("SELECT type, time,sum(fee) AS fee FROM bills WHERE uid='%d' and time >= '%s' and time <= '%s' SAMPLE BY 1d ALIGN TO CALENDAR;", info.UserID, startTime, endTime)
	//if info.Role == 1 || info.Role == 2 {
	//	sql = fmt.Sprintf("SELECT type, time,sum(fee) AS fee FROM bills WHERE time >= '%s' and time <= '%s' SAMPLE BY 1d ALIGN TO CALENDAR;", startTime, endTime)
	//}
brent's avatar
brent committed
1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258
	counts, err := postgres.CountTasks(sql)
	if err != nil {
		server.respond(models.BusinessFailed, err.Error())
		return
	}
	var responseTasks []models.TaskCount
	for _, task := range counts {
		apiPath := ""
		taskId, err := strconv.Atoi(task.Type)
		if err == nil {
			taskType, err1 := odysseus.GetTaskType(int64(taskId))
			if err1 == nil {
				apiPath = taskType.ApiPath
			}
		}

		reTask := models.TaskCount{
			Type:    task.Type,
			Time:    task.Time,
brent's avatar
brent committed
1259
			Fee:     task.Fee,
brent's avatar
brent committed
1260 1261 1262 1263
			ApiPath: apiPath,
		}
		responseTasks = append(responseTasks, reTask)
	}
brent's avatar
brent committed
1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275
	for _, value := range dates {
		tempDate := findTime(responseTasks, value)
		if tempDate != nil {
			reTask := models.TaskCount{
				Type:    "0",
				Time:    *tempDate,
				Fee:     "0",
				ApiPath: "",
			}
			responseTasks = append(responseTasks, reTask)
		}
	}
brent's avatar
brent committed
1276 1277 1278
	sort.Slice(responseTasks, func(i, j int) bool {
		return responseTasks[i].Time.Before(responseTasks[j].Time)
	})
brent's avatar
brent committed
1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291
	server.respond(http.StatusOK, "", responseTasks)
}

func (server *TaskController) UserTaskTypeFeePercentage() {
	info, err := server.Check()
	if err != nil {
		server.respond(http.StatusUnauthorized, err.Error())
		return
	}
	body := server.Ctx.Input.RequestBody
	appRequest := models.AppRequest{}
	err = json.Unmarshal(body, &appRequest) //解析body中数据
	logs.Debug("appRequest", appRequest)
brent's avatar
brent committed
1292 1293 1294 1295
	//if err != nil {
	//	server.respond(models.NoRequestBody, err.Error())
	//	return
	//}
brent's avatar
brent committed
1296
	if appRequest.StartTime == "" && appRequest.EndTime != "" {
brent's avatar
brent committed
1297
		server.respond(models.MissingParameter, "Missing start time")
brent's avatar
brent committed
1298 1299 1300
		return
	}
	if appRequest.StartTime != "" && appRequest.EndTime == "" {
brent's avatar
brent committed
1301
		server.respond(models.MissingParameter, "Missing end time")
brent's avatar
brent committed
1302 1303 1304 1305 1306 1307
		return
	}
	tempLayout := layout
	if appRequest.EndTime == "" && appRequest.StartTime == "" {
		tempLayout = format
	}
brent's avatar
brent committed
1308
	currentTime := time.Now()
brent's avatar
brent committed
1309
	if appRequest.EndTime == "" {
brent's avatar
brent committed
1310
		endTime := time.Date(currentTime.Year(), currentTime.Month(), currentTime.Day(), 23, 59, 59, 0, time.UTC)
brent's avatar
brent committed
1311
		appRequest.EndTime = fmt.Sprintf(endTime.Format(format))
brent's avatar
brent committed
1312
	}
brent's avatar
brent committed
1313
	if appRequest.StartTime == "" {
brent's avatar
brent committed
1314 1315 1316
		temp := fmt.Sprintf("-%dh", 24*7)
		m, _ := time.ParseDuration(temp)
		tempTime := currentTime.Add(m)
brent's avatar
brent committed
1317
		tempTime = time.Date(tempTime.Year(), tempTime.Month(), tempTime.Day(), 0, 0, 0, 0, time.UTC)
brent's avatar
brent committed
1318
		appRequest.StartTime = fmt.Sprintf(tempTime.Format(format))
brent's avatar
brent committed
1319
	}
brent's avatar
brent committed
1320 1321
	startTimeIn, _ := time.Parse(tempLayout, appRequest.StartTime)
	endTimeIn, _ := time.Parse(tempLayout, appRequest.EndTime)
brent's avatar
brent committed
1322

brent's avatar
brent committed
1323
	if endTimeIn.Before(startTimeIn) {
brent's avatar
brent committed
1324
		server.respond(models.BusinessFailed, "Start time cannot be greater than end time")
brent's avatar
brent committed
1325 1326 1327
		return
	}

brent's avatar
brent committed
1328 1329
	startTime := fmt.Sprintf(startTimeIn.Format(format))
	endTime := fmt.Sprintf(endTimeIn.Format(format))
brent's avatar
brent committed
1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343

	countQB, _ := orm.NewQueryBuilder("mysql")
	countQB.Select("sum(fee) AS fee", "type").
		From("bills").Where(fmt.Sprintf("time >= '%s'", startTime)).And(fmt.Sprintf("time <= '%s'", endTime))
	if info.Role != 1 && info.Role != 2 {
		countQB.And(fmt.Sprintf("uid = %d", info.UserID))
	}
	countQB.GroupBy("type")
	sql := countQB.String()

	//sql := fmt.Sprintf("SELECT type, sum(fee) AS fee FROM bills WHERE uid='%d' and time >= '%s' and time <= '%s' GROUP BY type;", info.UserID, startTime, endTime)
	//if info.Role == 1 || info.Role == 2 {
	//	sql = fmt.Sprintf("SELECT type, sum(fee) AS fee FROM bills WHERE time >= '%s' and time <= '%s' GROUP BY type;", startTime, endTime)
	//}
brent's avatar
brent committed
1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370
	counts, err := postgres.CountTasks(sql)
	if err != nil {
		server.respond(models.BusinessFailed, err.Error())
		return
	}
	var responseTasks []models.TaskCount
	for _, task := range counts {
		apiPath := ""
		taskId, err := strconv.Atoi(task.Type)
		if err == nil {
			taskType, err1 := odysseus.GetTaskType(int64(taskId))
			if err1 == nil {
				apiPath = taskType.ApiPath
			}
		}

		reTask := models.TaskCount{
			Type:    task.Type,
			Time:    task.Time,
			Count:   task.Count,
			ApiPath: apiPath,
		}
		responseTasks = append(responseTasks, reTask)
	}
	server.respond(http.StatusOK, "", responseTasks)
}

brent's avatar
brent committed
1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417
func (server *TaskController) Computility() {
	_, err := server.Check()
	if err != nil {
		server.respond(http.StatusUnauthorized, err.Error())
		return
	}
	body := server.Ctx.Input.RequestBody
	appRequest := models.AppRequest{}
	err = json.Unmarshal(body, &appRequest) //解析body中数据
	logs.Debug("appRequest", appRequest, string(body))

	if appRequest.Page == 0 {
		appRequest.Page = 1
	}
	if appRequest.Size == 0 {
		appRequest.Size = 10
	}
	offset := (appRequest.Page - 1) * appRequest.Size

	qs := mysql.GetMysqlInstace().Ormer.QueryTable("computility").Filter("deleted", 0)
	if appRequest.Type != 0 {
		qs.Filter("type", appRequest.Type)
	}
	if appRequest.Keyword != "" {
		cond := orm.NewCondition()
		cond1 := cond.Or("model__contains", appRequest.Keyword).Or("series__contains", appRequest.Keyword).Or("brand__contains", appRequest.Keyword)
		cond2 := cond.AndNotCond(cond1)
		qs = qs.SetCond(cond2)
	}
	infoQs := qs.Offset(offset).Limit(appRequest.Size)
	count, err := infoQs.Count()
	logs.Debug("lists = ", count)
	var lists []*models.Computility
	if count > 0 {
		infoQs.All(&lists)
	}
	total, err := qs.Count()
	responseData := struct {
		Total int64       `json:"total"`
		Data  interface{} `json:"data,omitempty"`
	}{
		Total: total,
		Data:  lists,
	}
	server.respond(http.StatusOK, "", responseData)
}

brent's avatar
brent committed
1418
func (server *TaskController) AddTasktype() {
brent's avatar
brent committed
1419 1420 1421 1422 1423
	_, err := server.Check()
	if err != nil {
		server.respond(http.StatusUnauthorized, err.Error())
		return
	}
brent's avatar
brent committed
1424 1425
	body := server.Ctx.Input.RequestBody
	appRequest := models.AddTaskType{}
brent's avatar
brent committed
1426 1427
	err = json.Unmarshal(body, &appRequest) //解析body中数据
	logs.Debug("appRequest", appRequest, string(body))
brent's avatar
brent committed
1428 1429 1430 1431 1432
	if err != nil {
		server.respond(models.NoRequestBody, err.Error())
		return
	}

brent's avatar
brent committed
1433
	if &appRequest.TaskTypeIn == nil {
brent's avatar
brent committed
1434
		server.respond(models.MissingParameter, "Missing type parameter")
brent's avatar
brent committed
1435 1436
		return
	}
brent's avatar
brent committed
1437
	if &appRequest.TaskTypeIn.Name == nil {
brent's avatar
brent committed
1438
		server.respond(models.MissingParameter, "Missing name parameter")
brent's avatar
brent committed
1439 1440 1441
		return
	}
	if &appRequest.TaskTypeIn.Type == nil {
brent's avatar
brent committed
1442
		server.respond(models.MissingParameter, "Missing type.type parameter")
brent's avatar
brent committed
1443 1444
		return
	}
brent's avatar
brent committed
1445

brent's avatar
brent committed
1446 1447 1448 1449 1450
	//if &appRequest.Type.Version == nil {
	//	server.respond(models.MissingParameter, "版本 不能为空")
	//	return
	//}
	if &appRequest.TaskTypeIn.BaseModel == nil {
brent's avatar
brent committed
1451
		server.respond(models.MissingParameter, "Missing base_model parameter")
brent's avatar
brent committed
1452 1453 1454 1455 1456 1457
		return
	}
	//if &appRequest.Type.Version == nil {
	//	server.respond(models.MissingParameter, "基础模型 不能为空")
	//	return
	//}
brent's avatar
brent committed
1458 1459

	if &appRequest.Levels == nil {
brent's avatar
brent committed
1460
		server.respond(models.MissingParameter, "Missing levels parameter")
brent's avatar
brent committed
1461 1462 1463
		return
	}
	if len(appRequest.Levels) <= 0 {
brent's avatar
brent committed
1464
		server.respond(models.MissingParameter, "levels.length is 0")
brent's avatar
brent committed
1465 1466 1467 1468
		return
	}

	//ormer := orm.NewOrm()
brent's avatar
brent committed
1469 1470 1471
	if appRequest.TaskTypeIn.ResultFileExpires == 0 {
		appRequest.TaskTypeIn.ResultFileExpires = 1800
	}
brent's avatar
brent committed
1472 1473 1474 1475 1476 1477 1478 1479 1480 1481

	ormer := mysql.GetMysqlInstace().Ormer
	//err = ormer.Begin()
	//if err != nil {
	//	server.respond(models.BusinessFailed, "填加 task type 失败")
	//	return
	//}

	timestamp := time.Now()

brent's avatar
brent committed
1482 1483 1484
	hardwareRequire, err := json.Marshal(appRequest.TaskTypeIn.HardwareRequire)
	cmd, err := json.Marshal(appRequest.TaskTypeIn.Cmd)
	//examples, err := json.Marshal(appRequest.Type.Examples)
brent's avatar
brent committed
1485
	//apiPath := fmt.Sprintf("/%s/%s/%s", appRequest.TaskTypeIn.Type.String(), appRequest.TaskTypeIn.BaseModel, appRequest.TaskTypeIn.Model)
brent's avatar
brent committed
1486 1487 1488 1489 1490 1491 1492
	//if appRequest.Type.BaseModel != "" {
	//	apiPath = fmt.Sprintf("/%s/%s", apiPath, appRequest.Type.BaseModel)
	//}
	//if appRequest.Type.Version != "" {
	//	apiPath = fmt.Sprintf("/%s/%s", apiPath, appRequest.Type.Version)
	//}
	price := int64(appRequest.TaskTypeIn.Price * 1000000)
brent's avatar
brent committed
1493
	dbType := models.TaskType{
brent's avatar
brent committed
1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519
		Name:              appRequest.TaskTypeIn.Name,
		BaseModel:         appRequest.TaskTypeIn.BaseModel,
		Model:             appRequest.TaskTypeIn.Model,
		Version:           appRequest.TaskTypeIn.Version,
		Desc:              appRequest.TaskTypeIn.Desc,
		Price:             price,
		PublicKey:         appRequest.TaskTypeIn.PublicKey,
		Complexity:        appRequest.TaskTypeIn.Complexity,
		Type:              int(appRequest.TaskTypeIn.Type),
		Kind:              appRequest.TaskTypeIn.Kind,
		HardwareRequire:   string(hardwareRequire),
		ImageId:           appRequest.TaskTypeIn.ImageId,
		ImageUrl:          appRequest.TaskTypeIn.ImageUrl,
		Cmd:               string(cmd),
		ResultFileExpires: appRequest.TaskTypeIn.ResultFileExpires,
		Workload:          appRequest.TaskTypeIn.Workload,
		ApiPath:           appRequest.TaskTypeIn.ApiPath,
		ImageName:         appRequest.TaskTypeIn.ImageName,
		SignUrl:           appRequest.TaskTypeIn.SignUrl,
		Username:          appRequest.TaskTypeIn.Username,
		Password:          appRequest.TaskTypeIn.Password,
		Category:          appRequest.TaskTypeIn.Category,
		PublishStatus:     appRequest.TaskTypeIn.PublishStatus,
		AccessStatus:      appRequest.TaskTypeIn.AccessStatus,
		CreatedTime:       timestamp,
		UpdatedTime:       timestamp,
brent's avatar
brent committed
1520 1521 1522 1523 1524
	}

	id, err := ormer.Insert(&dbType)
	if err != nil {
		//ormer.Rollback()
brent's avatar
brent committed
1525
		server.respond(models.BusinessFailed, "failed")
brent's avatar
brent committed
1526 1527
		return
	}
brent's avatar
brent committed
1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548

	dataString, err := redis.GetDataToString(cronjob.HeatKey)
	var response []models.TaskHeat
	if err != nil {
		logs.Debug("GetDataToString err")
	}
	err = json.Unmarshal([]byte(dataString), &response)
	if err != nil {
		logs.Debug("GetDataToString Unmarshal err")
	}
	retask := models.TaskHeat{
		TaskId:          int(id),
		User:            dbType.Username,
		Pwd:             dbType.Password,
		Repository:      dbType.ImageUrl,
		SignUrl:         dbType.SignUrl,
		ImageName:       dbType.ImageName,
		ImageId:         dbType.ImageId,
		HardwareRequire: appRequest.TaskTypeIn.HardwareRequire,
		Count:           int64(0),
		Kind:            dbType.Kind,
brent's avatar
brent committed
1549
		FileExpiresTime: strconv.Itoa(dbType.ResultFileExpires),
brent's avatar
brent committed
1550 1551
		AccessStatus:    dbType.AccessStatus,
		PublishStatus:   dbType.PublishStatus,
brent's avatar
brent committed
1552 1553 1554 1555 1556 1557 1558
	}
	response = append(response, retask)
	data, err := json.Marshal(response)
	if err == nil {
		redis.SetKeyAndData(cronjob.HeatKey, string(data), 0)
	}

brent's avatar
brent committed
1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570
	//todo:插入model表,并且关联task_type_id
	var levels []models.UserLevelTaskType
	for _, value := range appRequest.Levels {
		temp := value
		temp.TaskTypeId = int(id)
		temp.CreatedTime = timestamp
		temp.UpdatedTime = timestamp
		levels = append(levels, temp)
	}
	_, err = ormer.InsertMulti(len(appRequest.Levels), &levels)
	if err != nil {
		//ormer.Rollback()
brent's avatar
brent committed
1571
		server.respond(models.BusinessFailed, "failed")
brent's avatar
brent committed
1572 1573 1574 1575 1576 1577 1578
		return
	}
	//err = ormer.Commit()
	//if err != nil {
	//	server.respond(models.BusinessFailed, "填加 task type 失败")
	//	return
	//}
brent's avatar
brent committed
1579
	server.respond(http.StatusOK, "success")
brent's avatar
brent committed
1580 1581 1582 1583
}

func (server *TaskController) UpdateTaskType() {
	//todo:需要调用学前的setTaskType,然后再调用PublichTaskUpdate
brent's avatar
brent committed
1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598
	_, err := server.Check()
	if err != nil {
		server.respond(http.StatusUnauthorized, err.Error())
		return
	}
	body := server.Ctx.Input.RequestBody
	appRequest := models.AddTaskType{}
	err = json.Unmarshal(body, &appRequest) //解析body中数据
	logs.Debug("appRequest", appRequest)
	if err != nil {
		server.respond(models.NoRequestBody, err.Error())
		return
	}

	if &appRequest.TaskTypeIn == nil {
brent's avatar
brent committed
1599
		server.respond(models.MissingParameter, "Missing type parameter")
brent's avatar
brent committed
1600 1601 1602
		return
	}
	if &appRequest.TaskTypeIn.Id == nil {
brent's avatar
brent committed
1603
		server.respond(models.MissingParameter, "Missing type.id parameter")
brent's avatar
brent committed
1604 1605 1606
		return
	}
	if &appRequest.TaskTypeIn.Name == nil {
brent's avatar
brent committed
1607
		server.respond(models.MissingParameter, "Missing name parameter")
brent's avatar
brent committed
1608 1609 1610
		return
	}
	if &appRequest.TaskTypeIn.Type == nil {
brent's avatar
brent committed
1611
		server.respond(models.MissingParameter, "Missing type.type parameter")
brent's avatar
brent committed
1612 1613 1614
		return
	}
	if &appRequest.TaskTypeIn.BaseModel == nil {
brent's avatar
brent committed
1615
		server.respond(models.MissingParameter, "Missing type.base_model parameter")
brent's avatar
brent committed
1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627
		return
	}

	if len(appRequest.Levels) > 0 {
		flag := false
		for _, value := range appRequest.Levels {
			if value.Id == 0 {
				flag = true
				break
			}
		}
		if flag {
brent's avatar
brent committed
1628
			server.respond(models.MissingParameter, "Missing levels.id parameter")
brent's avatar
brent committed
1629 1630 1631
			return
		}
	}
brent's avatar
brent committed
1632 1633 1634
	if appRequest.TaskTypeIn.ResultFileExpires == 0 {
		appRequest.TaskTypeIn.ResultFileExpires = 1800
	}
brent's avatar
brent committed
1635 1636 1637 1638 1639 1640 1641 1642 1643 1644

	//ormer := orm.NewOrm()

	ormer := mysql.GetMysqlInstace().Ormer
	//err = ormer.Begin()
	//if err != nil {
	//	server.respond(models.BusinessFailed, "填加 task type 失败")
	//	return
	//}

brent's avatar
brent committed
1645 1646 1647 1648 1649 1650 1651
	checkType := &models.TaskType{Id: appRequest.TaskTypeIn.Id}
	err = mysql.GetMysqlInstace().Ormer.Read(checkType)
	if err != nil {
		server.respond(models.BusinessFailed, err.Error())
		return
	}

brent's avatar
brent committed
1652 1653 1654 1655
	timestamp := time.Now()

	hardwareRequire, err := json.Marshal(appRequest.TaskTypeIn.HardwareRequire)
	cmd, err := json.Marshal(appRequest.TaskTypeIn.Cmd)
brent's avatar
brent committed
1656
	//apiPath := fmt.Sprintf("/%s/%s/%s", appRequest.TaskTypeIn.Type.String(), appRequest.TaskTypeIn.BaseModel, appRequest.TaskTypeIn.Model)
brent's avatar
brent committed
1657 1658 1659 1660 1661 1662 1663 1664 1665
	//apiPath := fmt.Sprintf("/%s/%s", appRequest.Type.Type.String(), appRequest.Type.Name)
	//if appRequest.Type.BaseModel != "" {
	//	apiPath = fmt.Sprintf("/%s/%s", apiPath, appRequest.Type.BaseModel)
	//}
	//if appRequest.Type.Version != "" {
	//	apiPath = fmt.Sprintf("/%s/%s", apiPath, appRequest.Type.Version)
	//}
	price := int64(appRequest.TaskTypeIn.Price * 1000000)
	dbType := models.TaskType{
brent's avatar
brent committed
1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718
		Id:                appRequest.TaskTypeIn.Id,
		Name:              appRequest.TaskTypeIn.Name,
		BaseModel:         appRequest.TaskTypeIn.BaseModel,
		Model:             appRequest.TaskTypeIn.Model,
		Version:           appRequest.TaskTypeIn.Version,
		Desc:              appRequest.TaskTypeIn.Desc,
		Price:             price,
		PublicKey:         appRequest.TaskTypeIn.PublicKey,
		Complexity:        appRequest.TaskTypeIn.Complexity,
		HardwareRequire:   string(hardwareRequire),
		ImageId:           appRequest.TaskTypeIn.ImageId,
		ImageUrl:          appRequest.TaskTypeIn.ImageUrl,
		Type:              int(appRequest.TaskTypeIn.Type),
		Kind:              appRequest.TaskTypeIn.Kind,
		Cmd:               string(cmd),
		Workload:          appRequest.TaskTypeIn.Workload,
		ApiPath:           appRequest.TaskTypeIn.ApiPath,
		ImageName:         appRequest.TaskTypeIn.ImageName,
		SignUrl:           appRequest.TaskTypeIn.SignUrl,
		Username:          appRequest.TaskTypeIn.Username,
		Password:          appRequest.TaskTypeIn.Password,
		Category:          appRequest.TaskTypeIn.Category,
		ResultFileExpires: appRequest.TaskTypeIn.ResultFileExpires,
		PublishStatus:     appRequest.TaskTypeIn.PublishStatus,
		AccessStatus:      appRequest.TaskTypeIn.AccessStatus,
		UpdatedTime:       timestamp,
	}

	_, err = ormer.Update(&dbType, "name",
		"base_model",
		"model",
		"version",
		"desc",
		"price",
		"public_key",
		"complexity",
		"hardware_require",
		"image_id",
		"image_url",
		"type",
		"kind",
		"cmd",
		"workload",
		"api_path",
		"image_name",
		"sign_url",
		"username",
		"password",
		"category",
		"result_file_expires",
		"updated_time",
		"publish_status",
		"access_status")
brent's avatar
brent committed
1719 1720
	if err != nil {
		//ormer.Rollback()
brent's avatar
brent committed
1721
		server.respond(models.BusinessFailed, "failed")
brent's avatar
brent committed
1722 1723 1724
		return
	}
	dataString, err := redis.GetDataToString(cronjob.HeatKey)
brent's avatar
brent committed
1725
	var response []*models.TaskHeat
brent's avatar
brent committed
1726 1727 1728 1729 1730 1731 1732
	if err != nil {
		logs.Debug("GetDataToString err")
	}
	err = json.Unmarshal([]byte(dataString), &response)
	if err != nil {
		logs.Debug("GetDataToString Unmarshal err")
	}
brent's avatar
brent committed
1733 1734 1735 1736 1737 1738 1739 1740 1741

	var output interface{}
	if checkType.Form != "" {
		//var form interface{}
		err = json.Unmarshal([]byte(checkType.Form), &output)
		if err != nil {
			logs.Debug("Form Unmarshal err")
		}
	}
brent's avatar
brent committed
1742 1743 1744 1745 1746 1747 1748 1749 1750 1751
	for _, task := range response {
		if task.TaskId == dbType.Id {
			task.User = dbType.Username
			task.Pwd = dbType.Password
			task.Repository = dbType.ImageUrl
			task.SignUrl = dbType.SignUrl
			task.ImageName = dbType.ImageName
			task.ImageId = dbType.ImageId
			task.HardwareRequire = appRequest.TaskTypeIn.HardwareRequire
			task.Kind = dbType.Kind
brent's avatar
brent committed
1752 1753
			task.FileExpiresTime = strconv.Itoa(dbType.ResultFileExpires)
			task.OutPutJson = output
brent's avatar
brent committed
1754 1755
			task.AccessStatus = dbType.AccessStatus
			task.PublishStatus = dbType.PublishStatus
brent's avatar
brent committed
1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779
		}
	}
	data, err := json.Marshal(response)
	if err == nil {
		redis.SetKeyAndData(cronjob.HeatKey, string(data), 0)
	}

	//todo:插入model表,并且关联task_type_id
	//var levels []models.UserLevelTaskType
	for _, value := range appRequest.Levels {
		value.UpdatedTime = timestamp
		_, err = ormer.Update(&value)
		//if err != nil {
		//	//ormer.Rollback()
		//	//server.respond(models.BusinessFailed, "填加 task type 失败")
		//	return
		//}
	}

	//err = ormer.Commit()
	//if err != nil {
	//	server.respond(models.BusinessFailed, "填加 task type 失败")
	//	return
	//}
brent's avatar
brent committed
1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805

	task := model.TaskType{
		ID:              int64(dbType.Id),
		BaseModel:       dbType.BaseModel,
		Model:           dbType.Model,
		Desc:            dbType.Desc,
		Price:           price,
		PublicKey:       dbType.PublicKey,
		Complexity:      int64(dbType.Complexity),
		HardwareRequire: string(hardwareRequire),
		ImageId:         dbType.ImageId,
		ImageUrl:        dbType.ImageUrl,
		Type:            int(dbType.Type),
		Kind:            dbType.Kind,
		Cmd:             string(cmd),
		Workload:        int64(dbType.Workload),
		ApiPath:         dbType.ApiPath,
		ImageName:       dbType.ImageName,
		SignUrl:         dbType.SignUrl,
		Username:        dbType.Username,
		Password:        dbType.Password,
		CreatedTime:     appRequest.TaskTypeIn.CreatedTime,
		UpdatedTime:     dbType.UpdatedTime,
	}

	odysseus.SetTaskDataToRedis(&task)
brent's avatar
brent committed
1806
	odysseus.PublichTaskUpdate(dbType.ApiPath)
brent's avatar
brent committed
1807
	server.respond(http.StatusOK, "success")
brent's avatar
brent committed
1808 1809 1810 1811 1812 1813 1814 1815
}

func (server *TaskController) GetTaskTypes() {
	_, err := server.Check()
	if err != nil {
		server.respond(http.StatusUnauthorized, err.Error())
		return
	}
brent's avatar
brent committed
1816 1817 1818 1819 1820

	body := server.Ctx.Input.RequestBody
	appRequest := models.AppRequest{}
	err = json.Unmarshal(body, &appRequest) //解析body中数据
	logs.Debug("appRequest", appRequest, string(body))
brent's avatar
brent committed
1821 1822 1823 1824
	//if err != nil {
	//	server.respond(models.NoRequestBody, err.Error())
	//	return
	//}
brent's avatar
brent committed
1825 1826 1827 1828 1829 1830 1831 1832 1833

	if appRequest.Page == 0 {
		appRequest.Page = 1
	}

	if appRequest.Size == 0 {
		appRequest.Size = 10
	}
	offset := (appRequest.Page - 1) * appRequest.Size
brent's avatar
brent committed
1834
	//size := appRequest.Page * appRequest.Size
brent's avatar
brent committed
1835

brent's avatar
brent committed
1836 1837 1838 1839
	qs := mysql.GetMysqlInstace().Ormer.QueryTable("task_type").Filter("deleted", 0)
	infoQs := qs.Offset(offset).Limit(appRequest.Size)
	count, err := infoQs.Count()
	logs.Debug("Levels = ", count)
brent's avatar
brent committed
1840
	var types []*models.TaskType
brent's avatar
brent committed
1841 1842
	if count > 0 {
		infoQs.All(&types)
brent's avatar
brent committed
1843
	}
brent's avatar
brent committed
1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854
	var remodels []*models.NewTaskType
	for _, data := range types {
		var hardwareRequire interface{}
		eer := json.Unmarshal([]byte(data.HardwareRequire), &hardwareRequire)
		if eer != nil {

		}
		var cmd interface{}
		eer = json.Unmarshal([]byte(data.Cmd), &cmd)
		if eer != nil {

brent's avatar
brent committed
1855
		}
brent's avatar
brent committed
1856
		var examples interface{}
brent's avatar
brent committed
1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869
		eer = json.Unmarshal([]byte(data.Examples), &examples)
		if eer != nil {

		}
		var codes interface{}
		eer = json.Unmarshal([]byte(data.Codes), &codes)
		if eer != nil {

		}
		var tags []string
		eer = json.Unmarshal([]byte(data.Tags), &tags)
		if eer != nil {

brent's avatar
brent committed
1870 1871
		}
		remodel := models.NewTaskType{
brent's avatar
brent committed
1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884
			Id:                data.Id,
			Name:              data.Name,
			BaseModel:         data.BaseModel,
			Model:             data.Model,
			Version:           data.Version,
			Desc:              data.Desc,
			Price:             float64(data.Price / 1000000),
			PublicKey:         data.PublicKey,
			Complexity:        data.Complexity,
			Type:              models.ModelType(data.Type),
			TypeDesc:          models.ModelType(data.Type).String(),
			Kind:              data.Kind,
			KindDesc:          models.TaskKind(data.Kind).String(),
brent's avatar
brent committed
1885
			KindDescEn:        models.TaskKind(data.Kind).EnString(),
brent's avatar
brent committed
1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902
			Category:          data.Category,
			HardwareRequire:   hardwareRequire,
			ImageId:           data.ImageId,
			ImageUrl:          data.ImageUrl,
			Cmd:               cmd,
			Workload:          data.Workload,
			ApiPath:           data.ApiPath,
			ImageName:         data.ImageName,
			SignUrl:           data.SignUrl,
			Username:          data.Username,
			Password:          data.Password,
			Examples:          examples,
			Codes:             codes,
			Tags:              tags,
			PublishStatus:     data.PublishStatus,
			AccessStatus:      data.AccessStatus,
			ResultFileExpires: data.ResultFileExpires,
brent's avatar
brent committed
1903 1904 1905
		}
		remodels = append(remodels, &remodel)
	}
brent's avatar
brent committed
1906
	total, err := qs.Count()
brent's avatar
brent committed
1907 1908 1909 1910 1911 1912 1913
	responseData := struct {
		Total int64       `json:"total"`
		Data  interface{} `json:"data,omitempty"`
	}{
		Total: total,
		Data:  remodels,
	}
brent's avatar
brent committed
1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978

	//sql := "SELECT count(*) FROM task_type WHERE deleted = 0;"
	//var total int64
	//mysql.GetMysqlInstace().Ormer.Raw(sql).QueryRow(&total)
	//logs.Debug("total = %d", total)
	//if total == 0 {
	//	responseData := struct {
	//		Total int64       `json:"total"`
	//		Data  interface{} `json:"data,omitempty"`
	//	}{
	//		Total: total,
	//		Data:  types,
	//	}
	//	server.respond(http.StatusOK, "", responseData)
	//	return
	//}
	//sql = fmt.Sprintf("SELECT * FROM task_type WHERE deleted = 0 LIMIT %d,%d;", offset, size)
	//mysql.GetMysqlInstace().Ormer.Raw(sql).QueryRows(&types)
	//var remodels []*models.NewTaskType
	//for _, data := range types {
	//	var hardwareRequire interface{}
	//	eer := json.Unmarshal([]byte(data.HardwareRequire), &hardwareRequire)
	//	if eer != nil {
	//
	//	}
	//	var cmd interface{}
	//	eer = json.Unmarshal([]byte(data.Cmd), &cmd)
	//	if eer != nil {
	//
	//	}
	//	remodel := models.NewTaskType{
	//		Id:              data.Id,
	//		Name:            data.Name,
	//		BaseModel:       data.BaseModel,
	//		Model:           data.Model,
	//		Version:         data.Version,
	//		Desc:            data.Desc,
	//		Price:           float64(data.Price / 1000000),
	//		PublicKey:       data.PublicKey,
	//		Complexity:      data.Complexity,
	//		Type:            models.ModelType(data.Type),
	//		TypeDesc:        models.ModelType(data.Type).String(),
	//		Kind:            data.Kind,
	//		KindDesc:        models.TaskKind(data.Kind).String(),
	//		Category:        data.Category,
	//		HardwareRequire: hardwareRequire,
	//		ImageId:         data.ImageId,
	//		ImageUrl:        data.ImageUrl,
	//		Cmd:             cmd,
	//		Workload:        data.Workload,
	//		ApiPath:         data.ApiPath,
	//		ImageName:       data.ImageName,
	//		SignUrl:         data.SignUrl,
	//		Username:        data.Username,
	//		Password:        data.Password,
	//	}
	//	remodels = append(remodels, &remodel)
	//}
	//responseData := struct {
	//	Total int64       `json:"total"`
	//	Data  interface{} `json:"data,omitempty"`
	//}{
	//	Total: total,
	//	Data:  remodels,
	//}
brent's avatar
brent committed
1979
	server.respond(http.StatusOK, "", responseData)
brent's avatar
brent committed
1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014

	//qb, _ := orm.NewQueryBuilder("mysql")
	//
	//// 构建查询对象
	//qb.Select("name", "type", "").
	//	From("user").
	//	InnerJoin("profile").On("user.id_user = profile.fk_user").
	//	Where("age > ?").
	//	OrderBy("name").Desc().
	//	Limit(10).Offset(0)
	//
	//// 导出 SQL 语句
	////sql := qb.String()
	//sql := "SELECT `name` AS tit,type,`desc` AS content, tags ,examples,codes,base_model,api_path,version FROM task_type WHERE deleted = 0;"
	//
	//// 执行 SQL 语句
	//o := orm.NewOrm()
	//o.Raw(sql, 20).QueryRows(&types)

	//qs := mysql.GetMysqlInstace().Ormer.QueryTable("task_type")
	//mysql.GetMysqlInstace().Ormer.LoadRelated(types, "UserLevelTaskType")
	//count, err := qs.Count()
	//logs.Debug("types = ", count)
	//var types []*models.TaskType
	//if count > 0 {
	//	qs.All(&types)
	//	//mysql.GetMysqlInstace().Ormer.LoadRelated(types, "UserLevelTaskType")
	//	//for _, dbType := range types {
	//	//	var levels []*models.UserLevelTaskType
	//	//	qs := mysql.GetMysqlInstace().Ormer.QueryTable(" user_level_task_type ")
	//	//}
	//}
	//server.respond(http.StatusOK, "", types)
}

brent's avatar
brent committed
2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031
func (server *TaskController) DelTaskType() {
	_, err := server.Check()
	if err != nil {
		server.respond(http.StatusUnauthorized, err.Error())
		return
	}
	body := server.Ctx.Input.RequestBody
	logs.Debug("AddLevel body", string(body))
	request := models.TaskType{}
	err = json.Unmarshal(body, &request) //解析body中数据
	logs.Debug("request", request)
	if err != nil {
		server.respond(models.NoRequestBody, err.Error())
		return
	}

	if request.Id == 0 {
brent's avatar
brent committed
2032
		server.respond(models.MissingParameter, "Missing id parameter")
brent's avatar
brent committed
2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043
		return
	}
	checkType := &models.TaskType{Id: request.Id}
	err = mysql.GetMysqlInstace().Ormer.Read(checkType)
	if err != nil {
		server.respond(models.BusinessFailed, err.Error())
		return
	}
	checkType.Deleted = 1

	mysql.GetMysqlInstace().Ormer.Update(checkType)
brent's avatar
brent committed
2044
	server.respond(http.StatusOK, "success")
brent's avatar
brent committed
2045 2046
}

brent's avatar
brent committed
2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061
func (server *TaskController) AddOrUpdateExamples() {
	_, err := server.Check()
	if err != nil {
		server.respond(http.StatusUnauthorized, err.Error())
		return
	}
	body := server.Ctx.Input.RequestBody
	appRequest := models.NewTaskType{}
	err = json.Unmarshal(body, &appRequest) //解析body中数据
	logs.Debug("appRequest", appRequest)
	if err != nil {
		server.respond(models.NoRequestBody, err.Error())
		return
	}
	if appRequest.Id == 0 {
brent's avatar
brent committed
2062
		server.respond(models.MissingParameter, "Missing id parameter")
brent's avatar
brent committed
2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095
		return
	}

	checkType := &models.TaskType{Id: appRequest.Id}
	err = mysql.GetMysqlInstace().Ormer.Read(checkType)
	if err != nil {
		server.respond(models.BusinessFailed, err.Error())
		return
	}
	if appRequest.Examples != nil {
		examples, _ := json.Marshal(appRequest.Examples)
		checkType.Examples = string(examples)
	}

	if appRequest.Codes != nil {
		codes, _ := json.Marshal(appRequest.Codes)
		checkType.Codes = string(codes)
	}

	if appRequest.Tags != nil {
		tags, _ := json.Marshal(appRequest.Tags)
		checkType.Tags = string(tags)
	}

	checkType.ApiDocUrl = appRequest.ApiDocUrl
	checkType.ApiDocContent = appRequest.ApiDocContent

	_, err = mysql.GetMysqlInstace().Ormer.Update(checkType)
	if err != nil {
		server.respond(models.BusinessFailed, err.Error())
		return
	}

brent's avatar
brent committed
2096
	server.respond(http.StatusOK, "success")
brent's avatar
brent committed
2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120
}

func (server *TaskController) Examples() {
	body := server.Ctx.Input.RequestBody

	appRequest := models.AppRequest{}
	//if len(body) <= 0 {
	//	appRequest.Page == 1
	//}
	_ = json.Unmarshal(body, &appRequest) //解析body中数据
	logs.Debug("appRequest", appRequest, string(body))
	//if err != nil {
	//	server.respond(models.NoRequestBody, err.Error())
	//	return
	//}

	if appRequest.Page == 0 {
		appRequest.Page = 1
	}

	if appRequest.Size == 0 {
		appRequest.Size = 10
	}
	offset := (appRequest.Page - 1) * appRequest.Size
brent's avatar
brent committed
2121
	size := appRequest.Page * appRequest.Size
brent's avatar
brent committed
2122 2123 2124 2125

	where := ""
	if appRequest.Id != 0 {
		where = fmt.Sprintf("and id = %d", appRequest.Id)
brent's avatar
brent committed
2126 2127 2128 2129 2130 2131
	} else {
		if appRequest.Keyword != "" {
			keyword := "%" + appRequest.Keyword + "%"
			where = fmt.Sprintf("and (`name` LIKE '%s' OR `desc` LIKE '%s' OR tags LIKE '%s')", keyword, keyword, keyword)
		}
		if appRequest.Category != 0 {
brent's avatar
brent committed
2132
			where = fmt.Sprintf("%s and category = %d", where, appRequest.Category)
brent's avatar
brent committed
2133
		}
brent's avatar
brent committed
2134 2135 2136
	}

	var types []*models.Model
brent's avatar
brent committed
2137

brent's avatar
brent committed
2138
	sql := fmt.Sprintf("SELECT count(*) FROM task_type WHERE deleted = 0 %s;", where)
brent's avatar
brent committed
2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153
	var total int64
	mysql.GetMysqlInstace().Ormer.Raw(sql).QueryRow(&total)
	logs.Debug("total = %d", total)
	if total == 0 {
		responseData := struct {
			Total int64       `json:"total"`
			Data  interface{} `json:"data,omitempty"`
		}{
			Total: total,
			Data:  types,
		}
		server.respond(http.StatusOK, "", responseData)
		return
	}

brent's avatar
brent committed
2154
	sql = fmt.Sprintf("SELECT id, `name` AS tit,type,`desc` AS content, tags ,price,examples,codes,base_model,model,api_path,version,category,form,access_status,publish_status FROM task_type WHERE deleted = 0 %s order by codes desc LIMIT %d,%d;", where, offset, size)
brent's avatar
brent committed
2155 2156 2157
	mysql.GetMysqlInstace().Ormer.Raw(sql).QueryRows(&types)
	var remodels []*models.ResonseModel
	for _, data := range types {
brent's avatar
brent committed
2158 2159 2160
		//if data.Id == 19 {
		//	logs.Debug("")
		//}
brent's avatar
brent committed
2161
		var examples interface{}
brent's avatar
brent committed
2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174
		eer := json.Unmarshal([]byte(data.Examples), &examples)
		if eer != nil {

		}
		var codes interface{}
		eer = json.Unmarshal([]byte(data.Codes), &codes)
		if eer != nil {

		}
		var tags interface{}
		eer = json.Unmarshal([]byte(data.Tags), &tags)
		if eer != nil {

brent's avatar
brent committed
2175 2176 2177 2178 2179
		}
		var form interface{}
		eer = json.Unmarshal([]byte(data.Form), &form)
		if eer != nil {

brent's avatar
brent committed
2180 2181
		}
		remodel := models.ResonseModel{
brent's avatar
brent committed
2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197
			Id:                data.Id,
			Tit:               data.Tit,
			Version:           data.Version,
			Content:           data.Content,
			Type:              data.Type,
			ApiPath:           data.ApiPath,
			BaseModel:         data.BaseModel,
			Model:             data.Model,
			Examples:          examples,
			ApiDocUrl:         data.ApiDocUrl,
			ApiDocContent:     data.ApiDocContent,
			Codes:             codes,
			Tags:              tags,
			Category:          data.Category,
			Form:              form,
			ResultFileExpires: data.ResultFileExpires,
brent's avatar
brent committed
2198 2199
			AccessStatus:      data.AccessStatus,
			PublishStatus:     data.PublishStatus,
brent's avatar
brent committed
2200
			Price:             float64(data.Price / 1000000),
brent's avatar
brent committed
2201 2202 2203
		}
		remodels = append(remodels, &remodel)
	}
brent's avatar
brent committed
2204 2205 2206 2207 2208 2209 2210 2211
	responseData := struct {
		Total int64       `json:"total"`
		Data  interface{} `json:"data,omitempty"`
	}{
		Total: total,
		Data:  remodels,
	}
	server.respond(http.StatusOK, "", responseData)
brent's avatar
brent committed
2212 2213
}

brent's avatar
brent committed
2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246
func (server *TaskController) RunCount() {
	//_, err := server.Check()
	//if err != nil {
	//	server.respond(http.StatusUnauthorized, err.Error())
	//	return
	//}
	body := server.Ctx.Input.RequestBody
	appRequest := models.AppRequest{}
	err := json.Unmarshal(body, &appRequest) //解析body中数据
	logs.Debug("appRequest", appRequest)
	if err != nil {
		server.respond(models.NoRequestBody, err.Error())
		return
	}
	if appRequest.Id == 0 {
		server.respond(models.MissingParameter, "Missing id parameter")
		return
	}

	sql := fmt.Sprintf("SELECT type,count(type) FROM bills WHERE type = '%d';", appRequest.Id)
	datas, err := postgres.CountTasks(sql)
	if err != nil {
		server.respond(http.StatusOK, err.Error())
		return
	}

	var data models.TaskCount
	if len(datas) > 0 {
		data = datas[0]
	}
	server.respond(http.StatusOK, "", data)
}

brent's avatar
brent committed
2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261
func (server *TaskController) GetLevelsByTypeId() {
	_, err := server.Check()
	if err != nil {
		server.respond(http.StatusUnauthorized, err.Error())
		return
	}
	body := server.Ctx.Input.RequestBody
	appRequest := models.AppRequest{}
	err = json.Unmarshal(body, &appRequest) //解析body中数据
	logs.Debug("appRequest", appRequest)
	if err != nil {
		server.respond(models.NoRequestBody, err.Error())
		return
	}
	if appRequest.Id == 0 {
brent's avatar
brent committed
2262
		server.respond(models.MissingParameter, "Missing id parameter")
brent's avatar
brent committed
2263 2264 2265 2266 2267 2268 2269 2270
		return
	}
	var types []*models.UserLevelTaskType
	qs := mysql.GetMysqlInstace().Ormer.QueryTable("user_level_task_type").Filter("task_type_id", appRequest.Id)
	//mysql.GetMysqlInstace().Ormer.LoadRelated(types, "UserLevelTaskType")
	count, err := qs.Count()
	logs.Debug("types = ", count)
	//var types []*models.TaskType
brent's avatar
brent committed
2271 2272
	if count > 0 {
		qs.All(&types)
brent's avatar
brent committed
2273 2274 2275 2276 2277
		//mysql.GetMysqlInstace().Ormer.LoadRelated(types, "UserLevelTaskType")
		//for _, dbType := range types {
		//	var levels []*models.UserLevelTaskType
		//	qs := mysql.GetMysqlInstace().Ormer.QueryTable(" user_level_task_type ")
		//}
brent's avatar
brent committed
2278 2279 2280 2281
	}
	server.respond(http.StatusOK, "", types)
}

brent's avatar
brent committed
2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294
func (server *TaskController) AllCategorys() {
	var category []*models.Category
	qs := mysql.GetMysqlInstace().Ormer.QueryTable("category").
		Filter("deleted", 0).
		OrderBy("sort")
	count, _ := qs.Count()
	logs.Debug("types = ", count)
	if count > 0 {
		qs.All(&category)
	}
	server.respond(http.StatusOK, "", category)
}

brent's avatar
brent committed
2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316
func (server *TaskController) Enumeration() {
	_, err := server.Check()
	if err != nil {
		server.respond(http.StatusUnauthorized, err.Error())
		return
	}
	var categorys []*models.Category
	qs := mysql.GetMysqlInstace().Ormer.QueryTable("category").Filter("deleted", 0)
	//mysql.GetMysqlInstace().Ormer.LoadRelated(types, "UserLevelTaskType")
	count, err := qs.Count()
	logs.Debug("types = ", count)
	//var types []*models.TaskType
	if count > 0 {
		qs.All(&categorys)
		//mysql.GetMysqlInstace().Ormer.LoadRelated(types, "UserLevelTaskType")
		//for _, dbType := range types {
		//	var levels []*models.UserLevelTaskType
		//	qs := mysql.GetMysqlInstace().Ormer.QueryTable(" user_level_task_type ")
		//}
	}

	var types []*models.EnumType
brent's avatar
brent committed
2317
	for _, value := range [...]models.ModelType{models.TXTTOIMG, models.TXTTOTXT, models.TXTTOVIDEO, models.IMGTOTXT, models.IMGTOVIDEO, models.IMGTOIMG, models.IMGTXTTOTXT, models.IMGTXTTOIMG, models.IMGTXTTOVIDEO, models.TXTTOSPEECH, models.SPEECHTOTXT} {
brent's avatar
brent committed
2318 2319 2320 2321 2322 2323 2324 2325
		typeData := models.EnumType{
			Id:     int(value),
			Desc:   value.String(),
			EnDesc: "",
		}
		types = append(types, &typeData)
	}

brent's avatar
brent committed
2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345
	var publishStatusEnumS []*models.EnumType
	for _, value := range [...]models.PublishStatusEnum{models.Publish, models.UnPublish} {
		typeData := models.EnumType{
			Id:     int(value),
			Desc:   value.String(),
			EnDesc: "",
		}
		publishStatusEnumS = append(publishStatusEnumS, &typeData)
	}

	var accessStatusEnums []*models.EnumType
	for _, value := range [...]models.AccessStatusEnum{models.Public, models.Private} {
		typeData := models.EnumType{
			Id:     int(value),
			Desc:   value.String(),
			EnDesc: "",
		}
		accessStatusEnums = append(accessStatusEnums, &typeData)
	}

brent's avatar
brent committed
2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369
	var kinds []*models.EnumType
	for _, value := range [...]models.TaskKind{models.SystemTask, models.ComputeTask, models.CustomTask, models.StandardTask} {
		typeData := models.EnumType{
			Id:     int(value),
			Desc:   value.String(),
			EnDesc: value.EnString(),
		}
		kinds = append(kinds, &typeData)
	}

	var feeConditionEnums []*models.EnumType
	for _, value := range [...]models.FeeConditionEnum{models.FeeAll, models.FeeFree, models.FeeBased} {
		typeData := models.EnumType{
			Id:     int(value),
			Desc:   value.String(),
			EnDesc: value.EnString(),
		}
		feeConditionEnums = append(feeConditionEnums, &typeData)
	}
	responseData := struct {
		Categorys     []*models.Category `json:"categorys,omitempty"`
		Types         []*models.EnumType `json:"types,omitempty"`
		Kinds         []*models.EnumType `json:"kinds,omitempty"`
		FeeConditions []*models.EnumType `json:"fee_conditions,omitempty"`
brent's avatar
brent committed
2370 2371
		AccessStatus  []*models.EnumType `json:"access_status,omitempty"`
		PublishStatus []*models.EnumType `json:"publish_status,omitempty"`
brent's avatar
brent committed
2372 2373 2374 2375 2376
	}{
		Categorys:     categorys,
		Types:         types,
		Kinds:         kinds,
		FeeConditions: feeConditionEnums,
brent's avatar
brent committed
2377 2378
		AccessStatus:  accessStatusEnums,
		PublishStatus: publishStatusEnumS,
brent's avatar
brent committed
2379 2380 2381 2382
	}
	server.respond(http.StatusOK, "", responseData)
}

brent's avatar
brent committed
2383 2384 2385 2386 2387 2388 2389 2390 2391
func taskTypeCount() int64 {
	qs := mysql.GetMysqlInstace().Ormer.QueryTable("task_type")
	count, err := qs.Count()
	if err != nil {
		return 0
	}
	return count
}

brent's avatar
brent committed
2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405
func initTypeInRedis() []models.TaskHeat {
	qs := mysql.GetMysqlInstace().Ormer.QueryTable("task_type")
	count, _ := qs.Count()
	logs.Debug("types = ", count)
	var types []*models.TaskType
	if count > 0 {
		qs.All(&types)
	}
	var response []models.TaskHeat
	for _, dbType := range types {
		var hardwareRequire interface{}
		eer := json.Unmarshal([]byte(dbType.HardwareRequire), &hardwareRequire)
		if eer != nil {

brent's avatar
brent committed
2406 2407 2408 2409 2410 2411 2412
		}
		var output interface{}
		if dbType.Form != "" {
			err := json.Unmarshal([]byte(dbType.Form), &output)
			if err != nil {
				logs.Debug("Form Unmarshal err")
			}
brent's avatar
brent committed
2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424
		}
		retask := models.TaskHeat{
			TaskId:          dbType.Id,
			User:            dbType.Username,
			Pwd:             dbType.Password,
			Repository:      dbType.ImageUrl,
			SignUrl:         dbType.SignUrl,
			ImageName:       dbType.ImageName,
			ImageId:         dbType.ImageId,
			HardwareRequire: hardwareRequire,
			Count:           int64(0),
			Kind:            dbType.Kind,
brent's avatar
brent committed
2425 2426
			FileExpiresTime: strconv.Itoa(dbType.ResultFileExpires),
			OutPutJson:      output,
brent's avatar
brent committed
2427 2428
			AccessStatus:    dbType.AccessStatus,
			PublishStatus:   dbType.PublishStatus,
brent's avatar
brent committed
2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439
		}
		response = append(response, retask)
	}
	dataRedis, err := json.Marshal(response)
	if err == nil {
		redis.SetKeyAndData(cronjob.HeatKey, string(dataRedis), 0)
	}

	return response
}

brent's avatar
brent committed
2440
func (server *TaskController) TaskHeat() {
brent's avatar
brent committed
2441
	data, err := redis.GetDataToString(cronjob.HeatKey)
brent's avatar
brent committed
2442
	if data == "" || err != nil {
brent's avatar
brent committed
2443 2444 2445 2446 2447
		response := initTypeInRedis()
		server.respond(http.StatusOK, "", response)
		return
	}

brent's avatar
brent committed
2448
	var response []models.TaskHeat
brent's avatar
brent committed
2449
	err = json.Unmarshal([]byte(data), &response)
brent's avatar
brent committed
2450
	if err != nil {
brent's avatar
brent committed
2451
		response = initTypeInRedis()
brent's avatar
brent committed
2452 2453 2454
		server.respond(http.StatusOK, "", response)
		return
	}
brent's avatar
brent committed
2455 2456 2457
	count := taskTypeCount()
	if len(response) < int(count) {
		response = initTypeInRedis()
brent's avatar
brent committed
2458
		server.respond(http.StatusOK, "", response)
brent's avatar
brent committed
2459 2460
		return
	}
brent's avatar
brent committed
2461
	server.respond(http.StatusOK, "", response)
brent's avatar
brent committed
2462
}