feat: project_type.
This commit is contained in:
@@ -0,0 +1,76 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type ProjectType struct {
|
||||
ID uint `gorm:"primaryKey" json:"id"`
|
||||
Code string `gorm:"size:64;not null;uniqueIndex" json:"code"`
|
||||
Name string `gorm:"size:255;not null" json:"name"`
|
||||
Description string `gorm:"size:1024" json:"description"`
|
||||
SupportsGateway bool `gorm:"not null;default:false;index" json:"supportsGateway"`
|
||||
IsActive bool `gorm:"not null;default:true;index" json:"isActive"`
|
||||
Sort int `gorm:"not null;default:0;index" json:"sort"`
|
||||
CreatedAt int64 `gorm:"not null" json:"created_at"`
|
||||
UpdatedAt int64 `gorm:"not null" json:"updated_at"`
|
||||
}
|
||||
|
||||
func (ProjectType) TableName() string {
|
||||
return "project_types"
|
||||
}
|
||||
|
||||
func (p *ProjectType) BeforeCreate(tx *gorm.DB) (err error) {
|
||||
now := time.Now().UnixMilli()
|
||||
p.Code = strings.TrimSpace(strings.ToLower(p.Code))
|
||||
p.Name = strings.TrimSpace(p.Name)
|
||||
p.Description = strings.TrimSpace(p.Description)
|
||||
p.CreatedAt = now
|
||||
p.UpdatedAt = now
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *ProjectType) BeforeUpdate(tx *gorm.DB) (err error) {
|
||||
p.Code = strings.TrimSpace(strings.ToLower(p.Code))
|
||||
p.Name = strings.TrimSpace(p.Name)
|
||||
p.Description = strings.TrimSpace(p.Description)
|
||||
p.UpdatedAt = time.Now().UnixMilli()
|
||||
return nil
|
||||
}
|
||||
|
||||
func EnsureDefaultProjectTypes(db *gorm.DB) error {
|
||||
defaults := []ProjectType{
|
||||
{Code: "flink", Name: "步频节拍器", Description: "Flink 步频节拍器项目", SupportsGateway: false, IsActive: true, Sort: 10},
|
||||
{Code: "light", Name: "心肺耐力测试", Description: "Light 心肺耐力测试项目", SupportsGateway: true, IsActive: true, Sort: 20},
|
||||
{Code: "heartrate", Name: "智能心率采集", Description: "智能心率采集项目", SupportsGateway: true, IsActive: true, Sort: 30},
|
||||
{Code: "run50", Name: "50米往返跑", Description: "50米往返跑项目", SupportsGateway: false, IsActive: true, Sort: 40},
|
||||
}
|
||||
|
||||
for _, item := range defaults {
|
||||
var existing ProjectType
|
||||
err := db.Where("code = ?", item.Code).First(&existing).Error
|
||||
switch {
|
||||
case err == nil:
|
||||
existing.Name = item.Name
|
||||
existing.Description = item.Description
|
||||
existing.SupportsGateway = item.SupportsGateway
|
||||
existing.IsActive = item.IsActive
|
||||
existing.Sort = item.Sort
|
||||
if err := db.Save(&existing).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
case errors.Is(err, gorm.ErrRecordNotFound):
|
||||
if err := db.Create(&item).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
default:
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user