vegapokerbot/internal/db/model/integration.go

112 lines
2.4 KiB
Go

package model
import (
"database/sql/driver"
"errors"
"gitea.neur0tx.site/Neur0toxine/vegapokerbot/internal/handler/store"
"gorm.io/datatypes"
)
type Integration struct {
ID uint64 `gorm:"primaryKey; autoIncrement;"`
Type IntegrationType `gorm:"column:type; not null"`
ChatID uint64 `gorm:"column:chat_id; not null"`
Params datatypes.JSONMap `gorm:"column:params; not null"`
}
func (i *Integration) StoreRedmine(rs *store.RedmineSetup) {
i.Params = map[string]interface{}{
"url": rs.URL,
"key": rs.Key,
"save_hours": rs.SaveHours,
"sp_field": rs.SPFieldName,
}
}
func (i *Integration) LoadRedmine() *store.RedmineSetup {
rs := &store.RedmineSetup{}
if param, ok := i.Params["url"]; ok {
if val, ok := param.(string); ok {
rs.URL = val
}
}
if param, ok := i.Params["key"]; ok {
if val, ok := param.(string); ok {
rs.Key = val
}
}
if param, ok := i.Params["save_hours"]; ok {
if val, ok := param.(bool); ok {
rs.SaveHours = val
}
}
if param, ok := i.Params["sp_field"]; ok {
if val, ok := param.(string); ok {
rs.SPFieldName = val
}
}
return rs
}
func (Integration) TableName() string {
return "integration"
}
type IntegrationType uint8
const (
InvalidIntegration IntegrationType = iota
RedmineIntegration
)
var (
integrationTypesToIds = map[string]IntegrationType{
"invalid": InvalidIntegration,
"redmine": RedmineIntegration,
}
idsToIntegrationTypes = map[IntegrationType]string{
InvalidIntegration: "invalid",
RedmineIntegration: "redmine",
}
)
func (it IntegrationType) String() string {
val, ok := idsToIntegrationTypes[it]
if ok {
return val
}
return idsToIntegrationTypes[InvalidIntegration]
}
func (it *IntegrationType) Scan(value interface{}) error {
switch v := value.(type) {
case nil:
*it = 0 // or whatever default you want to set if the field is null in db
return nil
case IntegrationType:
*it = v
case string:
// lookup the value from the map and assign it
val, ok := integrationTypesToIds[v]
if !ok {
return errors.New("invalid IntegrationType")
}
*it = val
default:
return errors.New("invalid type")
}
return nil
}
func (it IntegrationType) Value() (driver.Value, error) {
val, ok := idsToIntegrationTypes[it]
if ok {
return val, nil
}
return InvalidIntegration, nil
}
func (IntegrationType) GormDataType() string {
return "varchar(24)"
}