ruspet_portal_back/service/telegram_service/state/state.go

70 lines
2.2 KiB
Go

package state
import (
"context"
"encoding/json"
"fmt"
"time"
redismodule "bitrix_balancer_api/core/lib/internally/redis"
)
const stateTTL = 30 * time.Minute
type FileAttachment struct {
Base64 string
FileName string
}
// ApprovalFlowState — состояние пользователя внутри флоу согласования.
// Хранится в Redis, сбрасывается по TTL или после отправки заявки.
type ApprovalFlowState struct {
TopicCode string `json:"topic_code"`
NodeKey string `json:"node_key"`
Collected map[string]string `json:"collected"`
AwaitInput bool `json:"await_input"`
InputKey string `json:"input_key"`
History []string `json:"history"`
AwaitFileInput bool `json:"await_file_input"`
Files []FileAttachment `json:"files"`
FileStatusMsgID int `json:"file_status_msg_id"`
SelectedApproverID uint64 `json:"selected_approver_id,omitempty"`
AwaitApproverSelection bool `json:"await_approver_selection"`
}
type StateManager struct {
redis *redismodule.ModuleRedis
}
func NewStateManager(redis *redismodule.ModuleRedis) *StateManager {
return &StateManager{redis: redis}
}
func key(telegramID int64) string {
return fmt.Sprintf("approval_flow:%d", telegramID)
}
func (s *StateManager) Set(ctx context.Context, telegramID int64, state *ApprovalFlowState) error {
data, err := json.Marshal(state)
if err != nil {
return err
}
return s.redis.Set(ctx, key(telegramID), string(data), stateTTL)
}
func (s *StateManager) Get(ctx context.Context, telegramID int64) (*ApprovalFlowState, error) {
data, err := s.redis.Get(ctx, key(telegramID))
if err != nil {
return nil, nil // нет активного состояния — это норма
}
var state ApprovalFlowState
if err := json.Unmarshal([]byte(data), &state); err != nil {
return nil, err
}
return &state, nil
}
func (s *StateManager) Clear(ctx context.Context, telegramID int64) error {
return s.redis.Del(ctx, key(telegramID))
}