diff --git a/docs/commands.md b/docs/commands.md index 6b74641..15c630d 100644 --- a/docs/commands.md +++ b/docs/commands.md @@ -363,9 +363,17 @@ wolt cart add huuva-food-court-niittykumpu 689efcc0dbe125482d2fecb2 \ When complete option metadata is available, unknown or ambiguous names fail closed; use the displayed group/value ID to disambiguate. Required and -minimum/maximum selection counts are validated before the mutation, and -explicitly free option values remain distinct from values whose price metadata -is missing. +minimum/maximum selection counts, and the per-value limit, are validated before +the mutation, and explicitly free option values remain distinct from values +whose price metadata is missing. + +A required group you leave out gets its default value, the one the Wolt app +preselects and `venue item` marks with `default: true`; the result lists it +under `default_options`. A required group without a default needs `--option`. +Optional groups stay empty unless you choose a value, even when Wolt names a +default for them. Some groups apply only after a value of another group is +chosen (`prerequisite_value_ids` in `venue item`); such a group is skipped +until then, and choosing a value in it before that is an error. A restaurant dish names each option group by its own item-level ID and takes the values from a shared library group; `venue menu --include-options` lists diff --git a/docs/mcp.md b/docs/mcp.md index 5c9f648..46ff90f 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -168,9 +168,14 @@ that could not be loaded. > official Wolt app or web UI. `wolt_checkout_preview` is a pricing preview only. `wolt_cart_add` always revalidates the exact item before mutating the basket; -caller-supplied display metadata cannot bypass an unavailable item. The tool -does not currently accept option selections, so it fails closed when an item -requires one instead of posting an invalid empty selection. +caller-supplied display metadata cannot bypass an unavailable item. It takes +option choices as `options: [{group_id, value_id, count?}]`, with the ids from +`wolt_venue_item` (names also work when unambiguous), and validates them the +same way as `wolt cart add --option`: limits per group and per value, unknown +values and groups that apply only after another choice. A required group left +out gets its default value, as in the Wolt app, and `default_options` in the +result lists each one applied; a required group without a default fails closed. +The line price includes the chosen option prices. `wolt_checkout_preview` revalidates every basket item before sending the preview request. Both operations fail closed if availability or venue currency cannot be verified. diff --git a/docs/output-contract.md b/docs/output-contract.md index 8360ca4..57d941a 100644 --- a/docs/output-contract.md +++ b/docs/output-contract.md @@ -454,12 +454,25 @@ availability_verified, is_available, unavailable_reason, purchasable_balance image_url, image_urls, image_blurhash unit_info, unit_price, sell_by_weight_config option_groups[]: { - group_id, name, required, min, max, - values[]: { value_id, name, price? } + group_id, library_group_id?, name, required, min, max, + prerequisite_value_ids[]?, + values[]: { value_id, name, price?, default? } } +default_price?: { amount, currency, formatted_amount } upsell_items[] ``` +`group_id` is the dish's item-level group id, the one the basket stores; +`library_group_id` is the venue's shared option-library group it takes its +values from. `min` and `max` bound how many units the group takes in total, and +`required` is true when `min` is at least 1. `default: true` marks the value +the Wolt app preselects. A group with `prerequisite_value_ids` applies only +while one of those values (from another group of the dish) is selected. +`default_price` is the price with the default values of the required groups +that apply without any other choice, which is what the Wolt app shows for a +dish whose required group is paid. It is absent when the item has no option +groups or a required group has no default. + `price.formatted_amount` is normalized from venue metadata when upstream omits the currency and the amount is known. Unknown amounts and their formatted values remain `null`; they are never inferred as zero. `upsell_items[].price` @@ -503,7 +516,8 @@ total_items: int total: { amount, formatted_amount } # Per mutation -add: basket_id, venue_id, line_id, item_name, item_price, item_currency +add: basket_id, venue_id, line_id, item_name, item_price, item_currency, + default_options[]?: { group_id, group_name?, value_id, value_name?, price } remove: basket_id, venue_id, line_id, removed_count clear: basket_ids[], cleared_baskets ``` @@ -512,6 +526,8 @@ Before `cart add`, the CLI always fetches the exact current item and refuses the mutation when it is disabled, has zero purchasable balance, is missing from the current assortment, or cannot be validated. Explicit `--price`, `--currency`, and `--name` values do not bypass this check. +A required option group left without `--option` gets its default value, as the +Wolt app preselects it, and `default_options` lists each one applied. The complete existing basket snapshot must also be reconstructable, including every item, selected option, count, and price, because Wolt's mutation replaces the full item array. diff --git a/internal/cli/cart_helpers.go b/internal/cli/cart_helpers.go index 0327805..f26b956 100644 --- a/internal/cli/cart_helpers.go +++ b/internal/cli/cart_helpers.go @@ -2,17 +2,14 @@ package cli import ( "fmt" - "sort" "strconv" "strings" + "github.com/mekedron/wolt-cli/internal/service/itemoptions" "github.com/mekedron/wolt-cli/internal/service/payloadutil" ) -type optionSelection struct { - ValueID string - Count int -} +type optionSelection = itemoptions.Choice func parseOptionSelections(raw []string) (map[string][]optionSelection, error) { result := map[string][]optionSelection{} @@ -54,136 +51,16 @@ func buildBasketOptions( itemPayload map[string]any, selections map[string][]optionSelection, ) ([]any, error) { - optionSpecs := extractOptionSpecs(itemPayload) - groupIDs := make([]string, 0, len(optionSpecs)) - for groupID := range optionSpecs { - groupIDs = append(groupIDs, groupID) - } - sort.Strings(groupIDs) - - resolvedSelections := map[string][]optionSelection{} - if len(optionSpecs) > 0 { - selectionGroupTokens := make([]string, 0, len(selections)) - for rawGroupToken := range selections { - selectionGroupTokens = append(selectionGroupTokens, rawGroupToken) - } - sort.Strings(selectionGroupTokens) - for _, rawGroupToken := range selectionGroupTokens { - choices := selections[rawGroupToken] - resolvedGroupID, err := resolveOptionGroupToken(rawGroupToken, optionSpecs) - if err != nil { - return nil, err - } - resolvedSelections[resolvedGroupID] = append(resolvedSelections[resolvedGroupID], choices...) - } - } else { - for rawGroupToken, choices := range selections { - groupID := strings.TrimSpace(rawGroupToken) - if groupID == "" { - continue - } - resolvedSelections[groupID] = append(resolvedSelections[groupID], choices...) - groupIDs = append(groupIDs, groupID) - } - sort.Strings(groupIDs) - groupIDs = dedupeStrings(groupIDs) - } - - options := make([]any, 0, len(groupIDs)) - for _, groupID := range groupIDs { - groupSpec := optionSpecs[groupID] - choices := resolvedSelections[groupID] - selectionCount := 0 - valueCounts := make(map[string]int, len(choices)) - for _, choice := range choices { - nextCount, ok := payloadutil.CheckedAddInt(selectionCount, choice.Count) - if !ok { - return nil, fmt.Errorf("option group %q selection count exceeds the supported integer range", groupID) - } - selectionCount = nextCount - valueID := choice.ValueID - resolvedValueID, err := resolveOptionValueToken(choice.ValueID, groupSpec) - if err == nil { - valueID = resolvedValueID - } else if len(groupSpec.Values) > 0 { - return nil, fmt.Errorf("option group %q: %w", groupID, err) - } - nextValueCount, ok := payloadutil.CheckedAddInt(valueCounts[valueID], choice.Count) - if !ok { - return nil, fmt.Errorf("option group %q value %q count exceeds the supported integer range", groupID, valueID) - } - valueCounts[valueID] = nextValueCount - } - minSelect := groupSpec.MinSelect - if groupSpec.Required && minSelect < 1 { - minSelect = 1 - } - maxSelect := groupSpec.MaxSelect - if minSelect < 0 || maxSelect < 0 || (maxSelect > 0 && minSelect > maxSelect) { - return nil, fmt.Errorf("option group %q has invalid selection limits", groupID) - } - if selectionCount < minSelect { - return nil, fmt.Errorf( - "option group %q selection count must be at least %d; got %d", - groupID, - minSelect, - selectionCount, - ) - } - if maxSelect > 0 && selectionCount > maxSelect { - return nil, fmt.Errorf( - "option group %q selection count must be at most %d; got %d", - groupID, - maxSelect, - selectionCount, - ) - } - if len(valueCounts) == 0 { - continue - } - valueIDs := make([]string, 0, len(valueCounts)) - for valueID := range valueCounts { - valueIDs = append(valueIDs, valueID) - } - sort.Strings(valueIDs) - - values := make([]any, 0, len(valueIDs)) - for _, valueID := range valueIDs { - price := 0 - if valueSpec, ok := groupSpec.Values[valueID]; ok { - if !valueSpec.HasPrice { - return nil, fmt.Errorf( - "option group %q value %q is missing current price metadata; refresh venue item data and try again", - groupID, - valueID, - ) - } - price = valueSpec.Price - } - values = append(values, map[string]any{ - "id": valueID, - "count": valueCounts[valueID], - "price": price, - }) - } - options = append(options, map[string]any{ - "id": groupID, - "values": values, - }) + result, err := itemoptions.Build(itemPayload, selections) + if err != nil { + return nil, err } - return options, nil + return result.Options, nil } // basketOptionsTotal sums price * count over the selected option values. func basketOptionsTotal(options []any) int { - total := 0 - for _, rawOption := range options { - for _, rawValue := range asSlice(asMap(rawOption)["values"]) { - value := asMap(rawValue) - total += asInt(value["price"]) * asInt(value["count"]) - } - } - return total + return itemoptions.Total(options) } func extractOptionSpecs(payload map[string]any) map[string]payloadutil.OptionGroupSpec { @@ -227,64 +104,10 @@ func buildItemPayloadFromAssortment(assortment map[string]any, itemID string) ma currency = payloadutil.CurrencyFromVenuePayload(assortment) } - optionGroupIDs := extractAssortmentOptionGroupIDs(item) - optionGroupIndex := map[string]map[string]any{} - rootOptionGroups := payloadutil.MergeOptionGroups( + optionGroups := payloadutil.JoinOptionLibrary(item, payloadutil.MergeOptionGroups( asSlice(assortment["options"]), asSlice(assortment["option_groups"]), - ) - for _, rawGroup := range rootOptionGroups { - group := asMap(rawGroup) - if group == nil { - continue - } - groupID := strings.TrimSpace(asString(coalesceAny(group["id"], group["option_id"], group["group_id"]))) - if groupID != "" { - optionGroupIndex[strings.ToLower(groupID)] = group - } - } - // A dish names each option group by an item-level "id" and points at the - // shared option library through "option_id". The basket API and the Wolt - // app only recognise the item-level id, and one library group can back - // several groups of the same dish (pick 1, 2 or 3 toppings), so every - // item-level group becomes its own basket group carrying the library values. - itemOptionIDs := map[string][]string{} - for _, rawOption := range asSlice(item["options"]) { - option := asMap(rawOption) - if option == nil { - continue - } - libraryID := strings.TrimSpace(asString(option["option_id"])) - itemLevelID := strings.TrimSpace(asString(option["id"])) - if libraryID != "" && itemLevelID != "" && !strings.EqualFold(libraryID, itemLevelID) { - key := strings.ToLower(libraryID) - itemOptionIDs[key] = append(itemOptionIDs[key], itemLevelID) - } - } - optionGroups := make([]any, 0, len(optionGroupIDs)) - for _, groupID := range optionGroupIDs { - group, ok := optionGroupIndex[strings.ToLower(groupID)] - if !ok { - continue - } - itemLevelIDs := itemOptionIDs[strings.ToLower(groupID)] - if len(itemLevelIDs) == 0 { - optionGroups = append(optionGroups, group) - continue - } - for _, itemLevelID := range itemLevelIDs { - rewritten := make(map[string]any, len(group)+2) - for key, value := range group { - rewritten[key] = value - } - rewritten["id"] = itemLevelID - rewritten["option_id"] = groupID - optionGroups = append(optionGroups, rewritten) - } - } - if len(optionGroups) == 0 { - optionGroups = asSlice(coalesceAny(item["option_groups"], item["options"])) - } + )) result := map[string]any{ "item_id": targetItemID, @@ -324,36 +147,6 @@ func buildItemPayloadFromAssortment(assortment map[string]any, itemID string) ma return result } -func extractAssortmentOptionGroupIDs(item map[string]any) []string { - groupIDs := []string{} - seen := map[string]struct{}{} - appendGroupID := func(raw any) { - groupID := strings.TrimSpace(asString(raw)) - key := strings.ToLower(groupID) - if groupID == "" { - return - } - if _, exists := seen[key]; exists { - return - } - seen[key] = struct{}{} - groupIDs = append(groupIDs, groupID) - } - for _, value := range asSlice(item["option_group_ids"]) { - appendGroupID(value) - } - for _, alias := range []string{"options", "option_groups"} { - for _, optionValue := range asSlice(item[alias]) { - option := asMap(optionValue) - if option == nil { - continue - } - appendGroupID(coalesceAny(option["option_id"], option["id"], option["group_id"])) - } - } - return groupIDs -} - func inferCurrency(formatted string) string { return payloadutil.InferCurrency(formatted) } @@ -362,113 +155,6 @@ func formatMinorAmount(amount int, currency string) string { return payloadutil.FormatMinorAmount(amount, currency) } -func resolveOptionGroupToken( - token string, - specs map[string]payloadutil.OptionGroupSpec, -) (string, error) { - token = strings.TrimSpace(token) - if token == "" { - return "", fmt.Errorf("option group is required") - } - if _, ok := specs[token]; ok { - return token, nil - } - libraryMatches := []string{} - for groupID, spec := range specs { - if spec.OptionID != "" && strings.EqualFold(spec.OptionID, token) { - libraryMatches = append(libraryMatches, groupID) - } - } - switch len(libraryMatches) { - case 0: - case 1: - return libraryMatches[0], nil - default: - sort.Strings(libraryMatches) - return "", fmt.Errorf( - "option group %q is shared by %d groups of this item; use one of their IDs: %s", - token, - len(libraryMatches), - strings.Join(libraryMatches, ", "), - ) - } - groupIDs := make([]string, 0, len(specs)) - for groupID := range specs { - groupIDs = append(groupIDs, groupID) - } - sort.Strings(groupIDs) - if match, ambiguous := uniqueOptionMatch(token, groupIDs, func(groupID string) string { - return groupID - }); match != "" || ambiguous { - if ambiguous { - return "", fmt.Errorf("ambiguous option group %q; use its ID", token) - } - return match, nil - } - if match, ambiguous := uniqueOptionMatch(token, groupIDs, func(groupID string) string { - return specs[groupID].Name - }); match != "" || ambiguous { - if ambiguous { - return "", fmt.Errorf("ambiguous option group %q; use its ID", token) - } - return match, nil - } - return "", fmt.Errorf("unknown option group %q", token) -} - -func resolveOptionValueToken( - token string, - group payloadutil.OptionGroupSpec, -) (string, error) { - token = strings.TrimSpace(token) - if token == "" { - return "", fmt.Errorf("option value is required") - } - if _, ok := group.Values[token]; ok { - return token, nil - } - valueIDs := make([]string, 0, len(group.Values)) - for valueID := range group.Values { - valueIDs = append(valueIDs, valueID) - } - sort.Strings(valueIDs) - if match, ambiguous := uniqueOptionMatch(token, valueIDs, func(valueID string) string { - return valueID - }); match != "" || ambiguous { - if ambiguous { - return "", fmt.Errorf("ambiguous option value %q; use its ID", token) - } - return match, nil - } - if match, ambiguous := uniqueOptionMatch(token, valueIDs, func(valueID string) string { - return group.Values[valueID].Name - }); match != "" || ambiguous { - if ambiguous { - return "", fmt.Errorf("ambiguous option value %q; use its ID", token) - } - return match, nil - } - return "", fmt.Errorf("unknown option value %q", token) -} - -func uniqueOptionMatch( - token string, - ids []string, - label func(string) string, -) (string, bool) { - match := "" - for _, id := range ids { - if !strings.EqualFold(strings.TrimSpace(label(id)), token) { - continue - } - if match != "" && match != id { - return "", true - } - match = id - } - return match, false -} - func dedupeStrings(values []string) []string { seen := map[string]struct{}{} out := make([]string, 0, len(values)) diff --git a/internal/cli/cart_helpers_test.go b/internal/cli/cart_helpers_test.go index c88bc7e..daf8088 100644 --- a/internal/cli/cart_helpers_test.go +++ b/internal/cli/cart_helpers_test.go @@ -595,3 +595,49 @@ func TestBuildBasketOptionsKeepsGroupsSharingALibraryGroupApart(t *testing.T) { } } } + +// Wolt keeps a dish's selection range on the item-level group +// (multi_choice_config.total_range) and its values and default on the +// library group; the CLI item payload must carry both. +func TestBuildItemPayloadFromAssortmentKeepsItemLevelRanges(t *testing.T) { + assortment := map[string]any{ + "items": []any{ + map[string]any{ + "id": "item-1", + "name": "Kebab", + "price": 1350, + "options": []any{ + map[string]any{ + "id": "grp-salsa", + "option_id": "lib-salsa", + "name": "Salsa", + "prerequisite_values": []any{}, + "multi_choice_config": map[string]any{ + "total_range": map[string]any{"min": 1, "max": 1}, + }, + }, + }, + }, + }, + "options": []any{ + map[string]any{ + "id": "lib-salsa", + "name": "Salsa (library)", + "default_value": "val-mild", + "values": []any{ + map[string]any{"id": "val-mild", "name": "Mild", "price": 0}, + map[string]any{"id": "val-hot", "name": "Hot", "price": 0}, + }, + }, + }, + } + specs := extractOptionSpecs(buildItemPayloadFromAssortment(assortment, "item-1")) + spec, ok := specs["grp-salsa"] + if !ok { + t.Fatalf("specs = %#v, want grp-salsa", specs) + } + if spec.Name != "Salsa" || !spec.Required || spec.MinSelect != 1 || spec.MaxSelect != 1 || + spec.DefaultValueID != "val-mild" || len(spec.Values) != 2 { + t.Fatalf("spec = %#v", spec) + } +} diff --git a/internal/cli/commands_cart.go b/internal/cli/commands_cart.go index 93bf45c..31e736f 100644 --- a/internal/cli/commands_cart.go +++ b/internal/cli/commands_cart.go @@ -9,6 +9,7 @@ import ( woltgateway "github.com/mekedron/wolt-cli/internal/gateway/wolt" "github.com/mekedron/wolt-cli/internal/service/basketprices" "github.com/mekedron/wolt-cli/internal/service/catalogitem" + "github.com/mekedron/wolt-cli/internal/service/itemoptions" "github.com/mekedron/wolt-cli/internal/service/output" "github.com/mekedron/wolt-cli/internal/service/payloadutil" "github.com/spf13/cobra" @@ -550,7 +551,8 @@ func newCartAddCommand(deps Dependencies) *cobra.Command { if len(selectedOptions) > 0 && !hasHydratedOptionSpecs(itemPayload) { warnings = append(warnings, "option metadata unavailable; provide option IDs or use --venue-slug to resolve option names") } - options, err := buildBasketOptions(itemPayload, selectedOptions) + optionResult, err := itemoptions.Build(itemPayload, selectedOptions) + options := optionResult.Options if err != nil { return emitErrorWithWarnings( cmd, @@ -569,7 +571,7 @@ func newCartAddCommand(deps Dependencies) *cobra.Command { linePrice := price if _, weighted := payloadutil.WeightConfigFromItem(itemPayload); !weighted { var ok bool - linePrice, ok = payloadutil.CheckedMultiplyInt(price+basketOptionsTotal(options), count) + linePrice, ok = payloadutil.CheckedMultiplyInt(price+optionResult.UnitTotal, count) if !ok { return emitError( cmd, @@ -705,6 +707,9 @@ func newCartAddCommand(deps Dependencies) *cobra.Command { "item_price": price, "item_currency": currency, } + if len(optionResult.Defaults) > 0 { + data["default_options"] = itemoptions.DefaultsData(optionResult.Defaults) + } if format == output.FormatTable { return writeTable(cmd, buildCartMutationTable(data), flags.Output) @@ -1727,6 +1732,18 @@ func buildCartMutationTable(data map[string]any) string { {"Total items", asString(data["total_items"])}, {"Total", fallbackString(asString(asMap(data["total"])["formatted_amount"]), "-")}, } + if defaults := asSlice(data["default_options"]); len(defaults) > 0 { + labels := make([]string, 0, len(defaults)) + for _, raw := range defaults { + entry := asMap(raw) + labels = append(labels, fmt.Sprintf( + "%s: %s", + fallbackString(asString(entry["group_name"]), asString(entry["group_id"])), + fallbackString(asString(entry["value_name"]), asString(entry["value_id"])), + )) + } + rows = append(rows, []string{"Default options", strings.Join(labels, "; ")}) + } return output.RenderTable("Cart mutation", headers, rows) } diff --git a/internal/mcpserver/cart_checkout_contract_test.go b/internal/mcpserver/cart_checkout_contract_test.go index a9c7a5c..63896be 100644 --- a/internal/mcpserver/cart_checkout_contract_test.go +++ b/internal/mcpserver/cart_checkout_contract_test.go @@ -148,7 +148,7 @@ func TestCartAddSendsWeightedBasketPayload(t *testing.T) { } } -func TestCartAddRejectsRequiredOptionsItCannotRepresent(t *testing.T) { +func TestCartAddRejectsRequiredOptionsWithoutAChoiceOrDefault(t *testing.T) { const ( venueID = "000000000000000000000343" itemID = "000000000000000000000344" @@ -190,7 +190,7 @@ func TestCartAddRejectsRequiredOptionsItCannotRepresent(t *testing.T) { Venue: "synthetic-market", ItemID: itemID, }) - if err == nil || !strings.Contains(err.Error(), "requires option selections") { + if err == nil || !strings.Contains(err.Error(), `option group "size" selection count must be at least 1; got 0`) { t.Fatalf("cart add error = %v, want required-option rejection", err) } if addCalls != 0 { diff --git a/internal/mcpserver/tools_cart.go b/internal/mcpserver/tools_cart.go index e56d4f9..1bbebe2 100644 --- a/internal/mcpserver/tools_cart.go +++ b/internal/mcpserver/tools_cart.go @@ -11,6 +11,7 @@ import ( woltgateway "github.com/mekedron/wolt-cli/internal/gateway/wolt" "github.com/mekedron/wolt-cli/internal/service/basketprices" "github.com/mekedron/wolt-cli/internal/service/catalogitem" + "github.com/mekedron/wolt-cli/internal/service/itemoptions" "github.com/mekedron/wolt-cli/internal/service/observability" "github.com/mekedron/wolt-cli/internal/service/payloadutil" ) @@ -40,7 +41,7 @@ func registerCartTools(srv *mcp.Server, tc *ToolCtx) { mcp.AddTool(srv, &mcp.Tool{ Name: "wolt_cart_add", Title: "Add an item to a basket", - Description: "Add an item after revalidating its current availability. Merges with existing basket items (does not replace them) and resolves current price and venue currency.", + Description: "Add an item after revalidating its current availability. Merges with existing basket items (does not replace them) and resolves current price and venue currency. Choose options with `options` (group and value ids from wolt_venue_item); a required group left out gets its default value, as in the Wolt app, and the line price includes the option prices.", Annotations: mutateAdd, }, tc.handleCartAdd) @@ -143,19 +144,30 @@ func (tc *ToolCtx) handleCartCount(ctx context.Context, _ *mcp.CallToolRequest, type CartAddInput struct { LocationInput - Venue string `json:"venue" jsonschema:"venue slug, id, or url"` - ItemID string `json:"item_id" jsonschema:"24-char item id (see wolt_venue_menu)"` - Count int `json:"count,omitempty" jsonschema:"how many to add (default 1)"` - Price int `json:"price,omitempty" jsonschema:"item price in minor units (auto-detected from menu if omitted)"` - Currency string `json:"currency,omitempty" jsonschema:"3-letter currency (auto-detected if omitted)"` - Name string `json:"name,omitempty" jsonschema:"item display name (auto-detected if omitted)"` - AllowSubstitutions bool `json:"allow_substitutions,omitempty" jsonschema:"if true, the venue may substitute equivalent items"` + Venue string `json:"venue" jsonschema:"venue slug, id, or url"` + ItemID string `json:"item_id" jsonschema:"24-char item id (see wolt_venue_menu)"` + Count int `json:"count,omitempty" jsonschema:"how many to add (default 1)"` + Price int `json:"price,omitempty" jsonschema:"item price in minor units (auto-detected from menu if omitted)"` + Currency string `json:"currency,omitempty" jsonschema:"3-letter currency (auto-detected if omitted)"` + Name string `json:"name,omitempty" jsonschema:"item display name (auto-detected if omitted)"` + AllowSubstitutions bool `json:"allow_substitutions,omitempty" jsonschema:"if true, the venue may substitute equivalent items"` + Options []CartOptionInput `json:"options,omitempty" jsonschema:"option choices for the item; list a value once per unit or set count. Required groups left out get their default value"` } + +// CartOptionInput is one chosen option value of the item being added. +type CartOptionInput struct { + GroupID string `json:"group_id" jsonschema:"option group id (group_id from wolt_venue_item; a library_group_id or the group name also works when unambiguous)"` + ValueID string `json:"value_id" jsonschema:"option value id (value_id from wolt_venue_item; the value name also works when unambiguous)"` + Count int `json:"count,omitempty" jsonschema:"units of this value (default 1)"` +} + type CartAddOutput struct { Summary string `json:"summary"` VenueID string `json:"venue_id"` ItemID string `json:"item_id"` Added int `json:"added"` + Options []any `json:"options,omitempty"` + DefaultOptions []any `json:"default_options,omitempty"` OrderAvailability map[string]any `json:"order_availability,omitempty"` Response map[string]any `json:"response,omitempty"` Warnings []string `json:"warnings,omitempty"` @@ -264,16 +276,30 @@ func (tc *ToolCtx) handleCartAdd(ctx context.Context, _ *mcp.CallToolRequest, in } } } - for _, spec := range payloadutil.ExtractOptionSpecs(itemPayload) { - minSelect := spec.MinSelect - if spec.Required && minSelect < 1 { - minSelect = 1 + selections := itemoptions.Selections{} + for _, option := range in.Options { + groupID := strings.TrimSpace(option.GroupID) + valueID := strings.TrimSpace(option.ValueID) + if groupID == "" || valueID == "" { + return nil, CartAddOutput{}, toolErrf("item was NOT added: every option needs group_id and value_id") } - if minSelect > 0 { - return nil, CartAddOutput{}, toolErrf( - "item was NOT added because it requires option selections, which wolt_cart_add does not accept", - ) + if option.Count < 0 { + return nil, CartAddOutput{}, toolErrf("item was NOT added: option count must be zero or greater") + } + optionCount := option.Count + if optionCount == 0 { + optionCount = 1 } + selections[groupID] = append(selections[groupID], itemoptions.Choice{ValueID: valueID, Count: optionCount}) + } + if len(selections) > 0 && !optionValuesKnown(itemPayload) { + return nil, CartAddOutput{}, toolErrf( + "item was NOT added because its option values and prices could not be loaded; try again later", + ) + } + optionResult, err := itemoptions.Build(itemPayload, selections) + if err != nil { + return nil, CartAddOutput{}, toolErrf("item was NOT added: %v", err) } if price <= 0 { return nil, CartAddOutput{}, toolErrf("could not determine item price; pass `price` in minor units") @@ -282,7 +308,11 @@ func (tc *ToolCtx) handleCartAdd(ctx context.Context, _ *mcp.CallToolRequest, in // A basket line's price is the whole-line total, as the Wolt app stores // it. Weighted lines are repriced by weight when they are built. - linePrice, ok := payloadutil.CheckedMultiplyInt(price, count) + unitPrice, ok := payloadutil.CheckedAddInt(price, optionResult.UnitTotal) + if !ok { + return nil, CartAddOutput{}, toolErrf("item was NOT added because its total exceeds the supported integer range") + } + linePrice, ok := payloadutil.CheckedMultiplyInt(unitPrice, count) if !ok { return nil, CartAddOutput{}, toolErrf("item was NOT added because its total exceeds the supported integer range") } @@ -291,7 +321,7 @@ func (tc *ToolCtx) handleCartAdd(ctx context.Context, _ *mcp.CallToolRequest, in "count": count, "name": name, "price": linePrice, - "options": []any{}, + "options": optionResult.Options, "substitution_settings": map[string]any{ "is_allowed": in.AllowSubstitutions, }, @@ -331,14 +361,27 @@ func (tc *ToolCtx) handleCartAdd(ctx context.Context, _ *mcp.CallToolRequest, in return nil, CartAddOutput{}, toolErr(err) } summary := fmt.Sprintf("added %d × %s to %s basket", count, firstNonEmpty(name, in.ItemID), venueMutationID) + if len(optionResult.Defaults) > 0 { + labels := make([]string, 0, len(optionResult.Defaults)) + for _, applied := range optionResult.Defaults { + labels = append(labels, firstNonEmpty(applied.GroupName, applied.GroupID)+": "+firstNonEmpty(applied.ValueName, applied.ValueID)) + } + summary += "; default options used for " + strings.Join(labels, ", ") + } if asBool(orderAvailability["scheduled_only"]) { summary += "; basket is available for scheduled order only" } + var defaultOptions []any + if len(optionResult.Defaults) > 0 { + defaultOptions = itemoptions.DefaultsData(optionResult.Defaults) + } return nil, CartAddOutput{ Summary: summary, VenueID: venueMutationID, ItemID: in.ItemID, Added: count, + Options: optionResult.Options, + DefaultOptions: defaultOptions, OrderAvailability: orderAvailability, Response: resp, Warnings: append(priceWarnings, availabilityWarnings...), @@ -677,3 +720,18 @@ func lookupProfileLocation(ctx context.Context, tc *ToolCtx) domain.Location { } return profile.Location } + +// optionValuesKnown reports whether every option group of the item comes +// with its values, so chosen values can be validated and priced. +func optionValuesKnown(itemPayload map[string]any) bool { + specs := payloadutil.ExtractOptionSpecs(itemPayload) + if len(specs) == 0 { + return false + } + for _, spec := range specs { + if len(spec.Values) == 0 { + return false + } + } + return true +} diff --git a/internal/mcpserver/tools_item_options_test.go b/internal/mcpserver/tools_item_options_test.go new file mode 100644 index 0000000..5bd1eb3 --- /dev/null +++ b/internal/mcpserver/tools_item_options_test.go @@ -0,0 +1,232 @@ +package mcpserver + +import ( + "context" + "reflect" + "strings" + "testing" + + "github.com/mekedron/wolt-cli/internal/domain" + woltgateway "github.com/mekedron/wolt-cli/internal/gateway/wolt" + "github.com/mekedron/wolt-cli/internal/service/payloadutil" +) + +const ( + optionsVenueID = "000000000000000000000651" + optionsItemID = "000000000000000000000652" +) + +// optionsAssortmentItems mirrors POST /assortment/items for a pizza: the item +// lists item-level groups with multi_choice_config, and the root "options" +// library holds the values, their prices and default_value. +func optionsAssortmentItems() map[string]any { + return map[string]any{ + "items": []any{ + map[string]any{ + "id": optionsItemID, + "name": "Pizza", + "price": 1200, + "purchasable_balance": nil, + "options": []any{ + map[string]any{ + "id": "grp-base", + "option_id": "lib-base", + "name": "Base", + "prerequisite_values": []any{}, + "multi_choice_config": map[string]any{ + "total_range": map[string]any{"min": 1, "max": 1}, + "max_single_selections": 1, + }, + }, + map[string]any{ + "id": "grp-toppings", + "option_id": "lib-toppings", + "name": "Toppings", + "prerequisite_values": []any{}, + "multi_choice_config": map[string]any{ + "total_range": map[string]any{"min": 0, "max": 3}, + "max_single_selections": 1, + }, + }, + }, + }, + }, + "options": []any{ + map[string]any{ + "id": "lib-base", + "name": "Base (+2,00€)", + "type": "choice", + "default_value": "val-wheat", + "values": []any{ + map[string]any{"id": "val-wheat", "name": "Wheat", "price": 200}, + map[string]any{"id": "val-gluten-free", "name": "Gluten free", "price": 400}, + }, + }, + map[string]any{ + "id": "lib-toppings", + "name": "Toppings", + "type": "multi_choice", + "default_value": "val-olives", + "values": []any{ + map[string]any{"id": "val-olives", "name": "Olives", "price": 100}, + map[string]any{"id": "val-ham", "name": "Ham", "price": 150}, + }, + }, + }, + } +} + +func optionsStubWolt(captured *map[string]any) *stubWolt { + return &stubWolt{ + venueStaticFn: func(context.Context, string) (map[string]any, error) { + return map[string]any{ + "venue": map[string]any{"id": optionsVenueID, "slug": "pizza-place", "currency": "EUR"}, + }, nil + }, + assortmentItemsFn: func(context.Context, string, []string, woltgateway.AuthContext) (map[string]any, error) { + return optionsAssortmentItems(), nil + }, + venueItemPageFn: func(context.Context, string, string) (map[string]any, error) { + return map[string]any{"sections": []any{}}, nil + }, + basketsPageFn: func(context.Context, domain.Location, woltgateway.AuthContext) (map[string]any, error) { + return map[string]any{"baskets": []any{}}, nil + }, + addToBasketFn: func(_ context.Context, payload map[string]any, _ woltgateway.AuthContext) (map[string]any, error) { + if captured != nil { + *captured = payload + } + return map[string]any{"id": "basket-options"}, nil + }, + } +} + +// Issue #65: wolt_venue_item returned every group with no values, min 0, +// max 0 and required false. +func TestVenueItemJoinsTheOptionLibrary(t *testing.T) { + tc := regressionMCPToolCtx(optionsStubWolt(nil)) + _, out, err := tc.handleVenueItem(context.Background(), nil, VenueItemInput{ + Venue: "pizza-place", + ItemID: optionsItemID, + }) + if err != nil { + t.Fatalf("handleVenueItem: %v", err) + } + groups := map[string]map[string]any{} + for _, raw := range asSlice(out.Item["option_groups"]) { + group := asMap(raw) + groups[asString(group["group_id"])] = group + } + base := groups["grp-base"] + if base == nil || base["name"] != "Base" || base["required"] != true || + base["min"] != 1 || base["max"] != 1 || base["library_group_id"] != "lib-base" { + t.Fatalf("base group = %#v", base) + } + values := asSlice(base["values"]) + if len(values) != 2 { + t.Fatalf("base values = %#v, want the two library values", values) + } + wheat := asMap(values[1]) + if wheat["value_id"] != "val-wheat" || wheat["price"] != 200 || wheat["default"] != true { + t.Fatalf("wheat value = %#v, want price 200 and default", wheat) + } + toppings := groups["grp-toppings"] + if toppings == nil || toppings["required"] != false || toppings["max"] != 3 || len(asSlice(toppings["values"])) != 2 { + t.Fatalf("toppings group = %#v", toppings) + } + defaultPrice := asMap(out.Item["default_price"]) + if payloadutil.Int(defaultPrice["amount"]) != 1400 { + t.Fatalf("default_price = %#v, want 1200 base + 200 required default", defaultPrice) + } +} + +// Issue #66: wolt_cart_add takes option selections, validates them and +// prices the line with them. +func TestCartAddSendsChosenAndDefaultOptions(t *testing.T) { + var captured map[string]any + tc := regressionMCPToolCtx(optionsStubWolt(&captured)) + _, out, err := tc.handleCartAdd(context.Background(), nil, CartAddInput{ + Venue: "pizza-place", + ItemID: optionsItemID, + Count: 2, + Options: []CartOptionInput{ + {GroupID: "grp-toppings", ValueID: "Ham"}, + {GroupID: "Toppings", ValueID: "val-olives", Count: 1}, + }, + }) + if err != nil { + t.Fatalf("handleCartAdd: %v", err) + } + line := asMap(asSlice(captured["items"])[0]) + // (1200 base + 200 default wheat + 150 ham + 100 olives) x 2 + if line["count"] != 2 || payloadutil.Int(line["price"]) != 3300 { + t.Fatalf("line = %#v, want count 2 and whole-line price 3300", line) + } + got := map[string]map[string]int{} + for _, raw := range asSlice(line["options"]) { + group := asMap(raw) + values := map[string]int{} + for _, rawValue := range asSlice(group["values"]) { + value := asMap(rawValue) + values[asString(value["id"])] = payloadutil.Int(value["count"]) + } + got[asString(group["id"])] = values + } + want := map[string]map[string]int{ + "grp-base": {"val-wheat": 1}, + "grp-toppings": {"val-ham": 1, "val-olives": 1}, + } + if !reflect.DeepEqual(got, want) { + t.Fatalf("basket options = %v, want %v", got, want) + } + if len(out.DefaultOptions) != 1 || asMap(out.DefaultOptions[0])["value_id"] != "val-wheat" { + t.Fatalf("default options = %#v, want the wheat base", out.DefaultOptions) + } + if !strings.Contains(out.Summary, "default options used for Base: Wheat") { + t.Fatalf("summary = %q, want the applied default named", out.Summary) + } +} + +func TestCartAddRejectsInvalidOptionChoices(t *testing.T) { + tests := []struct { + name string + options []CartOptionInput + want string + }{ + { + name: "unknown value", + options: []CartOptionInput{{GroupID: "grp-base", ValueID: "Rye"}}, + want: `unknown option value "Rye"`, + }, + { + name: "two values in a single-choice group", + options: []CartOptionInput{ + {GroupID: "grp-base", ValueID: "val-wheat"}, + {GroupID: "grp-base", ValueID: "val-gluten-free"}, + }, + want: "selection count must be at most 1; got 2", + }, + { + name: "missing value id", + options: []CartOptionInput{{GroupID: "grp-base"}}, + want: "every option needs group_id and value_id", + }, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + var captured map[string]any + tc := regressionMCPToolCtx(optionsStubWolt(&captured)) + _, _, err := tc.handleCartAdd(context.Background(), nil, CartAddInput{ + Venue: "pizza-place", + ItemID: optionsItemID, + Options: test.options, + }) + if err == nil || !strings.Contains(err.Error(), test.want) || !strings.Contains(err.Error(), "NOT added") { + t.Fatalf("handleCartAdd error = %v, want %q", err, test.want) + } + if captured != nil { + t.Fatalf("AddToBasket was called with %#v", captured) + } + }) + } +} diff --git a/internal/service/catalogitem/catalogitem.go b/internal/service/catalogitem/catalogitem.go index 19389af..0a9c0e5 100644 --- a/internal/service/catalogitem/catalogitem.go +++ b/internal/service/catalogitem/catalogitem.go @@ -380,39 +380,47 @@ func ScopedItem(payload map[string]any, itemID string) map[string]any { } } - referenced := make(map[string]struct{}) - appendReference := func(raw any) { - id := strings.TrimSpace(payloadutil.String(raw)) - if id != "" { - referenced[strings.ToLower(id)] = struct{}{} - } + if groups := itemOptionGroups(payload, target); len(groups) > 0 { + scoped["options"] = groups + scoped["option_groups"] = groups } - for _, rawID := range payloadutil.Slice(target["option_group_ids"]) { - appendReference(rawID) + return scoped +} + +// OptionGroups returns the option groups of one item in a payload, joined +// with the payload's option library (see payloadutil.JoinOptionLibrary). +func OptionGroups(payload map[string]any, itemID string) []any { + target := Find(payload, itemID) + if target == nil { + rootID := strings.TrimSpace(payloadutil.String(payloadutil.CoalesceAny(payload["item_id"], payload["id"]))) + if rootID != "" && strings.EqualFold(rootID, strings.TrimSpace(itemID)) { + target = payload + } } - targetGroups := payloadutil.MergeOptionGroups( - payloadutil.Slice(target["options"]), - payloadutil.Slice(target["option_groups"]), - ) - for _, rawGroup := range targetGroups { - appendReference(optionGroupID(rawGroup)) + if target == nil { + return nil } - groups := append([]any(nil), targetGroups...) + return itemOptionGroups(payload, target) +} + +func itemOptionGroups(payload map[string]any, target map[string]any) []any { rootGroups := payloadutil.MergeOptionGroups( payloadutil.Slice(payload["options"]), payloadutil.Slice(payload["option_groups"]), ) + groups := payloadutil.JoinOptionLibrary(target, rootGroups) + // A group the item lists by its own id may also have a root definition; + // MergeOptionGroups keeps whichever of the two is richer. + listed := make(map[string]struct{}, len(groups)) + for _, rawGroup := range groups { + listed[strings.ToLower(optionGroupID(rawGroup))] = struct{}{} + } for _, rawGroup := range rootGroups { - if _, ok := referenced[strings.ToLower(optionGroupID(rawGroup))]; !ok { - continue + if _, ok := listed[strings.ToLower(optionGroupID(rawGroup))]; ok { + groups = payloadutil.MergeOptionGroups(groups, []any{rawGroup}) } - groups = payloadutil.MergeOptionGroups(groups, []any{rawGroup}) } - if len(groups) > 0 { - scoped["options"] = groups - scoped["option_groups"] = groups - } - return scoped + return groups } func optionGroupID(raw any) string { diff --git a/internal/service/itemoptions/itemoptions.go b/internal/service/itemoptions/itemoptions.go new file mode 100644 index 0000000..b76937d --- /dev/null +++ b/internal/service/itemoptions/itemoptions.go @@ -0,0 +1,441 @@ +// Package itemoptions turns option selections for one menu item into the +// option groups of a basket line. The CLI (`wolt cart add --option`) and the +// MCP tool `wolt_cart_add` share it, so both validate and price options the +// same way. +package itemoptions + +import ( + "fmt" + "sort" + "strings" + + "github.com/mekedron/wolt-cli/internal/service/payloadutil" +) + +// Choice is one selected value of an option group. +type Choice struct { + ValueID string + Count int +} + +// Selections maps an option group token (item-level id, library id or name) +// to its chosen values (ids or names). +type Selections map[string][]Choice + +// AppliedDefault records a required group that had no selection and got the +// value the Wolt app preselects. +type AppliedDefault struct { + GroupID string `json:"group_id"` + GroupName string `json:"group_name,omitempty"` + ValueID string `json:"value_id"` + ValueName string `json:"value_name,omitempty"` + Price int `json:"price"` +} + +// Result is the basket form of the selected options. +type Result struct { + // Options are the basket option groups: {id, values: [{id, count, price}]}. + Options []any + // UnitTotal is the price of the options for one unit of the item. + UnitTotal int + // Defaults lists the required groups filled with their default value. + Defaults []AppliedDefault +} + +// Build validates selections against the item's option groups and returns +// the basket option groups. +// +// A required group (minimum of one) left without a selection gets its default +// value, as the Wolt app preselects it; a required group with no usable +// default is an error. A group with prerequisite values applies only while one +// of them is selected: its limits are skipped otherwise, and selecting a value +// in it is an error. Groups the payload does not describe pass through by id. +func Build(itemPayload map[string]any, selections Selections) (Result, error) { + specs := payloadutil.ExtractOptionSpecs(itemPayload) + groupIDs := make([]string, 0, len(specs)) + for groupID := range specs { + groupIDs = append(groupIDs, groupID) + } + sort.Strings(groupIDs) + + tokens := make([]string, 0, len(selections)) + for token := range selections { + tokens = append(tokens, token) + } + sort.Strings(tokens) + + resolved := map[string][]Choice{} + for _, token := range tokens { + groupID := strings.TrimSpace(token) + if len(specs) > 0 { + var err error + groupID, err = ResolveGroupToken(token, specs) + if err != nil { + return Result{}, err + } + } else if groupID == "" { + continue + } + resolved[groupID] = append(resolved[groupID], selections[token]...) + } + if len(specs) == 0 { + for groupID := range resolved { + groupIDs = append(groupIDs, groupID) + } + sort.Strings(groupIDs) + } + + valueCounts := map[string]map[string]int{} + selectionCounts := map[string]int{} + for _, groupID := range groupIDs { + spec := specs[groupID] + for _, choice := range resolved[groupID] { + if choice.Count <= 0 { + return Result{}, fmt.Errorf("option group %q value %q count must be a positive integer", groupID, choice.ValueID) + } + nextCount, ok := payloadutil.CheckedAddInt(selectionCounts[groupID], choice.Count) + if !ok { + return Result{}, fmt.Errorf("option group %q selection count exceeds the supported integer range", groupID) + } + selectionCounts[groupID] = nextCount + valueID := strings.TrimSpace(choice.ValueID) + resolvedValueID, err := ResolveValueToken(choice.ValueID, spec) + if err == nil { + valueID = resolvedValueID + } else if len(spec.Values) > 0 || valueID == "" { + return Result{}, fmt.Errorf("option group %q: %w", groupID, err) + } + if valueCounts[groupID] == nil { + valueCounts[groupID] = map[string]int{} + } + nextValueCount, ok := payloadutil.CheckedAddInt(valueCounts[groupID][valueID], choice.Count) + if !ok { + return Result{}, fmt.Errorf("option group %q value %q count exceeds the supported integer range", groupID, valueID) + } + valueCounts[groupID][valueID] = nextValueCount + } + } + + isSelected := func(valueID string) bool { + for _, values := range valueCounts { + for selectedID := range values { + if strings.EqualFold(selectedID, valueID) { + return true + } + } + } + return false + } + isActive := func(spec payloadutil.OptionGroupSpec) bool { + if len(spec.PrerequisiteValueIDs) == 0 { + return true + } + for _, valueID := range spec.PrerequisiteValueIDs { + if isSelected(valueID) { + return true + } + } + return false + } + + // A default can activate groups that depend on it, so repeat until no + // further default applies. + defaults := []AppliedDefault{} + for changed := true; changed; { + changed = false + for _, groupID := range groupIDs { + spec := specs[groupID] + if selectionCounts[groupID] > 0 || minimum(spec) != 1 || !isActive(spec) { + continue + } + valueID := canonicalValueID(spec, spec.DefaultValueID) + if valueID == "" { + continue + } + valueCounts[groupID] = map[string]int{valueID: 1} + selectionCounts[groupID] = 1 + value := spec.Values[valueID] + defaults = append(defaults, AppliedDefault{ + GroupID: groupID, + GroupName: spec.Name, + ValueID: valueID, + ValueName: value.Name, + Price: value.Price, + }) + changed = true + } + } + + result := Result{Options: make([]any, 0, len(groupIDs)), Defaults: defaults} + for _, groupID := range groupIDs { + spec := specs[groupID] + selectionCount := selectionCounts[groupID] + label := groupLabel(groupID, spec) + if !isActive(spec) { + if selectionCount > 0 { + return Result{}, fmt.Errorf( + "option group %s applies only when one of these option values is selected: %s", + label, + strings.Join(spec.PrerequisiteValueIDs, ", "), + ) + } + continue + } + minSelect := minimum(spec) + maxSelect := spec.MaxSelect + if minSelect < 0 || maxSelect < 0 || (maxSelect > 0 && minSelect > maxSelect) { + return Result{}, fmt.Errorf("option group %s has invalid selection limits", label) + } + if selectionCount < minSelect { + return Result{}, fmt.Errorf( + "option group %s selection count must be at least %d; got %d", + label, + minSelect, + selectionCount, + ) + } + if maxSelect > 0 && selectionCount > maxSelect { + return Result{}, fmt.Errorf( + "option group %s selection count must be at most %d; got %d", + label, + maxSelect, + selectionCount, + ) + } + if len(valueCounts[groupID]) == 0 { + continue + } + valueIDs := make([]string, 0, len(valueCounts[groupID])) + for valueID := range valueCounts[groupID] { + valueIDs = append(valueIDs, valueID) + } + sort.Strings(valueIDs) + + values := make([]any, 0, len(valueIDs)) + for _, valueID := range valueIDs { + count := valueCounts[groupID][valueID] + price := 0 + if valueSpec, ok := spec.Values[valueID]; ok { + if limit := valueLimit(spec, valueSpec); limit > 0 && count > limit { + return Result{}, fmt.Errorf( + "option group %s value %q can be chosen at most %d times; got %d", + label, + valueID, + limit, + count, + ) + } + if !valueSpec.HasPrice { + return Result{}, fmt.Errorf( + "option group %q value %q is missing current price metadata; refresh venue item data and try again", + groupID, + valueID, + ) + } + price = valueSpec.Price + } + valueTotal, ok := payloadutil.CheckedMultiplyInt(price, count) + if !ok { + return Result{}, fmt.Errorf("option group %q value %q total exceeds the supported integer range", groupID, valueID) + } + result.UnitTotal, ok = payloadutil.CheckedAddInt(result.UnitTotal, valueTotal) + if !ok { + return Result{}, fmt.Errorf("option total exceeds the supported integer range") + } + values = append(values, map[string]any{ + "id": valueID, + "count": count, + "price": price, + }) + } + result.Options = append(result.Options, map[string]any{ + "id": groupID, + "values": values, + }) + } + return result, nil +} + +// DefaultConfigurationTotal is the price of the options the Wolt app +// preselects for one unit: the default values of the required groups that +// apply without any other choice. The second result is false when a required +// group has no usable default, so no complete configuration exists without an +// explicit choice. +func DefaultConfigurationTotal(itemPayload map[string]any) (int, bool) { + result, err := Build(itemPayload, nil) + if err != nil { + return 0, false + } + return result.UnitTotal, true +} + +// DefaultsData renders applied defaults as plain maps for JSON and YAML output. +func DefaultsData(defaults []AppliedDefault) []any { + out := make([]any, 0, len(defaults)) + for _, entry := range defaults { + row := map[string]any{ + "group_id": entry.GroupID, + "value_id": entry.ValueID, + "price": entry.Price, + } + if entry.GroupName != "" { + row["group_name"] = entry.GroupName + } + if entry.ValueName != "" { + row["value_name"] = entry.ValueName + } + out = append(out, row) + } + return out +} + +// Total sums price x count over the values of basket option groups. +func Total(options []any) int { + total := 0 + for _, rawOption := range options { + for _, rawValue := range payloadutil.Slice(payloadutil.Map(rawOption)["values"]) { + value := payloadutil.Map(rawValue) + total += payloadutil.Int(value["price"]) * payloadutil.Int(value["count"]) + } + } + return total +} + +func minimum(spec payloadutil.OptionGroupSpec) int { + if spec.Required && spec.MinSelect < 1 { + return 1 + } + return spec.MinSelect +} + +func valueLimit(group payloadutil.OptionGroupSpec, value payloadutil.OptionValueSpec) int { + limit := group.MaxSingleSelections + if value.MaxCount > 0 && (limit == 0 || value.MaxCount < limit) { + limit = value.MaxCount + } + return limit +} + +func canonicalValueID(spec payloadutil.OptionGroupSpec, valueID string) string { + valueID = strings.TrimSpace(valueID) + if valueID == "" { + return "" + } + if _, ok := spec.Values[valueID]; ok { + return valueID + } + for id := range spec.Values { + if strings.EqualFold(id, valueID) { + return id + } + } + return "" +} + +func groupLabel(groupID string, spec payloadutil.OptionGroupSpec) string { + if spec.Name == "" || strings.EqualFold(spec.Name, groupID) { + return fmt.Sprintf("%q", groupID) + } + return fmt.Sprintf("%q (%s)", groupID, spec.Name) +} + +// ResolveGroupToken finds the option group a token names: its item-level id, +// its shared library id (when only one group of the item uses it), or its +// name. +func ResolveGroupToken(token string, specs map[string]payloadutil.OptionGroupSpec) (string, error) { + token = strings.TrimSpace(token) + if token == "" { + return "", fmt.Errorf("option group is required") + } + if _, ok := specs[token]; ok { + return token, nil + } + libraryMatches := []string{} + for groupID, spec := range specs { + if spec.OptionID != "" && strings.EqualFold(spec.OptionID, token) { + libraryMatches = append(libraryMatches, groupID) + } + } + switch len(libraryMatches) { + case 0: + case 1: + return libraryMatches[0], nil + default: + sort.Strings(libraryMatches) + return "", fmt.Errorf( + "option group %q is shared by %d groups of this item; use one of their IDs: %s", + token, + len(libraryMatches), + strings.Join(libraryMatches, ", "), + ) + } + groupIDs := make([]string, 0, len(specs)) + for groupID := range specs { + groupIDs = append(groupIDs, groupID) + } + sort.Strings(groupIDs) + if match, ambiguous := uniqueMatch(token, groupIDs, func(groupID string) string { + return groupID + }); match != "" || ambiguous { + if ambiguous { + return "", fmt.Errorf("ambiguous option group %q; use its ID", token) + } + return match, nil + } + if match, ambiguous := uniqueMatch(token, groupIDs, func(groupID string) string { + return specs[groupID].Name + }); match != "" || ambiguous { + if ambiguous { + return "", fmt.Errorf("ambiguous option group %q; use its ID", token) + } + return match, nil + } + return "", fmt.Errorf("unknown option group %q", token) +} + +// ResolveValueToken finds the value of a group a token names: its id or name. +func ResolveValueToken(token string, group payloadutil.OptionGroupSpec) (string, error) { + token = strings.TrimSpace(token) + if token == "" { + return "", fmt.Errorf("option value is required") + } + if _, ok := group.Values[token]; ok { + return token, nil + } + valueIDs := make([]string, 0, len(group.Values)) + for valueID := range group.Values { + valueIDs = append(valueIDs, valueID) + } + sort.Strings(valueIDs) + if match, ambiguous := uniqueMatch(token, valueIDs, func(valueID string) string { + return valueID + }); match != "" || ambiguous { + if ambiguous { + return "", fmt.Errorf("ambiguous option value %q; use its ID", token) + } + return match, nil + } + if match, ambiguous := uniqueMatch(token, valueIDs, func(valueID string) string { + return group.Values[valueID].Name + }); match != "" || ambiguous { + if ambiguous { + return "", fmt.Errorf("ambiguous option value %q; use its ID", token) + } + return match, nil + } + return "", fmt.Errorf("unknown option value %q", token) +} + +func uniqueMatch(token string, ids []string, label func(string) string) (string, bool) { + match := "" + for _, id := range ids { + if !strings.EqualFold(strings.TrimSpace(label(id)), token) { + continue + } + if match != "" && match != id { + return "", true + } + match = id + } + return match, false +} diff --git a/internal/service/itemoptions/itemoptions_test.go b/internal/service/itemoptions/itemoptions_test.go new file mode 100644 index 0000000..b4bae0a --- /dev/null +++ b/internal/service/itemoptions/itemoptions_test.go @@ -0,0 +1,250 @@ +package itemoptions + +import ( + "reflect" + "strings" + "testing" + + "github.com/mekedron/wolt-cli/internal/service/payloadutil" +) + +// mealAssortment mirrors a live Wolt assortment (Taco Bell meal, 2026-11): +// the dish lists item-level groups with ranges and prerequisites, and the +// venue library carries values, prices and default_value. Every library +// group has a default, including optional ones whose default is a paid extra. +func mealAssortment() map[string]any { + return map[string]any{ + "items": []any{ + map[string]any{ + "id": "item-meal", + "name": "Crunchwrap Meal", + "price": 1699, + "options": []any{ + itemGroup("grp-main", "lib-main", "Crunchwrap", 1, 1, 1, nil), + itemGroup("grp-protein", "lib-protein", "Protein", 1, 1, 1, []any{"val-crunchwrap"}), + itemGroup("grp-extras", "lib-extras", "Add Ingredients", 0, 5, 2, []any{"val-crunchwrap"}), + itemGroup("grp-drink", "lib-drink", "Drink", 1, 1, 1, nil), + itemGroup("grp-sauce", "lib-sauce", "Sauce", 1, 1, 1, []any{"val-never-selected"}), + }, + }, + }, + "options": []any{ + libraryGroup("lib-main", "val-crunchwrap", value("val-crunchwrap", "Crunchwrap", 0, 1)), + libraryGroup("lib-protein", "val-beef", + value("val-beef", "Beef", 0, 1), + value("val-chicken", "Chicken", 0, 1), + ), + libraryGroup("lib-extras", "val-extra-beef", + value("val-extra-beef", "Extra beef", 150, 1), + value("val-cheese", "Cheese", 100, 2), + ), + libraryGroup("lib-drink", "val-cola", + value("val-cola", "Cola", 0, 1), + value("val-large-cola", "Large cola", 120, 1), + ), + libraryGroup("lib-sauce", "val-mild", value("val-mild", "Mild", 0, 1)), + }, + } +} + +func itemGroup(id, libraryID, name string, minimum, maximum, maxSingle int, prerequisites []any) map[string]any { + if prerequisites == nil { + prerequisites = []any{} + } + return map[string]any{ + "id": id, + "option_id": libraryID, + "name": name, + "prerequisite_values": prerequisites, + "multi_choice_config": map[string]any{ + "total_range": map[string]any{"min": minimum, "max": maximum}, + "max_single_selections": maxSingle, + "free_selections": 0, + }, + } +} + +func libraryGroup(id, defaultValue string, values ...any) map[string]any { + return map[string]any{ + "id": id, + "name": id + " library name", + "type": "choice", + "default_value": defaultValue, + "values": values, + } +} + +func value(id, name string, price, maximum int) map[string]any { + return map[string]any{ + "id": id, + "name": name, + "price": price, + "multi_choice_config": map[string]any{ + "total_range": map[string]any{"min": 0, "max": maximum}, + }, + } +} + +func mealPayload(t *testing.T) map[string]any { + t.Helper() + assortment := mealAssortment() + item := payloadutil.Map(payloadutil.Slice(assortment["items"])[0]) + groups := payloadutil.JoinOptionLibrary(item, payloadutil.Slice(assortment["options"])) + if len(groups) != 5 { + t.Fatalf("joined groups = %d, want 5: %#v", len(groups), groups) + } + return map[string]any{"id": "item-meal", "price": 1699, "options": groups} +} + +func selectedValues(options []any) map[string]map[string]int { + out := map[string]map[string]int{} + for _, rawGroup := range options { + group := payloadutil.Map(rawGroup) + values := map[string]int{} + for _, rawValue := range payloadutil.Slice(group["values"]) { + entry := payloadutil.Map(rawValue) + values[payloadutil.String(entry["id"])] = payloadutil.Int(entry["count"]) + } + out[payloadutil.String(group["id"])] = values + } + return out +} + +func TestBuildFillsRequiredGroupsWithTheirDefaults(t *testing.T) { + result, err := Build(mealPayload(t), nil) + if err != nil { + t.Fatalf("Build: %v", err) + } + want := map[string]map[string]int{ + "grp-main": {"val-crunchwrap": 1}, + "grp-protein": {"val-beef": 1}, + "grp-drink": {"val-cola": 1}, + } + if got := selectedValues(result.Options); !reflect.DeepEqual(got, want) { + t.Fatalf("options = %v, want %v (optional extras and the sauce group whose prerequisite is unselected stay out)", got, want) + } + if result.UnitTotal != 0 { + t.Fatalf("UnitTotal = %d, want 0", result.UnitTotal) + } + if len(result.Defaults) != 3 { + t.Fatalf("Defaults = %#v, want three applied defaults", result.Defaults) + } + for _, applied := range result.Defaults { + if applied.GroupID == "grp-protein" && applied.GroupName != "Protein" { + t.Fatalf("default group name = %q, want the item-level name Protein", applied.GroupName) + } + } +} + +func TestBuildKeepsExplicitChoicesAndPricesThem(t *testing.T) { + result, err := Build(mealPayload(t), Selections{ + "grp-drink": {{ValueID: "Large cola", Count: 1}}, + "Add Ingredients": {{ValueID: "val-cheese", Count: 2}, {ValueID: "val-extra-beef", Count: 1}}, + }) + if err != nil { + t.Fatalf("Build: %v", err) + } + got := selectedValues(result.Options) + if !reflect.DeepEqual(got["grp-drink"], map[string]int{"val-large-cola": 1}) { + t.Fatalf("drink = %v, want the explicit large cola, not the default", got["grp-drink"]) + } + if !reflect.DeepEqual(got["grp-extras"], map[string]int{"val-cheese": 2, "val-extra-beef": 1}) { + t.Fatalf("extras = %v", got["grp-extras"]) + } + if result.UnitTotal != 120+2*100+150 { + t.Fatalf("UnitTotal = %d, want %d", result.UnitTotal, 120+2*100+150) + } + for _, applied := range result.Defaults { + if applied.GroupID == "grp-drink" { + t.Fatalf("explicit drink choice must not be reported as a default: %#v", result.Defaults) + } + } +} + +func TestBuildRejectsChoicesOutsideTheLimits(t *testing.T) { + tests := []struct { + name string + selections Selections + want string + }{ + { + name: "group whose prerequisite is not selected", + selections: Selections{"grp-sauce": {{ValueID: "val-mild", Count: 1}}}, + want: `option group "grp-sauce" (Sauce) applies only when one of these option values is selected: val-never-selected`, + }, + { + name: "value above max_single_selections", + selections: Selections{"grp-extras": {{ValueID: "val-cheese", Count: 2}, {ValueID: "val-cheese", Count: 1}}}, + want: `value "val-cheese" can be chosen at most 2 times; got 3`, + }, + { + name: "value above its own maximum", + selections: Selections{"grp-extras": {{ValueID: "val-extra-beef", Count: 2}}}, + want: `value "val-extra-beef" can be chosen at most 1 times; got 2`, + }, + { + name: "unknown value", + selections: Selections{"grp-drink": {{ValueID: "Lemonade", Count: 1}}}, + want: `unknown option value "Lemonade"`, + }, + { + name: "group above its maximum", + selections: Selections{"grp-drink": {{ValueID: "val-cola", Count: 1}, {ValueID: "val-large-cola", Count: 1}}}, + want: `option group "grp-drink" (Drink) selection count must be at most 1; got 2`, + }, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + _, err := Build(mealPayload(t), test.selections) + if err == nil || !strings.Contains(err.Error(), test.want) { + t.Fatalf("Build error = %v, want it to contain %q", err, test.want) + } + }) + } +} + +func TestBuildRequiresAChoiceWhenARequiredGroupHasNoDefault(t *testing.T) { + payload := map[string]any{ + "options": []any{ + map[string]any{ + "id": "grp-size", + "name": "Size", + "multi_choice_config": map[string]any{"total_range": map[string]any{"min": 1, "max": 1}}, + "values": []any{map[string]any{"id": "val-small", "price": 0}}, + }, + }, + } + if _, err := Build(payload, nil); err == nil || + !strings.Contains(err.Error(), `option group "grp-size" (Size) selection count must be at least 1; got 0`) { + t.Fatalf("Build error = %v, want a missing required choice", err) + } + if _, ok := DefaultConfigurationTotal(payload); ok { + t.Fatal("DefaultConfigurationTotal must report that a choice is needed") + } +} + +func TestDefaultConfigurationTotalAddsPaidRequiredDefaults(t *testing.T) { + payload := map[string]any{ + "options": []any{ + map[string]any{ + "id": "grp-base", + "default_value": "val-regular", + "multi_choice_config": map[string]any{"total_range": map[string]any{"min": 1, "max": 1}}, + "values": []any{ + map[string]any{"id": "val-regular", "price": 250}, + map[string]any{"id": "val-large", "price": 400}, + }, + }, + map[string]any{ + "id": "grp-extra", + "default_value": "val-bacon", + "multi_choice_config": map[string]any{"total_range": map[string]any{"min": 0, "max": 1}}, + "values": []any{map[string]any{"id": "val-bacon", "price": 150}}, + }, + }, + } + total, ok := DefaultConfigurationTotal(payload) + if !ok || total != 250 { + t.Fatalf("DefaultConfigurationTotal = %d, %v; want 250, true (the optional bacon default is not preselected)", total, ok) + } +} diff --git a/internal/service/observability/items.go b/internal/service/observability/items.go index a13c61a..ba32ffc 100644 --- a/internal/service/observability/items.go +++ b/internal/service/observability/items.go @@ -199,36 +199,7 @@ func extractOptionGroups(node any, itemID string) []map[string]any { if payload == nil { return []map[string]any{} } - target := catalogitem.Find(payload, itemID) - if target == nil { - rootID := strings.TrimSpace(stringFromAny(coalesce(payload["item_id"], payload["id"]))) - if strings.EqualFold(rootID, strings.TrimSpace(itemID)) { - target = payload - } - } - if target == nil { - return []map[string]any{} - } - - referenced := map[string]struct{}{} - for _, groupID := range extractOptionGroupIDs(target) { - referenced[strings.ToLower(groupID)] = struct{}{} - } - groups := payloadutil.MergeOptionGroups( - toSlice(target["options"]), - toSlice(target["option_groups"]), - ) - rootGroups := payloadutil.MergeOptionGroups( - toSlice(payload["options"]), - toSlice(payload["option_groups"]), - ) - for _, rawGroup := range rootGroups { - groupID := rawOptionGroupID(rawGroup) - if _, wanted := referenced[strings.ToLower(groupID)]; !wanted { - continue - } - groups = payloadutil.MergeOptionGroups(groups, []any{rawGroup}) - } + groups := catalogitem.OptionGroups(payload, itemID) specs := payloadutil.ExtractOptionSpecs(map[string]any{"option_groups": groups}) groupIDs := make([]string, 0, len(specs)) for groupID := range specs { @@ -254,29 +225,30 @@ func extractOptionGroups(node any, itemID string) []map[string]any { if valueSpec.HasPrice { value["price"] = valueSpec.Price } + if spec.DefaultValueID != "" && strings.EqualFold(spec.DefaultValueID, valueID) { + value["default"] = true + } values = append(values, value) } - out = append(out, map[string]any{ + group := map[string]any{ "group_id": groupID, "name": spec.Name, "required": spec.Required, "min": spec.MinSelect, "max": spec.MaxSelect, "values": values, - }) + } + if spec.OptionID != "" { + group["library_group_id"] = spec.OptionID + } + if len(spec.PrerequisiteValueIDs) > 0 { + group["prerequisite_value_ids"] = append([]string(nil), spec.PrerequisiteValueIDs...) + } + out = append(out, group) } return out } -func rawOptionGroupID(raw any) string { - group := toMap(raw) - return strings.TrimSpace(stringFromAny(coalesce( - group["id"], - group["group_id"], - group["option_id"], - ))) -} - func extractUpsellItems(node any) []map[string]any { candidateKeys := []string{"upsell_items", "related_items", "recommended_items"} upsell := []map[string]any{} diff --git a/internal/service/observability/items_builders.go b/internal/service/observability/items_builders.go index 4d4542c..c63f5e5 100644 --- a/internal/service/observability/items_builders.go +++ b/internal/service/observability/items_builders.go @@ -6,6 +6,8 @@ import ( "strings" "github.com/mekedron/wolt-cli/internal/domain" + "github.com/mekedron/wolt-cli/internal/service/catalogitem" + "github.com/mekedron/wolt-cli/internal/service/itemoptions" ) // BuildVenueMenu builds normalized venue menu payload. @@ -439,6 +441,9 @@ func BuildItemDetail( "option_groups": extractOptionGroups(payload, itemID), "upsell_items": upsellItems, } + if defaultPrice := defaultConfigurationPrice(payload, itemID, price); defaultPrice != nil { + data["default_price"] = defaultPrice + } if itemContext.VenueSlug != "" { data["venue_slug"] = itemContext.VenueSlug } @@ -567,3 +572,29 @@ func CopyItemMetadata(target map[string]any, source map[string]any) { } } } + +// defaultConfigurationPrice is the item price with the options the Wolt app +// preselects: the base price plus the default values of the required groups. +// It is nil for an item without option groups, without a base amount, or with +// a required group that has no default (a choice is needed first). +func defaultConfigurationPrice(payload map[string]any, itemID string, price map[string]any) map[string]any { + groups := catalogitem.OptionGroups(payload, itemID) + rawAmount, hasAmount := price["amount"] + if len(groups) == 0 || !hasAmount || rawAmount == nil { + return nil + } + optionsTotal, ok := itemoptions.DefaultConfigurationTotal(map[string]any{"option_groups": groups}) + if !ok { + return nil + } + amount := intValue(rawAmount) + optionsTotal + currency := strings.TrimSpace(stringFromAny(price["currency"])) + out := map[string]any{"amount": amount} + if currency != "" { + out["currency"] = currency + if formatted := formatAmount(&amount, currency); formatted != nil { + out["formatted_amount"] = *formatted + } + } + return out +} diff --git a/internal/service/payloadutil/payloadutil.go b/internal/service/payloadutil/payloadutil.go index a648b81..bdd4b87 100644 --- a/internal/service/payloadutil/payloadutil.go +++ b/internal/service/payloadutil/payloadutil.go @@ -28,6 +28,7 @@ type OptionValueSpec struct { Name string Price int HasPrice bool + MaxCount int // most units of this one value per line; 0 means no limit } type OptionGroupSpec struct { @@ -37,7 +38,14 @@ type OptionGroupSpec struct { Required bool MinSelect int MaxSelect int - Values map[string]OptionValueSpec + // MaxSingleSelections caps the count of any one value; 0 means no limit. + MaxSingleSelections int + // DefaultValueID is the value the Wolt app preselects for the group. + DefaultValueID string + // PrerequisiteValueIDs make the group apply only when one of these values + // (from another group of the same item) is selected. Empty means always. + PrerequisiteValueIDs []string + Values map[string]OptionValueSpec } // BasketVenueIdentity is the venue identity carried by a basket payload. @@ -635,14 +643,31 @@ func ExtractOptionSpecs(payload map[string]any) map[string]OptionGroupSpec { spec.OptionID = libraryID } if spec.Name == "" { - spec.Name = String(CoalesceAny(group["name"], group["title"])) + spec.Name = strings.TrimSpace(String(CoalesceAny(group["name"], group["title"]))) } - spec.Required = spec.Required || Bool(group["required"]) + // Wolt assortments carry the selection range of an item-level group in + // multi_choice_config.total_range; older payloads use flat fields. + choiceConfig := Map(group["multi_choice_config"]) + totalRange := Map(choiceConfig["total_range"]) if spec.MinSelect == 0 { - spec.MinSelect = Int(CoalesceAny(group["min"], group["minimum"], group["min_select"])) + spec.MinSelect = Int(CoalesceAny(group["min"], group["minimum"], group["min_select"], totalRange["min"])) } if spec.MaxSelect == 0 { - spec.MaxSelect = Int(CoalesceAny(group["max"], group["maximum"], group["max_select"])) + spec.MaxSelect = Int(CoalesceAny(group["max"], group["maximum"], group["max_select"], totalRange["max"])) + } + if spec.MaxSingleSelections == 0 { + spec.MaxSingleSelections = Int(choiceConfig["max_single_selections"]) + } + spec.Required = spec.Required || Bool(group["required"]) || spec.MinSelect >= 1 + if spec.DefaultValueID == "" { + spec.DefaultValueID = strings.TrimSpace(String(group["default_value"])) + } + if len(spec.PrerequisiteValueIDs) == 0 { + for _, raw := range Slice(group["prerequisite_values"]) { + if valueID := strings.TrimSpace(String(raw)); valueID != "" { + spec.PrerequisiteValueIDs = append(spec.PrerequisiteValueIDs, valueID) + } + } } for _, alias := range []string{"values", "options", "items"} { @@ -671,6 +696,9 @@ func ExtractOptionSpecs(payload map[string]any) map[string]OptionGroupSpec { valueSpec.Price = price valueSpec.HasPrice = true } + if valueSpec.MaxCount == 0 { + valueSpec.MaxCount = Int(Map(Map(valueMap["multi_choice_config"])["total_range"])["max"]) + } spec.Values[canonicalValueID] = valueSpec } } @@ -722,6 +750,99 @@ func MergeOptionGroups(existing []any, incoming []any) []any { return out } +// JoinOptionLibrary returns the option groups of one assortment item with the +// shared option library joined in. +// +// A dish names each option group by an item-level "id" and points at the +// venue's option library through "option_id". The item-level entry carries +// the dish-specific name, selection range (multi_choice_config) and +// prerequisite_values; the library entry carries the values, their prices and +// default_value. The basket API and the Wolt app recognise only the +// item-level id, and one library group can back several groups of the same +// dish (pick 1, 2 or 3 toppings), so every item-level group becomes its own +// group carrying the library values. Groups referenced only through +// option_group_ids come from the library as they are; item groups with no +// library entry stay as they are. +func JoinOptionLibrary(item map[string]any, library []any) []any { + if item == nil { + return nil + } + libraryIndex := map[string]map[string]any{} + for _, rawGroup := range library { + group := Map(rawGroup) + if id := optionGroupID(group); id != "" { + libraryIndex[strings.ToLower(id)] = group + } + } + + out := []any{} + seen := map[string]struct{}{} + coveredLibraryIDs := map[string]struct{}{} + appendGroup := func(group map[string]any) { + key := strings.ToLower(optionGroupID(group)) + if _, exists := seen[key]; exists { + return + } + seen[key] = struct{}{} + out = append(out, group) + } + for _, rawOption := range MergeOptionGroups(Slice(item["options"]), Slice(item["option_groups"])) { + option := Map(rawOption) + if option == nil { + continue + } + libraryID := strings.TrimSpace(String(option["option_id"])) + libraryGroup := libraryIndex[strings.ToLower(libraryID)] + if libraryID == "" || libraryGroup == nil || sameMap(libraryGroup, option) { + if optionGroupID(option) != "" { + appendGroup(option) + } + continue + } + coveredLibraryIDs[strings.ToLower(libraryID)] = struct{}{} + joined := make(map[string]any, len(libraryGroup)+len(option)) + for key, value := range libraryGroup { + joined[key] = value + } + for key, value := range option { + if text, ok := value.(string); ok && strings.TrimSpace(text) == "" { + continue + } + if value == nil { + continue + } + joined[key] = value + } + if name := strings.TrimSpace(String(option["name"])); name != "" { + joined["name"] = name + } + itemLevelID := strings.TrimSpace(String(CoalesceAny(option["id"], option["group_id"]))) + if itemLevelID == "" { + itemLevelID = libraryID + } + joined["id"] = itemLevelID + joined["option_id"] = libraryID + appendGroup(joined) + } + for _, rawID := range Slice(item["option_group_ids"]) { + key := strings.ToLower(strings.TrimSpace(String(rawID))) + if _, covered := coveredLibraryIDs[key]; covered { + continue + } + if group := libraryIndex[key]; group != nil { + appendGroup(group) + } + } + return out +} + +func sameMap(left map[string]any, right map[string]any) bool { + if left == nil || right == nil { + return false + } + return reflect.ValueOf(left).Pointer() == reflect.ValueOf(right).Pointer() +} + func optionGroupID(raw any) string { group := Map(raw) return strings.TrimSpace(String(CoalesceAny( @@ -740,7 +861,10 @@ func optionGroupScore(raw any) int { if strings.TrimSpace(String(CoalesceAny(group["name"], group["title"]))) != "" { score++ } - for _, key := range []string{"required", "min", "minimum", "min_select", "max", "maximum", "max_select"} { + for _, key := range []string{ + "required", "min", "minimum", "min_select", "max", "maximum", "max_select", + "multi_choice_config", "default_value", + } { if _, exists := group[key]; exists { score++ } diff --git a/skills/wolt-cli/references/command-reference.md b/skills/wolt-cli/references/command-reference.md index a4a1eb1..dfbbe4a 100644 --- a/skills/wolt-cli/references/command-reference.md +++ b/skills/wolt-cli/references/command-reference.md @@ -109,7 +109,7 @@ tool `wolt_venue_search_items`. - `wolt cart remove [--count ] [--all] [--venue-id ] [--address ... | --lat ... --lon ...]` - `wolt cart clear [--venue-id ] [--all] [--address ... | --lat ... --lon ...]` -`` accepts slug, hex ID, or Wolt URL (same as `venue`). `` on `cart add`/`cart remove` and `venue item` accepts a 24-char Mongo ObjectID or a Wolt item URL (`.../venue//itemid-`, `menuitem-`, or `?itemid=`). `--option` accepts both IDs and case-insensitive names (e.g. `--option "Drink=Cola"`). With complete option metadata, unknown or ambiguous names are rejected; use the displayed ID to disambiguate. A group ID may be the library ID from `venue menu --include-options` or the dish's item-level ID from `venue item`; the basket always stores the item-level ID, and a library ID the dish uses more than once is rejected with the item-level IDs to pick from. The saved line price is the whole-line total: count x (item price plus the selected paid option values), as the Wolt app stores it. If multiple baskets exist and no `--venue-id` is passed, commands select the first basket. +`` accepts slug, hex ID, or Wolt URL (same as `venue`). `` on `cart add`/`cart remove` and `venue item` accepts a 24-char Mongo ObjectID or a Wolt item URL (`.../venue//itemid-`, `menuitem-`, or `?itemid=`). `--option` accepts both IDs and case-insensitive names (e.g. `--option "Drink=Cola"`). With complete option metadata, unknown or ambiguous names are rejected; use the displayed ID to disambiguate. A group ID may be the library ID from `venue menu --include-options` or the dish's item-level ID from `venue item`; the basket always stores the item-level ID, and a library ID the dish uses more than once is rejected with the item-level IDs to pick from. The saved line price is the whole-line total: count x (item price plus the selected paid option values), as the Wolt app stores it. A required option group left without `--option` gets its default value (marked `default: true` in `venue item`), as the Wolt app preselects it, and `default_options` in the result lists it; groups with `prerequisite_value_ids` apply only after one of those values is chosen. The MCP tool `wolt_cart_add` takes the same choices as `options: [{group_id, value_id, count?}]`. If multiple baskets exist and no `--venue-id` is passed, commands select the first basket. ## Checkout