feat: 实现 Bell 联系人与值班排班 (#183)
This commit is contained in:
@@ -0,0 +1,59 @@
|
||||
package contact
|
||||
|
||||
import (
|
||||
"crypto/aes"
|
||||
"crypto/cipher"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"io"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var ErrChannelKeyUnavailable = errors.New("联系人通道加密密钥未配置或格式错误")
|
||||
|
||||
func ParseChannelKey(value string) ([]byte, error) {
|
||||
key, err := base64.StdEncoding.DecodeString(strings.TrimSpace(value))
|
||||
if err != nil || len(key) != 32 {
|
||||
return nil, ErrChannelKeyUnavailable
|
||||
}
|
||||
return key, nil
|
||||
}
|
||||
|
||||
func encryptAddress(key []byte, value string) ([]byte, error) {
|
||||
block, err := aes.NewCipher(key)
|
||||
if err != nil {
|
||||
return nil, ErrChannelKeyUnavailable
|
||||
}
|
||||
gcm, err := cipher.NewGCM(block)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
nonce := make([]byte, gcm.NonceSize())
|
||||
if _, err = io.ReadFull(rand.Reader, nonce); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return gcm.Seal(nonce, nonce, []byte(value), nil), nil
|
||||
}
|
||||
|
||||
func decryptAddress(key, encoded []byte) (string, error) {
|
||||
block, err := aes.NewCipher(key)
|
||||
if err != nil {
|
||||
return "", ErrChannelKeyUnavailable
|
||||
}
|
||||
gcm, err := cipher.NewGCM(block)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if len(encoded) < gcm.NonceSize() {
|
||||
return "", errors.New("通道密文已损坏")
|
||||
}
|
||||
plain, err := gcm.Open(nil, encoded[:gcm.NonceSize()], encoded[gcm.NonceSize():], nil)
|
||||
return string(plain), err
|
||||
}
|
||||
|
||||
func fingerprint(value string) string {
|
||||
sum := sha256.Sum256([]byte(value))
|
||||
return base64.RawURLEncoding.EncodeToString(sum[:])
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
package contact
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"os"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/gin-gonic/gin/binding"
|
||||
"github.com/go-admin-team/go-admin-core/sdk/api"
|
||||
jwt "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth"
|
||||
"github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth/user"
|
||||
)
|
||||
|
||||
type Handler struct{ api.Api }
|
||||
type enabledInput struct {
|
||||
Enabled *bool `json:"enabled" binding:"required"`
|
||||
ExpectedVersion int `json:"expectedVersion" binding:"required"`
|
||||
}
|
||||
type validationInput struct {
|
||||
Status string `json:"status"`
|
||||
Detail string `json:"detail"`
|
||||
}
|
||||
|
||||
func (h Handler) service() (Service, error) {
|
||||
key, err := ParseChannelKey(os.Getenv("BELL_CONTACT_CHANNEL_KEY"))
|
||||
return NewService(h.Orm, key), err
|
||||
}
|
||||
func (h Handler) List(c *gin.Context) {
|
||||
var q PageQuery
|
||||
h.MakeContext(c).MakeOrm().Bind(&q, binding.Form)
|
||||
if h.Errors != nil {
|
||||
h.Error(400, ErrInvalid, ErrInvalid.Error())
|
||||
return
|
||||
}
|
||||
items, count, err := NewService(h.Orm, nil).List(c.Request.Context(), q)
|
||||
if err != nil {
|
||||
h.Error(500, errors.New("读取联系人失败"), "读取联系人失败")
|
||||
return
|
||||
}
|
||||
p, s := pageValues(q.PageIndex, q.PageSize)
|
||||
h.PageOK(items, int(count), p, s, "查询成功")
|
||||
}
|
||||
func (h Handler) Create(c *gin.Context) {
|
||||
if !admin(c) {
|
||||
h.MakeContext(c).Error(403, errors.New("仅管理员可维护联系人"), "仅管理员可维护联系人")
|
||||
return
|
||||
}
|
||||
var input WriteInput
|
||||
h.MakeContext(c).MakeOrm().Bind(&input, binding.JSON)
|
||||
if h.Errors != nil {
|
||||
h.Error(400, ErrInvalid, ErrInvalid.Error())
|
||||
return
|
||||
}
|
||||
item, err := NewService(h.Orm, nil).Create(c.Request.Context(), input, user.GetUserId(c))
|
||||
h.result(item, err)
|
||||
}
|
||||
func (h Handler) Update(c *gin.Context) {
|
||||
if !admin(c) {
|
||||
h.MakeContext(c).Error(403, errors.New("仅管理员可维护联系人"), "仅管理员可维护联系人")
|
||||
return
|
||||
}
|
||||
var input WriteInput
|
||||
h.MakeContext(c).MakeOrm().Bind(&input, binding.JSON)
|
||||
if h.Errors != nil {
|
||||
h.Error(400, ErrInvalid, ErrInvalid.Error())
|
||||
return
|
||||
}
|
||||
item, err := NewService(h.Orm, nil).Update(c.Request.Context(), c.Param("id"), input, user.GetUserId(c))
|
||||
h.result(item, err)
|
||||
}
|
||||
func (h Handler) SetEnabled(c *gin.Context) {
|
||||
if !admin(c) {
|
||||
h.MakeContext(c).Error(403, errors.New("仅管理员可维护联系人"), "仅管理员可维护联系人")
|
||||
return
|
||||
}
|
||||
var input enabledInput
|
||||
h.MakeContext(c).MakeOrm().Bind(&input, binding.JSON)
|
||||
if h.Errors != nil || input.Enabled == nil {
|
||||
h.Error(400, ErrInvalid, ErrInvalid.Error())
|
||||
return
|
||||
}
|
||||
item, err := NewService(h.Orm, nil).SetEnabled(c.Request.Context(), c.Param("id"), *input.Enabled, input.ExpectedVersion, user.GetUserId(c))
|
||||
h.result(item, err)
|
||||
}
|
||||
func (h Handler) AddChannel(c *gin.Context) {
|
||||
if !admin(c) {
|
||||
h.MakeContext(c).Error(403, errors.New("仅管理员可维护通道"), "仅管理员可维护通道")
|
||||
return
|
||||
}
|
||||
if err := restoreChannelBody(c); err != nil {
|
||||
h.MakeContext(c).Error(http.StatusBadRequest, ErrInvalid, ErrInvalid.Error())
|
||||
return
|
||||
}
|
||||
var input ChannelInput
|
||||
h.MakeContext(c).MakeOrm().Bind(&input, binding.JSON)
|
||||
if h.Errors != nil {
|
||||
h.Error(400, ErrInvalid, ErrInvalid.Error())
|
||||
return
|
||||
}
|
||||
service, keyErr := h.service()
|
||||
if keyErr != nil {
|
||||
h.Error(503, keyErr, keyErr.Error())
|
||||
return
|
||||
}
|
||||
item, err := service.AddChannel(c.Request.Context(), c.Param("id"), input, user.GetUserId(c))
|
||||
h.result(item, err)
|
||||
}
|
||||
func (h Handler) ValidateChannel(c *gin.Context) {
|
||||
if !admin(c) {
|
||||
h.MakeContext(c).Error(403, errors.New("仅管理员可验证通道"), "仅管理员可验证通道")
|
||||
return
|
||||
}
|
||||
var input validationInput
|
||||
h.MakeContext(c).MakeOrm().Bind(&input, binding.JSON)
|
||||
if h.Errors != nil {
|
||||
h.Error(400, ErrInvalid, ErrInvalid.Error())
|
||||
return
|
||||
}
|
||||
item, err := NewService(h.Orm, nil).RecordValidation(c.Request.Context(), c.Param("id"), input.Status, input.Detail, user.GetUserId(c))
|
||||
h.result(item, err)
|
||||
}
|
||||
func (h Handler) result(item any, err error) {
|
||||
switch {
|
||||
case err == nil:
|
||||
h.OK(item, "保存成功")
|
||||
case errors.Is(err, ErrInvalid):
|
||||
h.Error(400, err, err.Error())
|
||||
case errors.Is(err, ErrNotFound):
|
||||
h.Error(404, err, err.Error())
|
||||
case errors.Is(err, ErrConflict):
|
||||
h.Error(409, err, err.Error())
|
||||
case errors.Is(err, ErrChannelKeyUnavailable):
|
||||
h.Error(503, err, err.Error())
|
||||
default:
|
||||
h.Logger.Errorf("write Bell contact failed: %v", err)
|
||||
h.Error(409, errors.New("联系人保存失败"), "联系人保存失败")
|
||||
}
|
||||
}
|
||||
func admin(c *gin.Context) bool {
|
||||
claims := jwt.ExtractClaims(c)
|
||||
role, _ := claims[jwt.RoleKey].(string)
|
||||
return role == "admin"
|
||||
}
|
||||
|
||||
var _ = http.StatusOK
|
||||
@@ -0,0 +1,68 @@
|
||||
package contact
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Contact struct {
|
||||
ID string `json:"id" gorm:"type:uuid;primaryKey"`
|
||||
Name string `json:"name" gorm:"size:128;not null"`
|
||||
Role string `json:"role" gorm:"size:128;not null"`
|
||||
Enabled bool `json:"enabled" gorm:"not null;default:true;index"`
|
||||
Version int `json:"version" gorm:"not null;default:1"`
|
||||
CreatedBy int `json:"createdBy" gorm:"not null"`
|
||||
UpdatedBy int `json:"updatedBy" gorm:"not null"`
|
||||
CreatedAt time.Time `json:"createdAt" gorm:"type:timestamptz;not null"`
|
||||
UpdatedAt time.Time `json:"updatedAt" gorm:"type:timestamptz;not null"`
|
||||
}
|
||||
|
||||
func (Contact) TableName() string { return "bell_contacts" }
|
||||
|
||||
type Channel struct {
|
||||
ID string `json:"id" gorm:"type:uuid;primaryKey"`
|
||||
ContactID string `json:"contactId" gorm:"type:uuid;not null;index"`
|
||||
Kind string `json:"kind" gorm:"size:16;not null"`
|
||||
AddressCiphertext []byte `json:"-" gorm:"type:bytea;not null"`
|
||||
AddressFingerprint string `json:"-" gorm:"size:64;not null;index"`
|
||||
AddressMasked string `json:"addressMasked" gorm:"size:64;not null"`
|
||||
CreatedBy int `json:"createdBy" gorm:"not null"`
|
||||
CreatedAt time.Time `json:"createdAt" gorm:"type:timestamptz;not null"`
|
||||
}
|
||||
|
||||
func (Channel) TableName() string { return "bell_contact_channels" }
|
||||
|
||||
type ChannelValidation struct {
|
||||
ID string `json:"id" gorm:"type:uuid;primaryKey"`
|
||||
ChannelID string `json:"channelId" gorm:"type:uuid;not null;index"`
|
||||
Status string `json:"status" gorm:"size:16;not null"`
|
||||
Detail string `json:"detail" gorm:"size:256;not null"`
|
||||
ActorID int `json:"actorId" gorm:"not null"`
|
||||
CreatedAt time.Time `json:"createdAt" gorm:"type:timestamptz;not null;index"`
|
||||
}
|
||||
|
||||
func (ChannelValidation) TableName() string { return "bell_contact_channel_validations" }
|
||||
|
||||
type AuditFact struct {
|
||||
ID string `json:"id" gorm:"type:uuid;primaryKey"`
|
||||
ContactID string `json:"contactId" gorm:"type:uuid;not null;index"`
|
||||
Action string `json:"action" gorm:"size:32;not null"`
|
||||
Snapshot json.RawMessage `json:"snapshot" gorm:"type:jsonb;not null"`
|
||||
ActorID int `json:"actorId" gorm:"not null"`
|
||||
CreatedAt time.Time `json:"createdAt" gorm:"type:timestamptz;not null"`
|
||||
}
|
||||
|
||||
func (AuditFact) TableName() string { return "bell_contact_audit_facts" }
|
||||
|
||||
type ChannelView struct {
|
||||
ID string `json:"id"`
|
||||
Kind string `json:"kind"`
|
||||
AddressMasked string `json:"addressMasked"`
|
||||
Status string `json:"status"`
|
||||
ValidatedAt *time.Time `json:"validatedAt,omitempty"`
|
||||
}
|
||||
|
||||
type ContactView struct {
|
||||
Contact
|
||||
Channels []ChannelView `json:"channels"`
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package contact
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
const maxChannelRequestBytes = 8 * 1024
|
||||
const channelBodyKey = "bell.contact.channel-body"
|
||||
const channelBodyErrorKey = "bell.contact.channel-body-error"
|
||||
|
||||
var redactedChannelBody = []byte(`{"redacted":true}`)
|
||||
|
||||
// RedactRequestBody must run before GoAdmin's LoggerToFile middleware. The
|
||||
// handler restores the original body from Gin context, while sys_opera_log
|
||||
// only sees a fixed marker and never the contact address.
|
||||
func RedactRequestBody() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
if c.Request.Method != http.MethodPost || !isChannelCreatePath(c.Request.URL.Path) {
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
body, err := io.ReadAll(io.LimitReader(c.Request.Body, maxChannelRequestBytes+1))
|
||||
if err != nil {
|
||||
c.Set(channelBodyErrorKey, err)
|
||||
} else if len(body) > maxChannelRequestBytes {
|
||||
c.Set(channelBodyErrorKey, errors.New("request body too large"))
|
||||
} else {
|
||||
c.Set(channelBodyKey, body)
|
||||
}
|
||||
_ = c.Request.Body.Close()
|
||||
c.Request.Body = io.NopCloser(bytes.NewReader(redactedChannelBody))
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
func restoreChannelBody(c *gin.Context) error {
|
||||
if value, ok := c.Get(channelBodyErrorKey); ok {
|
||||
return value.(error)
|
||||
}
|
||||
value, ok := c.Get(channelBodyKey)
|
||||
if !ok {
|
||||
return errors.New("channel request body was not captured")
|
||||
}
|
||||
c.Request.Body = io.NopCloser(bytes.NewReader(value.([]byte)))
|
||||
return nil
|
||||
}
|
||||
|
||||
func isChannelCreatePath(path string) bool {
|
||||
const prefix = "/api/v1/bell/contacts/"
|
||||
const suffix = "/channels"
|
||||
if !strings.HasPrefix(path, prefix) || !strings.HasSuffix(path, suffix) {
|
||||
return false
|
||||
}
|
||||
id := strings.TrimSuffix(strings.TrimPrefix(path, prefix), suffix)
|
||||
return id != "" && !strings.Contains(id, "/")
|
||||
}
|
||||
@@ -0,0 +1,251 @@
|
||||
package contact
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type PageQuery struct {
|
||||
PageIndex int `form:"pageIndex"`
|
||||
PageSize int `form:"pageSize"`
|
||||
Name string `form:"name"`
|
||||
Enabled *bool `form:"enabled"`
|
||||
}
|
||||
type Service struct {
|
||||
DB *gorm.DB
|
||||
Key []byte
|
||||
}
|
||||
|
||||
func NewService(db *gorm.DB, key []byte) Service { return Service{DB: db, Key: key} }
|
||||
|
||||
func (s Service) List(ctx context.Context, query PageQuery) ([]ContactView, int64, error) {
|
||||
page, size := pageValues(query.PageIndex, query.PageSize)
|
||||
db := s.DB.WithContext(ctx).Model(&Contact{})
|
||||
if name := strings.TrimSpace(query.Name); name != "" {
|
||||
db = db.Where("name ILIKE ? OR role ILIKE ?", "%"+name+"%", "%"+name+"%")
|
||||
}
|
||||
if query.Enabled != nil {
|
||||
db = db.Where("enabled = ?", *query.Enabled)
|
||||
}
|
||||
var count int64
|
||||
if err := db.Count(&count).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
var contacts []Contact
|
||||
if err := db.Order("created_at DESC,id DESC").Offset((page - 1) * size).Limit(size).Find(&contacts).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
views := make([]ContactView, 0, len(contacts))
|
||||
for _, item := range contacts {
|
||||
view, err := s.view(ctx, item)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
views = append(views, view)
|
||||
}
|
||||
return views, count, nil
|
||||
}
|
||||
|
||||
func (s Service) Create(ctx context.Context, input WriteInput, actor int) (ContactView, error) {
|
||||
input, err := normalizeContact(input)
|
||||
if err != nil {
|
||||
return ContactView{}, err
|
||||
}
|
||||
now := time.Now().UTC()
|
||||
item := Contact{ID: uuid.NewString(), Name: input.Name, Role: input.Role, Enabled: true, Version: 1, CreatedBy: actor, UpdatedBy: actor, CreatedAt: now, UpdatedAt: now}
|
||||
err = s.DB.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
if err := tx.Create(&item).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return appendAudit(tx, item, "created", actor)
|
||||
})
|
||||
if err != nil {
|
||||
return ContactView{}, err
|
||||
}
|
||||
return ContactView{Contact: item, Channels: []ChannelView{}}, nil
|
||||
}
|
||||
|
||||
func (s Service) Update(ctx context.Context, id string, input WriteInput, actor int) (ContactView, error) {
|
||||
if _, err := uuid.Parse(id); err != nil {
|
||||
return ContactView{}, ErrNotFound
|
||||
}
|
||||
input, err := normalizeContact(input)
|
||||
if err != nil {
|
||||
return ContactView{}, err
|
||||
}
|
||||
if input.ExpectedVersion < 1 {
|
||||
return ContactView{}, ErrInvalid
|
||||
}
|
||||
var item Contact
|
||||
err = s.DB.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
result := tx.Model(&Contact{}).Where("id = ? AND version = ?", id, input.ExpectedVersion).Updates(map[string]any{"name": input.Name, "role": input.Role, "version": gorm.Expr("version + 1"), "updated_by": actor, "updated_at": time.Now().UTC()})
|
||||
if result.Error != nil {
|
||||
return result.Error
|
||||
}
|
||||
if result.RowsAffected != 1 {
|
||||
var count int64
|
||||
_ = tx.Model(&Contact{}).Where("id = ?", id).Count(&count).Error
|
||||
if count == 0 {
|
||||
return ErrNotFound
|
||||
}
|
||||
return ErrConflict
|
||||
}
|
||||
if err := tx.First(&item, "id = ?", id).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return appendAudit(tx, item, "updated", actor)
|
||||
})
|
||||
if err != nil {
|
||||
return ContactView{}, err
|
||||
}
|
||||
return s.view(ctx, item)
|
||||
}
|
||||
|
||||
func (s Service) SetEnabled(ctx context.Context, id string, enabled bool, expectedVersion, actor int) (ContactView, error) {
|
||||
if _, err := uuid.Parse(id); err != nil {
|
||||
return ContactView{}, ErrNotFound
|
||||
}
|
||||
if expectedVersion < 1 {
|
||||
return ContactView{}, ErrInvalid
|
||||
}
|
||||
var item Contact
|
||||
err := s.DB.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
result := tx.Model(&Contact{}).Where("id = ? AND version = ?", id, expectedVersion).Updates(map[string]any{"enabled": enabled, "version": gorm.Expr("version + 1"), "updated_by": actor, "updated_at": time.Now().UTC()})
|
||||
if result.Error != nil {
|
||||
return result.Error
|
||||
}
|
||||
if result.RowsAffected != 1 {
|
||||
return ErrConflict
|
||||
}
|
||||
if err := tx.First(&item, "id = ?", id).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return appendAudit(tx, item, map[bool]string{true: "enabled", false: "disabled"}[enabled], actor)
|
||||
})
|
||||
if err != nil {
|
||||
return ContactView{}, err
|
||||
}
|
||||
return s.view(ctx, item)
|
||||
}
|
||||
|
||||
func (s Service) AddChannel(ctx context.Context, contactID string, input ChannelInput, actor int) (ChannelView, error) {
|
||||
if len(s.Key) != 32 {
|
||||
return ChannelView{}, ErrChannelKeyUnavailable
|
||||
}
|
||||
if _, err := uuid.Parse(contactID); err != nil {
|
||||
return ChannelView{}, ErrNotFound
|
||||
}
|
||||
input, err := normalizeChannel(input)
|
||||
if err != nil {
|
||||
return ChannelView{}, err
|
||||
}
|
||||
ciphertext, err := encryptAddress(s.Key, input.Address)
|
||||
if err != nil {
|
||||
return ChannelView{}, err
|
||||
}
|
||||
now := time.Now().UTC()
|
||||
item := Channel{ID: uuid.NewString(), ContactID: contactID, Kind: input.Kind, AddressCiphertext: ciphertext, AddressFingerprint: fingerprint(input.Address), AddressMasked: maskAddress(input.Address), CreatedBy: actor, CreatedAt: now}
|
||||
err = s.DB.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
var contact Contact
|
||||
if err := tx.First(&contact, "id = ?", contactID).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return ErrNotFound
|
||||
}
|
||||
return err
|
||||
}
|
||||
if err := tx.Create(&item).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return appendAudit(tx, contact, "channel_added", actor)
|
||||
})
|
||||
if err != nil {
|
||||
return ChannelView{}, err
|
||||
}
|
||||
return ChannelView{ID: item.ID, Kind: item.Kind, AddressMasked: item.AddressMasked, Status: "pending"}, nil
|
||||
}
|
||||
|
||||
func (s Service) RecordValidation(ctx context.Context, channelID, status, detail string, actor int) (ChannelView, error) {
|
||||
status = strings.ToLower(strings.TrimSpace(status))
|
||||
detail = strings.TrimSpace(detail)
|
||||
if status != "verified" && status != "failed" {
|
||||
return ChannelView{}, ErrInvalid
|
||||
}
|
||||
if len([]rune(detail)) > 256 || hasControl(detail) {
|
||||
return ChannelView{}, ErrInvalid
|
||||
}
|
||||
var channel Channel
|
||||
fact := ChannelValidation{ID: uuid.NewString(), ChannelID: channelID, Status: status, Detail: detail, ActorID: actor, CreatedAt: time.Now().UTC()}
|
||||
err := s.DB.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
if err := tx.First(&channel, "id = ?", channelID).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return ErrNotFound
|
||||
}
|
||||
return err
|
||||
}
|
||||
if err := tx.Create(&fact).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
var c Contact
|
||||
if err := tx.First(&c, "id = ?", channel.ContactID).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return appendAudit(tx, c, "channel_validation_"+status, actor)
|
||||
})
|
||||
if err != nil {
|
||||
return ChannelView{}, err
|
||||
}
|
||||
return ChannelView{ID: channel.ID, Kind: channel.Kind, AddressMasked: channel.AddressMasked, Status: status, ValidatedAt: &fact.CreatedAt}, nil
|
||||
}
|
||||
|
||||
// DecryptChannelAddress is intentionally server-only. API responses never expose this value.
|
||||
func (s Service) DecryptChannelAddress(ctx context.Context, channelID string) (string, error) {
|
||||
var item Channel
|
||||
if err := s.DB.WithContext(ctx).First(&item, "id = ?", channelID).Error; err != nil {
|
||||
return "", err
|
||||
}
|
||||
return decryptAddress(s.Key, item.AddressCiphertext)
|
||||
}
|
||||
|
||||
func (s Service) view(ctx context.Context, item Contact) (ContactView, error) {
|
||||
var channels []Channel
|
||||
if err := s.DB.WithContext(ctx).Where("contact_id = ?", item.ID).Order("created_at,id").Find(&channels).Error; err != nil {
|
||||
return ContactView{}, err
|
||||
}
|
||||
views := make([]ChannelView, 0, len(channels))
|
||||
for _, ch := range channels {
|
||||
view := ChannelView{ID: ch.ID, Kind: ch.Kind, AddressMasked: ch.AddressMasked, Status: "pending"}
|
||||
var fact ChannelValidation
|
||||
err := s.DB.WithContext(ctx).Where("channel_id = ?", ch.ID).Order("created_at DESC,id DESC").Take(&fact).Error
|
||||
if err == nil {
|
||||
view.Status = fact.Status
|
||||
view.ValidatedAt = &fact.CreatedAt
|
||||
} else if !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return ContactView{}, err
|
||||
}
|
||||
views = append(views, view)
|
||||
}
|
||||
return ContactView{Contact: item, Channels: views}, nil
|
||||
}
|
||||
|
||||
func appendAudit(tx *gorm.DB, item Contact, action string, actor int) error {
|
||||
snapshot, err := json.Marshal(map[string]any{"id": item.ID, "name": item.Name, "role": item.Role, "enabled": item.Enabled, "version": item.Version})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Create(&AuditFact{ID: uuid.NewString(), ContactID: item.ID, Action: action, Snapshot: snapshot, ActorID: actor, CreatedAt: time.Now().UTC()}).Error
|
||||
}
|
||||
func pageValues(page, size int) (int, int) {
|
||||
if page < 1 {
|
||||
page = 1
|
||||
}
|
||||
if size < 1 || size > 100 {
|
||||
size = 20
|
||||
}
|
||||
return page, size
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package contact
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"regexp"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrInvalid = errors.New("联系人或通道信息不符合要求")
|
||||
ErrNotFound = errors.New("联系人或通道不存在")
|
||||
ErrConflict = errors.New("数据已被其他人员更新,请刷新后重试")
|
||||
phonePattern = regexp.MustCompile(`^\+?[0-9]{6,20}$`)
|
||||
)
|
||||
|
||||
type WriteInput struct {
|
||||
Name string `json:"name"`
|
||||
Role string `json:"role"`
|
||||
ExpectedVersion int `json:"expectedVersion"`
|
||||
}
|
||||
|
||||
type ChannelInput struct {
|
||||
Kind string `json:"kind"`
|
||||
Address string `json:"address"`
|
||||
}
|
||||
|
||||
func normalizeContact(input WriteInput) (WriteInput, error) {
|
||||
input.Name = strings.TrimSpace(input.Name)
|
||||
input.Role = strings.TrimSpace(input.Role)
|
||||
if input.Name == "" || len([]rune(input.Name)) > 128 || input.Role == "" || len([]rune(input.Role)) > 128 || hasControl(input.Name+input.Role) {
|
||||
return WriteInput{}, ErrInvalid
|
||||
}
|
||||
return input, nil
|
||||
}
|
||||
|
||||
func normalizeChannel(input ChannelInput) (ChannelInput, error) {
|
||||
input.Kind = strings.ToLower(strings.TrimSpace(input.Kind))
|
||||
input.Address = strings.ReplaceAll(strings.ReplaceAll(strings.TrimSpace(input.Address), " ", ""), "-", "")
|
||||
if (input.Kind != "sms" && input.Kind != "voice") || !phonePattern.MatchString(input.Address) {
|
||||
return ChannelInput{}, ErrInvalid
|
||||
}
|
||||
return input, nil
|
||||
}
|
||||
|
||||
func maskAddress(value string) string {
|
||||
runes := []rune(value)
|
||||
if len(runes) <= 4 {
|
||||
return "****"
|
||||
}
|
||||
return strings.Repeat("*", min(8, len(runes)-4)) + string(runes[len(runes)-4:])
|
||||
}
|
||||
|
||||
func hasControl(value string) bool {
|
||||
for _, r := range value {
|
||||
if r < 32 || r == 127 {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
package duty_schedule
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/gin-gonic/gin/binding"
|
||||
"github.com/go-admin-team/go-admin-core/sdk/api"
|
||||
jwt "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth"
|
||||
"github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth/user"
|
||||
)
|
||||
|
||||
type Handler struct{ api.Api }
|
||||
|
||||
func (h Handler) List(c *gin.Context) {
|
||||
var q PageQuery
|
||||
h.MakeContext(c).MakeOrm().Bind(&q, binding.Form)
|
||||
if h.Errors != nil {
|
||||
h.Error(400, ErrInvalid, ErrInvalid.Error())
|
||||
return
|
||||
}
|
||||
items, count, err := NewService(h.Orm).List(c.Request.Context(), q)
|
||||
if err != nil {
|
||||
h.Error(500, errors.New("读取排班失败"), "读取排班失败")
|
||||
return
|
||||
}
|
||||
p, s := pageValues(q.PageIndex, q.PageSize)
|
||||
h.PageOK(items, int(count), p, s, "查询成功")
|
||||
}
|
||||
func (h Handler) CreateGroup(c *gin.Context) {
|
||||
if !admin(c) {
|
||||
h.MakeContext(c).Error(403, errors.New("仅管理员可维护排班"), "仅管理员可维护排班")
|
||||
return
|
||||
}
|
||||
var input GroupInput
|
||||
h.bind(c, &input)
|
||||
if h.Errors != nil {
|
||||
return
|
||||
}
|
||||
item, err := NewService(h.Orm).CreateGroup(c.Request.Context(), input, user.GetUserId(c))
|
||||
h.result(item, err)
|
||||
}
|
||||
func (h Handler) UpdateGroup(c *gin.Context) {
|
||||
if !admin(c) {
|
||||
h.MakeContext(c).Error(403, errors.New("仅管理员可维护排班"), "仅管理员可维护排班")
|
||||
return
|
||||
}
|
||||
var input GroupInput
|
||||
h.bind(c, &input)
|
||||
if h.Errors != nil {
|
||||
return
|
||||
}
|
||||
item, err := NewService(h.Orm).UpdateGroup(c.Request.Context(), c.Param("id"), input, user.GetUserId(c))
|
||||
h.result(item, err)
|
||||
}
|
||||
func (h Handler) AddMember(c *gin.Context) {
|
||||
if !admin(c) {
|
||||
h.MakeContext(c).Error(403, errors.New("仅管理员可维护排班"), "仅管理员可维护排班")
|
||||
return
|
||||
}
|
||||
var input MemberInput
|
||||
h.bind(c, &input)
|
||||
if h.Errors != nil {
|
||||
return
|
||||
}
|
||||
item, err := NewService(h.Orm).AddMember(c.Request.Context(), c.Param("id"), input, user.GetUserId(c))
|
||||
h.result(item, err)
|
||||
}
|
||||
func (h Handler) CreateSchedule(c *gin.Context) {
|
||||
if !admin(c) {
|
||||
h.MakeContext(c).Error(403, errors.New("仅管理员可维护排班"), "仅管理员可维护排班")
|
||||
return
|
||||
}
|
||||
var input ScheduleInput
|
||||
h.bind(c, &input)
|
||||
if h.Errors != nil {
|
||||
return
|
||||
}
|
||||
item, err := NewService(h.Orm).CreateSchedule(c.Request.Context(), c.Param("id"), input, user.GetUserId(c))
|
||||
h.result(item, err)
|
||||
}
|
||||
func (h Handler) Publish(c *gin.Context) {
|
||||
if !admin(c) {
|
||||
h.MakeContext(c).Error(403, errors.New("仅管理员可发布排班"), "仅管理员可发布排班")
|
||||
return
|
||||
}
|
||||
item, err := NewService(h.Orm).Publish(c.Request.Context(), c.Param("id"), user.GetUserId(c))
|
||||
h.result(item, err)
|
||||
}
|
||||
func (h Handler) CreateOverride(c *gin.Context) {
|
||||
if !admin(c) {
|
||||
h.MakeContext(c).Error(403, errors.New("仅管理员可维护替班"), "仅管理员可维护替班")
|
||||
return
|
||||
}
|
||||
var input OverrideInput
|
||||
h.bind(c, &input)
|
||||
if h.Errors != nil {
|
||||
return
|
||||
}
|
||||
item, err := NewService(h.Orm).CreateOverride(c.Request.Context(), c.Param("id"), input, user.GetUserId(c))
|
||||
h.result(item, err)
|
||||
}
|
||||
func (h *Handler) bind(c *gin.Context, value any) {
|
||||
h.MakeContext(c).MakeOrm().Bind(value, binding.JSON)
|
||||
if h.Errors != nil {
|
||||
h.Error(400, ErrInvalid, ErrInvalid.Error())
|
||||
}
|
||||
}
|
||||
func (h Handler) result(item any, err error) {
|
||||
switch {
|
||||
case err == nil:
|
||||
h.OK(item, "保存成功")
|
||||
case errors.Is(err, ErrInvalid) || errors.Is(err, ErrCoverage):
|
||||
h.Error(400, err, err.Error())
|
||||
case errors.Is(err, ErrNotFound):
|
||||
h.Error(404, err, err.Error())
|
||||
case errors.Is(err, ErrConflict):
|
||||
h.Error(409, err, err.Error())
|
||||
default:
|
||||
h.Logger.Errorf("write Bell duty schedule failed: %v", err)
|
||||
h.Error(409, errors.New("排班保存失败"), "排班保存失败")
|
||||
}
|
||||
}
|
||||
func admin(c *gin.Context) bool {
|
||||
claims := jwt.ExtractClaims(c)
|
||||
role, _ := claims[jwt.RoleKey].(string)
|
||||
return role == "admin"
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
package duty_schedule
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Group struct {
|
||||
ID string `json:"id" gorm:"type:uuid;primaryKey"`
|
||||
Name string `json:"name" gorm:"size:128;not null;uniqueIndex"`
|
||||
Timezone string `json:"timezone" gorm:"size:64;not null"`
|
||||
Enabled bool `json:"enabled" gorm:"not null;default:true;index"`
|
||||
Version int `json:"version" gorm:"not null;default:1"`
|
||||
CreatedBy int `json:"createdBy" gorm:"not null"`
|
||||
UpdatedBy int `json:"updatedBy" gorm:"not null"`
|
||||
CreatedAt time.Time `json:"createdAt" gorm:"type:timestamptz;not null"`
|
||||
UpdatedAt time.Time `json:"updatedAt" gorm:"type:timestamptz;not null"`
|
||||
}
|
||||
|
||||
func (Group) TableName() string { return "bell_duty_groups" }
|
||||
|
||||
type Member struct {
|
||||
GroupID string `json:"groupId" gorm:"type:uuid;primaryKey"`
|
||||
ContactID string `json:"contactId" gorm:"type:uuid;primaryKey"`
|
||||
Role string `json:"role" gorm:"size:16;not null"`
|
||||
CreatedBy int `json:"createdBy" gorm:"not null"`
|
||||
CreatedAt time.Time `json:"createdAt" gorm:"type:timestamptz;not null"`
|
||||
}
|
||||
|
||||
func (Member) TableName() string { return "bell_duty_members" }
|
||||
|
||||
type ScheduleVersion struct {
|
||||
ID string `json:"id" gorm:"type:uuid;primaryKey"`
|
||||
GroupID string `json:"groupId" gorm:"type:uuid;not null;index"`
|
||||
Version int `json:"version" gorm:"not null"`
|
||||
Timezone string `json:"timezone" gorm:"size:64;not null"`
|
||||
EffectiveFrom time.Time `json:"effectiveFrom" gorm:"type:timestamptz;not null"`
|
||||
EffectiveTo *time.Time `json:"effectiveTo,omitempty" gorm:"type:timestamptz"`
|
||||
Status string `json:"status" gorm:"size:16;not null"`
|
||||
CreatedBy int `json:"createdBy" gorm:"not null"`
|
||||
CreatedAt time.Time `json:"createdAt" gorm:"type:timestamptz;not null"`
|
||||
PublishedBy *int `json:"publishedBy,omitempty"`
|
||||
PublishedAt *time.Time `json:"publishedAt,omitempty" gorm:"type:timestamptz"`
|
||||
}
|
||||
|
||||
func (ScheduleVersion) TableName() string { return "bell_duty_schedule_versions" }
|
||||
|
||||
type RotationSlot struct {
|
||||
ID string `json:"id" gorm:"type:uuid;primaryKey"`
|
||||
ScheduleVersionID string `json:"scheduleVersionId" gorm:"type:uuid;not null;index"`
|
||||
Weekday int `json:"weekday" gorm:"not null"`
|
||||
StartMinute int `json:"startMinute" gorm:"not null"`
|
||||
EndMinute int `json:"endMinute" gorm:"not null"`
|
||||
PrimaryContactID string `json:"primaryContactId" gorm:"type:uuid;not null"`
|
||||
BackupContactID string `json:"backupContactId" gorm:"type:uuid;not null"`
|
||||
}
|
||||
|
||||
func (RotationSlot) TableName() string { return "bell_duty_rotation_slots" }
|
||||
|
||||
type Override struct {
|
||||
ID string `json:"id" gorm:"type:uuid;primaryKey"`
|
||||
GroupID string `json:"groupId" gorm:"type:uuid;not null;index"`
|
||||
OriginalContactID string `json:"originalContactId" gorm:"type:uuid;not null"`
|
||||
ReplacementContactID string `json:"replacementContactId" gorm:"type:uuid;not null"`
|
||||
StartsAt time.Time `json:"startsAt" gorm:"type:timestamptz;not null;index"`
|
||||
EndsAt time.Time `json:"endsAt" gorm:"type:timestamptz;not null"`
|
||||
Reason string `json:"reason" gorm:"size:256;not null"`
|
||||
CreatedBy int `json:"createdBy" gorm:"not null"`
|
||||
CreatedAt time.Time `json:"createdAt" gorm:"type:timestamptz;not null"`
|
||||
}
|
||||
|
||||
func (Override) TableName() string { return "bell_duty_overrides" }
|
||||
|
||||
type AuditFact struct {
|
||||
ID string `json:"id" gorm:"type:uuid;primaryKey"`
|
||||
GroupID string `json:"groupId" gorm:"type:uuid;not null;index"`
|
||||
Action string `json:"action" gorm:"size:32;not null"`
|
||||
Snapshot json.RawMessage `json:"snapshot" gorm:"type:jsonb;not null"`
|
||||
ActorID int `json:"actorId" gorm:"not null"`
|
||||
CreatedAt time.Time `json:"createdAt" gorm:"type:timestamptz;not null"`
|
||||
}
|
||||
|
||||
func (AuditFact) TableName() string { return "bell_duty_audit_facts" }
|
||||
|
||||
type GroupView struct {
|
||||
Group
|
||||
Members []Member `json:"members"`
|
||||
Schedules []ScheduleView `json:"schedules"`
|
||||
Overrides []Override `json:"overrides"`
|
||||
}
|
||||
type ScheduleView struct {
|
||||
ScheduleVersion
|
||||
Slots []RotationSlot `json:"slots"`
|
||||
}
|
||||
@@ -0,0 +1,299 @@
|
||||
package duty_schedule
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
|
||||
"go-admin/app/bell/contact"
|
||||
)
|
||||
|
||||
type PageQuery struct {
|
||||
PageIndex int `form:"pageIndex"`
|
||||
PageSize int `form:"pageSize"`
|
||||
Name string `form:"name"`
|
||||
Enabled *bool `form:"enabled"`
|
||||
}
|
||||
type Service struct{ DB *gorm.DB }
|
||||
|
||||
func NewService(db *gorm.DB) Service { return Service{DB: db} }
|
||||
func (s Service) List(ctx context.Context, q PageQuery) ([]GroupView, int64, error) {
|
||||
p, z := pageValues(q.PageIndex, q.PageSize)
|
||||
db := s.DB.WithContext(ctx).Model(&Group{})
|
||||
if name := strings.TrimSpace(q.Name); name != "" {
|
||||
db = db.Where("name ILIKE ?", "%"+name+"%")
|
||||
}
|
||||
if q.Enabled != nil {
|
||||
db = db.Where("enabled = ?", *q.Enabled)
|
||||
}
|
||||
var count int64
|
||||
if err := db.Count(&count).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
var groups []Group
|
||||
if err := db.Order("created_at DESC,id DESC").Offset((p - 1) * z).Limit(z).Find(&groups).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
views := make([]GroupView, 0, len(groups))
|
||||
for _, g := range groups {
|
||||
v, err := s.view(ctx, g)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
views = append(views, v)
|
||||
}
|
||||
return views, count, nil
|
||||
}
|
||||
func (s Service) CreateGroup(ctx context.Context, input GroupInput, actor int) (GroupView, error) {
|
||||
input, err := normalizeGroup(input)
|
||||
if err != nil {
|
||||
return GroupView{}, err
|
||||
}
|
||||
now := time.Now().UTC()
|
||||
item := Group{ID: uuid.NewString(), Name: input.Name, Timezone: input.Timezone, Enabled: true, Version: 1, CreatedBy: actor, UpdatedBy: actor, CreatedAt: now, UpdatedAt: now}
|
||||
err = s.DB.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
if err := tx.Create(&item).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return audit(tx, item.ID, "group_created", item, actor)
|
||||
})
|
||||
return GroupView{Group: item, Members: []Member{}, Schedules: []ScheduleView{}, Overrides: []Override{}}, err
|
||||
}
|
||||
func (s Service) UpdateGroup(ctx context.Context, id string, input GroupInput, actor int) (GroupView, error) {
|
||||
input, err := normalizeGroup(input)
|
||||
if err != nil {
|
||||
return GroupView{}, err
|
||||
}
|
||||
if input.ExpectedVersion < 1 {
|
||||
return GroupView{}, ErrInvalid
|
||||
}
|
||||
var item Group
|
||||
err = s.DB.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
r := tx.Model(&Group{}).Where("id=? AND version=?", id, input.ExpectedVersion).Updates(map[string]any{"name": input.Name, "timezone": input.Timezone, "version": gorm.Expr("version+1"), "updated_by": actor, "updated_at": time.Now().UTC()})
|
||||
if r.Error != nil {
|
||||
return r.Error
|
||||
}
|
||||
if r.RowsAffected != 1 {
|
||||
return ErrConflict
|
||||
}
|
||||
if err := tx.First(&item, "id=?", id).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return audit(tx, id, "group_updated", item, actor)
|
||||
})
|
||||
if err != nil {
|
||||
return GroupView{}, err
|
||||
}
|
||||
return s.view(ctx, item)
|
||||
}
|
||||
func (s Service) AddMember(ctx context.Context, groupID string, input MemberInput, actor int) (Member, error) {
|
||||
input.Role = strings.ToLower(strings.TrimSpace(input.Role))
|
||||
if input.Role != "primary" && input.Role != "backup" {
|
||||
return Member{}, ErrInvalid
|
||||
}
|
||||
now := time.Now().UTC()
|
||||
item := Member{GroupID: groupID, ContactID: input.ContactID, Role: input.Role, CreatedBy: actor, CreatedAt: now}
|
||||
err := s.DB.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
if err := assertEnabledContact(tx, input.ContactID); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := tx.First(&Group{}, "id=?", groupID).Error; err != nil {
|
||||
return ErrNotFound
|
||||
}
|
||||
if err := tx.Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "group_id"}, {Name: "contact_id"}}, DoUpdates: clause.AssignmentColumns([]string{"role", "created_by", "created_at"})}).Create(&item).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return audit(tx, groupID, "member_saved", item, actor)
|
||||
})
|
||||
return item, err
|
||||
}
|
||||
func (s Service) CreateSchedule(ctx context.Context, groupID string, input ScheduleInput, actor int) (ScheduleView, error) {
|
||||
if input.EffectiveFrom.IsZero() || (input.EffectiveTo != nil && !input.EffectiveTo.After(input.EffectiveFrom)) {
|
||||
return ScheduleView{}, ErrInvalid
|
||||
}
|
||||
if err := validateSlots(input.Slots); err != nil {
|
||||
return ScheduleView{}, err
|
||||
}
|
||||
var result ScheduleView
|
||||
err := s.DB.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
var group Group
|
||||
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).First(&group, "id=?", groupID).Error; err != nil {
|
||||
return ErrNotFound
|
||||
}
|
||||
for _, slot := range input.Slots {
|
||||
if err := assertGroupMember(tx, groupID, slot.PrimaryContactID); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := assertGroupMember(tx, groupID, slot.BackupContactID); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
var latest int
|
||||
tx.Model(&ScheduleVersion{}).Where("group_id=?", groupID).Select("coalesce(max(version),0)").Scan(&latest)
|
||||
now := time.Now().UTC()
|
||||
version := ScheduleVersion{ID: uuid.NewString(), GroupID: groupID, Version: latest + 1, Timezone: group.Timezone, EffectiveFrom: input.EffectiveFrom.UTC(), EffectiveTo: input.EffectiveTo, Status: "draft", CreatedBy: actor, CreatedAt: now}
|
||||
if err := tx.Create(&version).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
slots := make([]RotationSlot, 0, len(input.Slots))
|
||||
for _, in := range input.Slots {
|
||||
slots = append(slots, RotationSlot{ID: uuid.NewString(), ScheduleVersionID: version.ID, Weekday: in.Weekday, StartMinute: in.StartMinute, EndMinute: in.EndMinute, PrimaryContactID: in.PrimaryContactID, BackupContactID: in.BackupContactID})
|
||||
}
|
||||
if err := tx.Create(&slots).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if err := audit(tx, groupID, "schedule_created", version, actor); err != nil {
|
||||
return err
|
||||
}
|
||||
result = ScheduleView{ScheduleVersion: version, Slots: slots}
|
||||
return nil
|
||||
})
|
||||
return result, err
|
||||
}
|
||||
func (s Service) Publish(ctx context.Context, id string, actor int) (ScheduleView, error) {
|
||||
var result ScheduleView
|
||||
err := s.DB.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
var item ScheduleVersion
|
||||
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).First(&item, "id=?", id).Error; err != nil {
|
||||
return ErrNotFound
|
||||
}
|
||||
if item.Status != "draft" {
|
||||
return ErrConflict
|
||||
}
|
||||
var slots []RotationSlot
|
||||
if err := tx.Where("schedule_version_id=?", id).Find(&slots).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
inputs := make([]SlotInput, 0, len(slots))
|
||||
for _, v := range slots {
|
||||
inputs = append(inputs, SlotInput{Weekday: v.Weekday, StartMinute: v.StartMinute, EndMinute: v.EndMinute, PrimaryContactID: v.PrimaryContactID, BackupContactID: v.BackupContactID})
|
||||
}
|
||||
if err := validateSlots(inputs); err != nil {
|
||||
return err
|
||||
}
|
||||
for _, v := range slots {
|
||||
if err := assertVerifiedContact(tx, v.PrimaryContactID); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := assertVerifiedContact(tx, v.BackupContactID); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
now := time.Now().UTC()
|
||||
if err := tx.Model(&item).Updates(map[string]any{"status": "published", "published_by": actor, "published_at": now}).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
item.Status = "published"
|
||||
item.PublishedBy = &actor
|
||||
item.PublishedAt = &now
|
||||
if err := audit(tx, item.GroupID, "schedule_published", item, actor); err != nil {
|
||||
return err
|
||||
}
|
||||
result = ScheduleView{ScheduleVersion: item, Slots: slots}
|
||||
return nil
|
||||
})
|
||||
return result, err
|
||||
}
|
||||
func (s Service) CreateOverride(ctx context.Context, groupID string, input OverrideInput, actor int) (Override, error) {
|
||||
input, err := normalizeOverride(input)
|
||||
if err != nil {
|
||||
return Override{}, err
|
||||
}
|
||||
item := Override{ID: uuid.NewString(), GroupID: groupID, OriginalContactID: input.OriginalContactID, ReplacementContactID: input.ReplacementContactID, StartsAt: input.StartsAt.UTC(), EndsAt: input.EndsAt.UTC(), Reason: input.Reason, CreatedBy: actor, CreatedAt: time.Now().UTC()}
|
||||
err = s.DB.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
if err := assertGroupMember(tx, groupID, input.OriginalContactID); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := assertGroupMember(tx, groupID, input.ReplacementContactID); err != nil {
|
||||
return err
|
||||
}
|
||||
var overlaps int64
|
||||
if err := tx.Model(&Override{}).Where("group_id=? AND original_contact_id=? AND starts_at < ? AND ends_at > ?", groupID, input.OriginalContactID, item.EndsAt, item.StartsAt).Count(&overlaps).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if overlaps > 0 {
|
||||
return ErrConflict
|
||||
}
|
||||
if err := tx.Create(&item).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return audit(tx, groupID, "override_created", item, actor)
|
||||
})
|
||||
return item, err
|
||||
}
|
||||
func (s Service) view(ctx context.Context, g Group) (GroupView, error) {
|
||||
v := GroupView{Group: g, Members: []Member{}, Schedules: []ScheduleView{}, Overrides: []Override{}}
|
||||
if err := s.DB.WithContext(ctx).Where("group_id=?", g.ID).Order("role,contact_id").Find(&v.Members).Error; err != nil {
|
||||
return v, err
|
||||
}
|
||||
var versions []ScheduleVersion
|
||||
if err := s.DB.WithContext(ctx).Where("group_id=?", g.ID).Order("version DESC").Find(&versions).Error; err != nil {
|
||||
return v, err
|
||||
}
|
||||
for _, sv := range versions {
|
||||
var slots []RotationSlot
|
||||
if err := s.DB.WithContext(ctx).Where("schedule_version_id=?", sv.ID).Order("weekday,start_minute").Find(&slots).Error; err != nil {
|
||||
return v, err
|
||||
}
|
||||
v.Schedules = append(v.Schedules, ScheduleView{ScheduleVersion: sv, Slots: slots})
|
||||
}
|
||||
if err := s.DB.WithContext(ctx).Where("group_id=?", g.ID).Order("starts_at DESC").Limit(50).Find(&v.Overrides).Error; err != nil {
|
||||
return v, err
|
||||
}
|
||||
return v, nil
|
||||
}
|
||||
func assertEnabledContact(tx *gorm.DB, id string) error {
|
||||
var c contact.Contact
|
||||
if err := tx.Where("id=? AND enabled=true", id).First(&c).Error; err != nil {
|
||||
return ErrInvalid
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func assertGroupMember(tx *gorm.DB, groupID, contactID string) error {
|
||||
if err := assertEnabledContact(tx, contactID); err != nil {
|
||||
return err
|
||||
}
|
||||
var count int64
|
||||
if err := tx.Model(&Member{}).Where("group_id=? AND contact_id=?", groupID, contactID).Count(&count).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if count != 1 {
|
||||
return ErrInvalid
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func assertVerifiedContact(tx *gorm.DB, contactID string) error {
|
||||
if err := assertEnabledContact(tx, contactID); err != nil {
|
||||
return err
|
||||
}
|
||||
var count int64
|
||||
err := tx.Raw(`SELECT count(*) FROM bell_contact_channels c WHERE c.contact_id=? AND (SELECT v.status FROM bell_contact_channel_validations v WHERE v.channel_id=c.id ORDER BY v.created_at DESC,v.id DESC LIMIT 1)='verified'`, contactID).Scan(&count).Error
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if count == 0 {
|
||||
return ErrInvalid
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func audit(tx *gorm.DB, groupID, action string, value any, actor int) error {
|
||||
data, err := json.Marshal(value)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Create(&AuditFact{ID: uuid.NewString(), GroupID: groupID, Action: action, Snapshot: data, ActorID: actor, CreatedAt: time.Now().UTC()}).Error
|
||||
}
|
||||
func pageValues(p, s int) (int, int) {
|
||||
if p < 1 {
|
||||
p = 1
|
||||
}
|
||||
if s < 1 || s > 100 {
|
||||
s = 20
|
||||
}
|
||||
return p, s
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
package duty_schedule
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrInvalid = errors.New("值班排班信息不符合要求")
|
||||
ErrNotFound = errors.New("值班组或排班不存在")
|
||||
ErrConflict = errors.New("数据已被其他人员更新,请刷新后重试")
|
||||
ErrCoverage = errors.New("周排班存在空档或重叠")
|
||||
)
|
||||
|
||||
type GroupInput struct {
|
||||
Name string `json:"name"`
|
||||
Timezone string `json:"timezone"`
|
||||
ExpectedVersion int `json:"expectedVersion"`
|
||||
}
|
||||
type MemberInput struct {
|
||||
ContactID string `json:"contactId"`
|
||||
Role string `json:"role"`
|
||||
}
|
||||
type SlotInput struct {
|
||||
Weekday int `json:"weekday"`
|
||||
StartMinute int `json:"startMinute"`
|
||||
EndMinute int `json:"endMinute"`
|
||||
PrimaryContactID string `json:"primaryContactId"`
|
||||
BackupContactID string `json:"backupContactId"`
|
||||
}
|
||||
type ScheduleInput struct {
|
||||
EffectiveFrom time.Time `json:"effectiveFrom"`
|
||||
EffectiveTo *time.Time `json:"effectiveTo"`
|
||||
Slots []SlotInput `json:"slots"`
|
||||
}
|
||||
type OverrideInput struct {
|
||||
OriginalContactID string `json:"originalContactId"`
|
||||
ReplacementContactID string `json:"replacementContactId"`
|
||||
StartsAt time.Time `json:"startsAt"`
|
||||
EndsAt time.Time `json:"endsAt"`
|
||||
Reason string `json:"reason"`
|
||||
}
|
||||
|
||||
func normalizeGroup(input GroupInput) (GroupInput, error) {
|
||||
input.Name = strings.TrimSpace(input.Name)
|
||||
input.Timezone = strings.TrimSpace(input.Timezone)
|
||||
if input.Name == "" || len([]rune(input.Name)) > 128 {
|
||||
return GroupInput{}, ErrInvalid
|
||||
}
|
||||
if _, err := time.LoadLocation(input.Timezone); err != nil {
|
||||
return GroupInput{}, ErrInvalid
|
||||
}
|
||||
return input, nil
|
||||
}
|
||||
func validateSlots(slots []SlotInput) error {
|
||||
if len(slots) == 0 {
|
||||
return ErrCoverage
|
||||
}
|
||||
byDay := map[int][]SlotInput{}
|
||||
for _, slot := range slots {
|
||||
if slot.Weekday < 0 || slot.Weekday > 6 || slot.StartMinute < 0 || slot.EndMinute > 1440 || slot.StartMinute >= slot.EndMinute || slot.PrimaryContactID == "" || slot.BackupContactID == "" || slot.PrimaryContactID == slot.BackupContactID {
|
||||
return ErrInvalid
|
||||
}
|
||||
byDay[slot.Weekday] = append(byDay[slot.Weekday], slot)
|
||||
}
|
||||
for day := 0; day < 7; day++ {
|
||||
daySlots := byDay[day]
|
||||
sort.Slice(daySlots, func(i, j int) bool { return daySlots[i].StartMinute < daySlots[j].StartMinute })
|
||||
cursor := 0
|
||||
for _, slot := range daySlots {
|
||||
if slot.StartMinute != cursor {
|
||||
return ErrCoverage
|
||||
}
|
||||
cursor = slot.EndMinute
|
||||
}
|
||||
if cursor != 1440 {
|
||||
return ErrCoverage
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func normalizeOverride(input OverrideInput) (OverrideInput, error) {
|
||||
input.Reason = strings.TrimSpace(input.Reason)
|
||||
if input.OriginalContactID == "" || input.ReplacementContactID == "" || input.OriginalContactID == input.ReplacementContactID || input.StartsAt.IsZero() || !input.EndsAt.After(input.StartsAt) || input.Reason == "" || len([]rune(input.Reason)) > 256 {
|
||||
return OverrideInput{}, ErrInvalid
|
||||
}
|
||||
return input, nil
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package router
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
jwt "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth"
|
||||
|
||||
"go-admin/app/bell/contact"
|
||||
"go-admin/common/middleware"
|
||||
)
|
||||
|
||||
func init() { registrars = append(registrars, registerContactRouter) }
|
||||
func registerContactRouter(v1 *gin.RouterGroup, auth *jwt.GinJWTMiddleware) {
|
||||
h := contact.Handler{}
|
||||
secured := v1.Group("").Use(auth.MiddlewareFunc()).Use(middleware.AuthCheckRole())
|
||||
secured.GET("/contacts", h.List)
|
||||
secured.POST("/contacts", h.Create)
|
||||
secured.PUT("/contacts/:id", h.Update)
|
||||
secured.PUT("/contacts/:id/enabled", h.SetEnabled)
|
||||
secured.POST("/contacts/:id/channels", h.AddChannel)
|
||||
secured.POST("/contact-channels/:id/validations", h.ValidateChannel)
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package router
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
jwt "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth"
|
||||
|
||||
"go-admin/app/bell/duty_schedule"
|
||||
"go-admin/common/middleware"
|
||||
)
|
||||
|
||||
func init() { registrars = append(registrars, registerDutyScheduleRouter) }
|
||||
func registerDutyScheduleRouter(v1 *gin.RouterGroup, auth *jwt.GinJWTMiddleware) {
|
||||
h := duty_schedule.Handler{}
|
||||
secured := v1.Group("").Use(auth.MiddlewareFunc()).Use(middleware.AuthCheckRole())
|
||||
secured.GET("/duty-groups", h.List)
|
||||
secured.POST("/duty-groups", h.CreateGroup)
|
||||
secured.PUT("/duty-groups/:id", h.UpdateGroup)
|
||||
secured.POST("/duty-groups/:id/members", h.AddMember)
|
||||
secured.POST("/duty-groups/:id/schedules", h.CreateSchedule)
|
||||
secured.POST("/duty-schedules/:id/publish", h.Publish)
|
||||
secured.POST("/duty-groups/:id/overrides", h.CreateOverride)
|
||||
}
|
||||
Reference in New Issue
Block a user