diff --git a/botsfwmodels/chat_base_data.go b/botsfwmodels/chat_base_data.go index 79c11d9..32ce9ec 100644 --- a/botsfwmodels/chat_base_data.go +++ b/botsfwmodels/chat_base_data.go @@ -24,6 +24,7 @@ type ChatBaseData struct { BotBaseData chatState chatSettings + chatVars // AppUserIntIDs is kept for legacy reasons // Deprecated: replace with `AppUserIDs []string` diff --git a/botsfwmodels/chat_data.go b/botsfwmodels/chat_data.go index d7c4071..c48d162 100644 --- a/botsfwmodels/chat_data.go +++ b/botsfwmodels/chat_data.go @@ -86,6 +86,11 @@ type BotChatData interface { // PushStepToAwaitingReplyTo pushes step to awaiting reply to PushStepToAwaitingReplyTo(code string) //GetGaClientID() string + + SetVar(key string, value string) + GetVar(key string) string + DelVar(key string) + HasChangedVars() bool } // NewChatID create a new bot chat ID, returns string diff --git a/botsfwmodels/chat_vars.go b/botsfwmodels/chat_vars.go new file mode 100644 index 0000000..c41744d --- /dev/null +++ b/botsfwmodels/chat_vars.go @@ -0,0 +1,54 @@ +package botsfwmodels + +import ( + "github.com/strongo/slice" + "slices" +) + +type chatVars struct { + Vars map[string]string `dalgo:"vars,omitempty" firestore:"vars,omitempty"` + changed []string + deleted []string +} + +// GetVar returns a chat variable +func (v *chatVars) GetVar(key string) string { + if v.Vars == nil { + return "" + } + return v.Vars[key] +} + +// SetVar sets a chat variable +func (v *chatVars) SetVar(key, value string) { + if v.Vars == nil { + v.Vars = make(map[string]string) + } else if v.Vars[key] == value { + return + } + v.Vars[key] = value + slice.RemoveInPlaceByValue(v.deleted, key) + if !slices.Contains(v.changed, key) { + v.changed = append(v.changed, key) + } +} + +// DelVar deletes a chat variable +func (v *chatVars) DelVar(key string) { + if v.Vars == nil { + return + } + if _, ok := v.Vars[key]; !ok { + return + } + delete(v.Vars, key) + v.changed = slice.RemoveInPlaceByValue(v.changed, key) + if !slices.Contains(v.deleted, key) { + v.deleted = append(v.deleted, key) + } +} + +// HasChangedVars returns true if vars have been changed +func (v *chatVars) HasChangedVars() bool { + return len(v.changed) > 0 || len(v.deleted) > 0 +} diff --git a/go.mod b/go.mod index dc49315..3d42874 100644 --- a/go.mod +++ b/go.mod @@ -3,3 +3,5 @@ module github.com/bots-go-framework/bots-fw-store go 1.22 require github.com/strongo/validation v0.0.7 + +require github.com/strongo/slice v0.3.1 // indirect diff --git a/go.sum b/go.sum index 26aab83..7d07123 100644 --- a/go.sum +++ b/go.sum @@ -1,2 +1,4 @@ +github.com/strongo/slice v0.3.1 h1:VWkyYBgcVJn6Hs7wYhL9Vxwgb7V3zQAUFTBV9wo5lc4= +github.com/strongo/slice v0.3.1/go.mod h1:B5ODKCkl0rp2oiG0UBqkN1cCOrSCU2cUuhqCM1sC8r4= github.com/strongo/validation v0.0.7 h1:gs6YkwPsYtVsepQaQOB+ZF+T0Gu5+nk4ZMND8F85e+U= github.com/strongo/validation v0.0.7/go.mod h1:YUwoPEItLJd/Bc9X1OCUm03ofhvm3kwZvuihU7/jz58=