完善季度

This commit is contained in:
2024-08-29 09:05:26 +08:00
parent 2622876c70
commit a27c5f702f
13 changed files with 292 additions and 58 deletions

View File

@@ -1,6 +1,7 @@
package core
import (
init_db_data "energy-management-system/core/init-db-data"
"energy-management-system/global"
peak_valley "energy-management-system/model/peak-valley"
"fmt"
@@ -62,7 +63,8 @@ func AutoMigrate(db *gorm.DB) {
err := db.AutoMigrate(
new(peak_valley.PeakValleyTimeBlock),
new(peak_valley.PeakValleyTimeBlockPrice),
new(peak_valley.PeakValleyQuarterRule),
new(peak_valley.PeakValleyQuarter),
new(peak_valley.PeakValleyRule),
//new(model.Role),
//new(model.UserRole),
@@ -76,3 +78,7 @@ func AutoMigrate(db *gorm.DB) {
os.Exit(0)
}
}
func AutoInitDbData() {
init_db_data.InitDbData()
}

31
core/init-db-data/init.go Normal file
View File

@@ -0,0 +1,31 @@
package init_db_data
import (
"fmt"
"os"
)
type InitDBFunc interface {
Init() (err error)
}
// 初始化数据库
func initDB(InitDBFunctions ...InitDBFunc) (err error) {
for _, v := range InitDBFunctions {
err = v.Init()
if err != nil {
return err
}
}
return nil
}
func InitDbData() {
err := initDB(initPeakValleyTimeBlockData)
if err != nil {
fmt.Println("[-]初始化基础数据失败:", err)
os.Exit(0)
}
}
//

View File

@@ -0,0 +1,56 @@
package init_db_data
import (
"energy-management-system/global"
peak_valley_model "energy-management-system/model/peak-valley"
"github.com/gookit/color"
"gorm.io/gorm"
)
type InitPeakValleyTimeBlockData struct{}
var initPeakValleyTimeBlockData = new(InitPeakValleyTimeBlockData)
// type api struct{}
func buildData() (dataList []*peak_valley_model.PeakValleyTimeBlock) {
// 一天有24小时即1440分钟
totalMinutes := 24 * 60
// 时间块的持续时间10分钟
blockDuration := 10
// 遍历一天中的所有时间块
for i := 0; i < totalMinutes; i += blockDuration {
startTime := i
endTime := i + blockDuration
dataList = append(dataList, &peak_valley_model.PeakValleyTimeBlock{
StartTime: uint(startTime),
EndTime: uint(endTime),
})
}
return dataList
}
// Init 初始化用户数据
func (i *InitPeakValleyTimeBlockData) Init() error {
return global.Db.Transaction(func(tx *gorm.DB) error {
m := &peak_valley_model.PeakValleyTimeBlock{}
var count int64
err := tx.Model(&peak_valley_model.PeakValleyTimeBlock{}).Count(&count).Error
if err != nil {
return err
}
if count == 144 {
color.Danger.Println("\n[PGSQL] --> " + m.TableName() + " 表的初始数据已存在!")
return nil
}
dataList := buildData()
if err := tx.Create(&dataList).Error; err != nil { // 遇到错误时回滚事务
return err
}
color.Info.Println("\n[PGSQL] --> " + m.TableName() + "表初始数据成功!")
return nil
})
}