Skip to content

Commit

Permalink
Support bulk suggestions adding (#194)
Browse files Browse the repository at this point in the history
Closes #171
  • Loading branch information
LucaBernstein authored Nov 10, 2022
1 parent 1d6d59b commit 0953f5f
Show file tree
Hide file tree
Showing 2 changed files with 94 additions and 17 deletions.
44 changes: 28 additions & 16 deletions bot/suggestions.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,10 +41,12 @@ func (bc *BotController) suggestionsHelp(m *tb.Message, err error) {

_, err = bc.Bot.Send(Recipient(m), errorMsg+fmt.Sprintf(`Usage help for /suggestions:
/suggestions list <type>
/suggestions add <type> <value>
/suggestions add <type> <value> [<value>...]
/suggestions rm <type> [value]
Parameter <type> is one from: [%s]`, strings.Join(suggestionTypes, ", ")))
Parameter <type> is one of: [%s]
Adding multiple suggestions at once is supported either by space separation (with quotation marks) or using newlines.`, strings.Join(suggestionTypes, ", ")))
if err != nil {
bc.Logf(ERROR, m, "Sending bot message failed: %s", err.Error())
}
Expand Down Expand Up @@ -88,29 +90,39 @@ func (bc *BotController) suggestionsHandleList(m *tb.Message, params ...string)
}

func (bc *BotController) suggestionsHandleAdd(m *tb.Message, params ...string) {
p, err := h.ExtractTypeValue(params...)
if err != nil {
bc.suggestionsHelp(m, fmt.Errorf("error encountered while retrieving suggestions list: %s", err.Error()))
return
}
p.T = h.FqCacheKey(p.T)
if !isAllowedSuggestionType(p.T) {
if len(params) < 2 {
bc.suggestionsHelp(m, fmt.Errorf("error encountered while retrieving suggestions list: Insufficient parameters count"))
}
suggestionTypeSplit := strings.SplitN(params[0], "\n", 2)
suggestionType := suggestionTypeSplit[0]
remainder := ""
if len(suggestionTypeSplit) > 1 {
remainder = suggestionTypeSplit[1]
}
// Undo splitting by spaces: concat and then split by newlines for bulk suggestions adding support
restoredValue := remainder + " " + strings.Join(params[1:], " ")
singleValues := strings.Split(strings.TrimSpace(restoredValue), "\n")

suggestionType = h.FqCacheKey(suggestionType)
if !isAllowedSuggestionType(suggestionType) {
bc.suggestionsHelp(m, fmt.Errorf("unexpected subcommand"))
return
}
if p.Value == "" {
if len(singleValues) == 0 || (len(singleValues) == 1 && singleValues[0] == "") {
bc.suggestionsHelp(m, fmt.Errorf("no value to add provided"))
return
}
err = bc.Repo.PutCacheHints(m, map[string]string{p.T: p.Value})
if err != nil {
_, err := bc.Bot.Send(Recipient(m), fmt.Sprintf("Error encountered while adding suggestion (%s): %s", p.Value, err.Error()))
for _, value := range singleValues {
err := bc.Repo.PutCacheHints(m, map[string]string{suggestionType: value})
if err != nil {
bc.Logf(ERROR, m, "Sending bot message failed: %s", err.Error())
_, err := bc.Bot.Send(Recipient(m), fmt.Sprintf("Error encountered while adding suggestion (%s): %s", value, err.Error()))
if err != nil {
bc.Logf(ERROR, m, "Sending bot message failed: %s", err.Error())
}
return
}
return
}
_, err = bc.Bot.Send(Recipient(m), "Successfully added suggestion(s).")
_, err := bc.Bot.Send(Recipient(m), "Successfully added suggestion(s).")
if err != nil {
bc.Logf(ERROR, m, "Sending bot message failed: %s", err.Error())
}
Expand Down
67 changes: 66 additions & 1 deletion bot/suggestions_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"testing"

"github.com/DATA-DOG/go-sqlmock"
"github.com/LucaBernstein/beancount-bot-tg/db/crud"
tb "gopkg.in/telebot.v3"
)

Expand Down Expand Up @@ -36,7 +37,6 @@ func TestSuggestionsHandlingWithSpaces(t *testing.T) {
if !strings.Contains(fmt.Sprintf("%v", bot.LastSentWhat), "Usage help") {
t.Errorf("MissingType: Bot unexpectedly did not send usage help: %s", bot.LastSentWhat)
}
log.Print(1)

// missing type
bc.commandSuggestions(&MockContext{M: &tb.Message{Text: "/suggestions rm", Chat: chat}})
Expand Down Expand Up @@ -69,3 +69,68 @@ func TestSuggestionsHandlingWithSpaces(t *testing.T) {
t.Errorf("there were unfulfilled expectations: %s", err)
}
}

func TestAddMultipleSuggestionsAtOnce(t *testing.T) {
// Test dependencies
crud.TEST_MODE = true
chat := &tb.Chat{ID: 12345}
db, mock, err := sqlmock.New()
if err != nil {
log.Fatal(err)
}

bc := NewBotController(db)
bot := &MockBot{}
bc.AddBotAndStart(bot)

mock.
ExpectQuery(`SELECT "type", "value" FROM "bot::cache"`).
WithArgs(12345).
WillReturnRows(sqlmock.NewRows([]string{"type", "value"}))
mock.
ExpectExec(`INSERT INTO "bot::cache"`).
WithArgs(12345, "account:from", "First Suggestion").
WillReturnResult(sqlmock.NewResult(1, 1))
mock.
ExpectQuery(`SELECT "type", "value" FROM "bot::cache"`).
WithArgs(12345).
WillReturnRows(sqlmock.NewRows([]string{"type", "value"}))
mock.
ExpectQuery(`SELECT "type", "value" FROM "bot::cache"`).
WithArgs(12345).
WillReturnRows(sqlmock.NewRows([]string{"type", "value"}))
mock.
ExpectExec(`INSERT INTO "bot::cache"`).
WithArgs(12345, "account:from", "Second Suggestion").
WillReturnResult(sqlmock.NewResult(1, 1))
mock.
ExpectQuery(`SELECT "type", "value" FROM "bot::cache"`).
WithArgs(12345).
WillReturnRows(sqlmock.NewRows([]string{"type", "value"}))

bc.commandSuggestions(&MockContext{M: &tb.Message{Text: "/suggestions add account:from\nFirst Suggestion\nSecond Suggestion", Chat: chat}})

// Add single suggestion
mock.
ExpectQuery(`SELECT "type", "value" FROM "bot::cache"`).
WithArgs(12345).
WillReturnRows(sqlmock.NewRows([]string{"type", "value"}))
mock.
ExpectExec(`INSERT INTO "bot::cache"`).
WithArgs(12345, "account:to", "One lonely suggestion").
WillReturnResult(sqlmock.NewResult(1, 1))
mock.
ExpectQuery(`SELECT "type", "value" FROM "bot::cache"`).
WithArgs(12345).
WillReturnRows(sqlmock.NewRows([]string{"type", "value"}))

bc.commandSuggestions(&MockContext{M: &tb.Message{Text: "/suggestions add account:to \"One lonely suggestion\"", Chat: chat}})

if !strings.Contains(fmt.Sprintf("%v", bot.LastSentWhat), "Successfully added") {
t.Errorf("Unexpected bot response: %v", bot.AllLastSentWhat...)
}

if err := mock.ExpectationsWereMet(); err != nil {
t.Errorf("there were unfulfilled expectations: %s", err)
}
}

0 comments on commit 0953f5f

Please sign in to comment.