diff --git a/AGENTS.md b/AGENTS.md index e67981d0..06040fc0 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -43,7 +43,7 @@ Other: - `mix graphql.schema` — writes the schema SDL to `priv/graphql/schema.graphql`. A test fails when that file is stale, and the frontend GraphQL check reads it, so run this after every schema change and commit the result. - `bin/setup` — first-time bootstrap. -Credentials live in `config/dev.secret.exs` (gitignored, optional: the fake stack boots without it) and `config/runtime.exs` via env vars (`NEW_RELIC_LICENSE_KEY`, `SENTRY_DSN`, supermarket auth). Don't commit those. +Credentials live in `config/dev.secret.exs` (gitignored, optional: the fake stack boots without it) and `config/runtime.exs` via env vars (`NEW_RELIC_LICENSE_KEY`, `SENTRY_DSN`, supermarket auth, `PICNIC_AUTH_KEY` plus optional `PICNIC_BASE_URL`/`PICNIC_AGENT`/`PICNIC_DID`/`PICNIC_USER_AGENT` for picnic mode). Don't commit those. ## Deploy diff --git a/README.md b/README.md index 6de71c25..8655c333 100644 --- a/README.md +++ b/README.md @@ -35,10 +35,12 @@ It is a route in the Phoenix router, so it is up whenever the app is, on the dat | --- | --- | | `search_ingredients` | Search the ingredients Picape knows, by name | | `search_supermarket` | Search the supermarket's product catalogue | +| `search_picnic` | Search the Picnic product catalogue | +| `map_ingredient_picnic` | Set or clear the Picnic product behind an ingredient | | `get_shopping_list` | Read the current order: items, quantities, totals, availability and the freeze state | | `get_previous_orders` | Read closed orders: items, quantities and when each closed, including products added in the supermarket's own app | | `set_ingredient_quantity` | Put an ingredient on the list, change it, or remove it with quantity 0 | -| `set_mode` | Switch where the list lives: the supermarket basket or Picape's own checklist | +| `set_mode` | Switch where the list lives: the supermarket basket, the Picnic cart or Picape's own checklist | | `check_item` | Tick an item off the checklist, or untick it | | `add_ingredient` | Teach Picape an ingredient, backed by a supermarket product ID | | `edit_ingredient` | Change an ingredient, for example onto another supermarket product | @@ -84,7 +86,8 @@ Notes on the tools: - `edit_ingredient` is the other way round: it changes only the fields you send and leaves the rest, tags included. When the supermarket drops a product, `search_ingredients` reports a `warning` and `edit_ingredient` moves the ingredient onto a replacement product, which keeps the recipes that use it. - `set_ingredient_replacement` is different from repointing an ingredient: the ingredient keeps its product, and sync orders the replacement's product only while the wanted one cannot be delivered. The cart row then says what it stands in for (`substituted_for`). - `get_shopping_list` marks products the supermarket cannot deliver right now with `is_orderable: false`; `only_unavailable: true` returns just those. While the supermarket processes a paid order the answer's `is_placed` is true and Picape freezes: `set_ingredient_quantity` and `plan_recipe` still record the intent, but nothing reaches the supermarket until the order is delivered. -- `get_shopping_list` also reports `mode`. `ah` means the list lives in the supermarket basket; `checklist` means it lives in Picape's own database and planning, ordering and ticking work without the supermarket. Switch with `set_mode`; switching back to `ah` pushes the accumulated list into the basket and the reply's `pushed_to_supermarket` says whether that worked. `check_item` ticks items only in checklist mode. +- `get_shopping_list` also reports `mode`, and `store` per item. `ah` means the list lives in the supermarket basket; `picnic` means it lives in the Picnic cart; `checklist` means it lives in Picape's own database and planning, ordering and ticking work without a supermarket. In picnic mode an ingredient without a Picnic mapping shows up as a `checklist` item. Switch with `set_mode`; switching to `ah` or `picnic` pushes the accumulated list into that basket and the reply's `pushed_to_supermarket` says whether that worked. `check_item` ticks items in checklist and picnic mode. +- Picnic mode syncs the plan into the Picnic cart for every ingredient that has a `picnic_product_id` (set with `map_ingredient_picnic`, found with `search_picnic`). Picape never checks out, pays or picks a delivery slot at Picnic. Ordering finishes in the Picnic app, and Picape cannot see that checkout: after the Picnic order is in, tap "Bestelling ontvangen" in Picape to close the order the way the supermarket's delivered order does. Picnic mode needs `PICNIC_AUTH_KEY` in the environment: the `x-picnic-auth` value the Picnic app itself sends on every request, taken from an app session. The storefront api has no refresh flow, so Picape uses the key as it is; when Picnic rejects it the calls fail and the list falls back to the checklist until a fresh key is configured. `PICNIC_BASE_URL`, `PICNIC_AGENT`, `PICNIC_DID` and `PICNIC_USER_AGENT` have defaults. - `get_previous_orders` reads the basket contents Picape snapshot at the moment each order closed, so products that were added in the supermarket's own app appear with `ingredient_id: null` and `external: true`. Orders closed before snapshots existed fall back to what Picape's plan rows recorded, so their external items are lost. - There is no delete for recipes or ingredients. - The two history tools read finished orders only, nine years of them. The order being planned now is not history yet, an ingredient taken off a list again was never bought, and a recipe that was unplanned again was never cooked, so none of the three count. diff --git a/config/runtime.exs b/config/runtime.exs index 1ed25806..d0c27286 100644 --- a/config/runtime.exs +++ b/config/runtime.exs @@ -26,6 +26,13 @@ if config_env() == :prod do "X-Clientname": System.get_env("SUPERMARKET_CLIENT_NAME"), "User-Agent": System.get_env("SUPERMARKET_USER_AGENT") ] + + config :picape, Picape.Picnic, + base_url: System.get_env("PICNIC_BASE_URL"), + auth_key: System.get_env("PICNIC_AUTH_KEY"), + agent: System.get_env("PICNIC_AGENT"), + did: System.get_env("PICNIC_DID"), + user_agent: System.get_env("PICNIC_USER_AGENT") end if config_env() == :dev do @@ -33,6 +40,15 @@ if config_env() == :dev do config :picape, Picape.Supermarket, base_url: base_url end + if System.get_env("PICNIC_BASE_URL") || System.get_env("PICNIC_AUTH_KEY") do + config :picape, Picape.Picnic, + base_url: System.get_env("PICNIC_BASE_URL"), + auth_key: System.get_env("PICNIC_AUTH_KEY"), + agent: System.get_env("PICNIC_AGENT"), + did: System.get_env("PICNIC_DID"), + user_agent: System.get_env("PICNIC_USER_AGENT") + end + if System.get_env("SUPERMARKET_REFRESH") == "0" do config :picape, Picape.Supermarket.KeepLogin, refresh: false end diff --git a/config/test.exs b/config/test.exs index 09302457..36ea1c96 100644 --- a/config/test.exs +++ b/config/test.exs @@ -27,3 +27,5 @@ config :picape, Picape.Repo, ownership_timeout: 60_000 config :picape, Picape.Supermarket, base_url: "http://localhost:4021", headers: [] + +config :picape, Picape.Picnic, base_url: "http://localhost:4021/api/15", auth_key: "test-auth-key" diff --git a/e2e/tests/__screenshots__/ipad/shop.png b/e2e/tests/__screenshots__/ipad/shop.png index 17fc5cb6..455c0f0a 100644 Binary files a/e2e/tests/__screenshots__/ipad/shop.png and b/e2e/tests/__screenshots__/ipad/shop.png differ diff --git a/e2e/tests/__screenshots__/iphone-standalone/shop.png b/e2e/tests/__screenshots__/iphone-standalone/shop.png index 00eff63d..383cb20f 100644 Binary files a/e2e/tests/__screenshots__/iphone-standalone/shop.png and b/e2e/tests/__screenshots__/iphone-standalone/shop.png differ diff --git a/e2e/tests/__screenshots__/iphone/shop.png b/e2e/tests/__screenshots__/iphone/shop.png index 93b73c0c..c912af6b 100644 Binary files a/e2e/tests/__screenshots__/iphone/shop.png and b/e2e/tests/__screenshots__/iphone/shop.png differ diff --git a/frontend/components/Search/SearchIngredients.js b/frontend/components/Search/SearchIngredients.js index cdfe985c..4e2ddf17 100644 --- a/frontend/components/Search/SearchIngredients.js +++ b/frontend/components/Search/SearchIngredients.js @@ -1,4 +1,4 @@ -import { useLazyQuery, gql } from '@apollo/client'; +import { useLazyQuery, useQuery, gql } from '@apollo/client'; import { useNavigation } from '@react-navigation/native'; import { LinearGradient } from 'expo-linear-gradient'; import * as React from 'react'; @@ -15,7 +15,7 @@ import { ListItem } from '../ListItem/ListItem'; import SearchBar from '../Search/SearchBar'; const SEARCH_INGREDIENTS = gql` - query SearchIngredient($query: String!, $supermarket: Boolean!) { + query SearchIngredient($query: String!, $supermarket: Boolean!, $picnic: Boolean!) { ingredients: searchIngredient(query: $query) @skip(if: $supermarket) { id name @@ -26,7 +26,13 @@ const SEARCH_INGREDIENTS = gql` description } } - ingredients: searchSupermarket(query: $query) @include(if: $supermarket) { + ingredients: searchSupermarket(query: $query) @include(if: $supermarket) @skip(if: $picnic) { + id + name + imageUrl + unitQuantity + } + ingredients: searchPicnic(query: $query) @include(if: $picnic) { id name imageUrl @@ -35,6 +41,14 @@ const SEARCH_INGREDIENTS = gql` } `; +const GET_MODE = gql` + query SearchIngredientsMode { + currentOrder { + mode + } + } +`; + const renderItem = ({ navigator, item: ingredient, supermarket }) => ( + searchIngredients({ + variables: { query: text, supermarket: toStore, picnic: toStore && picnic }, + }); + const ingredients = query === '' ? [] : foundIngredients; const renderRow = (item) => customRenderItem @@ -98,14 +121,14 @@ export function SearchIngredients({ placeholder={placeholder} showLoading={searchLoading} loadingProps={{ color: Colors.tintColor }} - onChangeText={(query) => searchIngredients({ variables: { query, supermarket } })} + onChangeText={(text) => runSearch(text, supermarket)} value={query} rightIcon={ supermarketOnly ? null : ( { setSupermarket(!supermarket); - return searchIngredients({ variables: { query, supermarket: !supermarket } }); + return runSearch(query, !supermarket); }} style={{ color: Colors.text, @@ -115,7 +138,7 @@ export function SearchIngredients({ borderRadius: 7, padding: 5, }}> - {supermarket ? 'AH' : 'Picape'} + {supermarket ? (picnic ? 'Picnic' : 'AH') : 'Picape'} ) } diff --git a/frontend/operations/getOrder.js b/frontend/operations/getOrder.js index dbd786ce..115f0f59 100644 --- a/frontend/operations/getOrder.js +++ b/frontend/operations/getOrder.js @@ -21,6 +21,7 @@ export const orderFields = gql` availabilityLabel substitutedFor checked + store ingredient { id name diff --git a/frontend/screens/AddIngredientScreen.js b/frontend/screens/AddIngredientScreen.js index ea1667f6..d96b1b52 100644 --- a/frontend/screens/AddIngredientScreen.js +++ b/frontend/screens/AddIngredientScreen.js @@ -13,11 +13,17 @@ import { FloatingTop, Spacing } from '../constants/Spacing'; import { useSheetGesture } from '../navigation/useSheetGesture'; const ADD_INGREDIENT = gql` - mutation AddIngredient($name: String!, $isEssential: Boolean!, $supermarketProductId: String!) { + mutation AddIngredient( + $name: String! + $isEssential: Boolean! + $supermarketProductId: String + $picnicProductId: String + ) { addIngredient( name: $name isEssential: $isEssential supermarketProductId: $supermarketProductId + picnicProductId: $picnicProductId ) { id name @@ -29,6 +35,10 @@ const ADD_INGREDIENT = gql` } `; +// A Picnic selling unit id looks like "s2001"; those go in picnicProductId, +// never in supermarketProductId. +const isPicnicId = (id) => /^s\d+$/.test(String(id || '')); + export function AddIngredientScreen({ navigation, route: { @@ -38,7 +48,8 @@ export function AddIngredientScreen({ const [form, changeForm] = useState({ name: ingredient.name, isEssential: false, - supermarketProductId: ingredient.id, + supermarketProductId: isPicnicId(ingredient.id) ? null : ingredient.id, + picnicProductId: isPicnicId(ingredient.id) ? ingredient.id : null, }); const insets = useSafeAreaInsets(); const colors = useTheme(); @@ -107,6 +118,7 @@ export function AddIngredientScreen({ variables: { name: form.name, supermarketProductId: form.supermarketProductId, + picnicProductId: form.picnicProductId, isEssential: form.isEssential, }, }); diff --git a/frontend/screens/EditIngredientScreen.js b/frontend/screens/EditIngredientScreen.js index 0fb26a33..44b31f05 100644 --- a/frontend/screens/EditIngredientScreen.js +++ b/frontend/screens/EditIngredientScreen.js @@ -41,6 +41,9 @@ const GET_INGREDIENT = gql` isEssential supermarketProductId supermarketName + picnicProductId + picnicName + picnicImageUrl tags { id name @@ -51,6 +54,9 @@ const GET_INGREDIENT = gql` } } } + currentOrder { + mode + } ingredients(first: 1000) { tags { id @@ -84,18 +90,25 @@ export function EditIngredientScreen({ name: '', isEssential: false, supermarketProductId: '', + picnicProductId: null, + picnicName: '', }); - const { data: { node: ingredient } = {}, loading } = useQuery(GET_INGREDIENT, { - variables: { ingredientId }, - onCompleted: (data) => { - changeForm({ - name: data.node.name, - isEssential: data.node.isEssential, - supermarketProductId: data.node.supermarketProductId, - }); - }, - }); + const { data: { node: ingredient, currentOrder: { mode } = {} } = {}, loading } = useQuery( + GET_INGREDIENT, + { + variables: { ingredientId }, + onCompleted: (data) => { + changeForm({ + name: data.node.name, + isEssential: data.node.isEssential, + supermarketProductId: data.node.supermarketProductId, + picnicProductId: data.node.picnicProductId, + }); + }, + } + ); + const picnic = mode === 'picnic'; if (loading) return null; if (!loading && !ingredient) { @@ -155,30 +168,53 @@ export function EditIngredientScreen({ - Supermarket + + {picnic ? 'Picnic' : 'Supermarket'} + ( - + placeholder={ + picnic + ? form.picnicName || ingredient.picnicName || 'Zoek in Picnic' + : form.supermarketName || ingredient.supermarketName + } + customRenderItem={({ item: product, searchRef }) => ( + { e.preventDefault(); searchRef.current.clear(); - console.log(ingredient); - return changeForm({ - ...form, - supermarketProductId: ingredient.id, - supermarketName: ingredient.name, - }); + return changeForm( + picnic + ? { + ...form, + picnicProductId: product.id, + picnicName: product.name, + } + : { + ...form, + supermarketProductId: product.id, + supermarketName: product.name, + } + ); }} /> )} /> + {picnic && form.picnicProductId && ( + + changeForm({ ...form, picnicProductId: null, picnicName: '(geen Picnic product)' }) + } + /> + )} @@ -199,6 +235,7 @@ export function EditIngredientScreen({ ingredientId, name: form.name, supermarketProductId: form.supermarketProductId, + picnicProductId: form.picnicProductId, isEssential: form.isEssential, tagIds: ingredient.tags.map((tag) => tag.id), }, diff --git a/frontend/screens/ListScreen.js b/frontend/screens/ListScreen.js index cdfa97d6..6dab2b88 100644 --- a/frontend/screens/ListScreen.js +++ b/frontend/screens/ListScreen.js @@ -217,14 +217,30 @@ export default function ListScreen({ navigation }) { {currentOrder.mode && ( - { - e.preventDefault(); - setMode({ variables: { mode: checklistMode ? 'ah' : 'checklist' } }); - }}> - {checklistMode ? 'Naar supermarkt' : 'Naar checklist'} - + + {[ + ['ah', 'AH'], + ['picnic', 'Picnic'], + ['checklist', 'Lijstje'], + ].map(([mode, label]) => ( + { + e.preventDefault(); + if (mode !== currentOrder.mode) { + setMode({ variables: { mode } }); + } + }}> + {label} + + ))} + )} {currentOrder.totalDiscount > 0 && ( @@ -272,7 +288,7 @@ export default function ListScreen({ navigation }) { }, ]} leading={ - checklistMode && ingredient ? ( + (checklistMode || item.store === 'checklist') && ingredient ? ( ) : null } @@ -360,6 +376,11 @@ const styles = StyleSheet.create({ color: Colors.secondaryText, textDecorationLine: 'line-through', }, + storeSwitch: { + flexDirection: 'row', + justifyContent: 'flex-end', + gap: Spacing.md, + }, supermarketDown: { color: Colors.secondaryText, paddingHorizontal: Gutter, diff --git a/lib/picape/checklist.ex b/lib/picape/checklist.ex index 8014241e..e256e3f2 100644 --- a/lib/picape/checklist.ex +++ b/lib/picape/checklist.ex @@ -16,11 +16,13 @@ defmodule Picape.Checklist do @doc """ Ticks an ingredient on the checklist (`checked` true) or unticks it. Only writes while the order reads as a checklist — the mode says so, or the - supermarket is down and the order falls back to it. Ticking a basket the - supermarket owns would record a state nothing reads. + supermarket is down and the order falls back to it. In picnic mode ticking + is always allowed: the items Picnic does not carry live on the checklist, + and a tick on a cart item just marks it bought while shopping. Ticking a + basket the supermarket owns would record a state nothing reads. """ def check(ingredient_id, checked \\ true) do - if Settings.checklist?() or not Supermarket.reachable?() do + if Settings.checklist?() or Settings.picnic?() or not Supermarket.reachable?() do %Item{} |> Item.changeset(%{ingredient_id: ingredient_id, checked: checked}) |> Repo.insert( diff --git a/lib/picape/ingredients.ex b/lib/picape/ingredients.ex index a70652ef..506c0b83 100644 --- a/lib/picape/ingredients.ex +++ b/lib/picape/ingredients.ex @@ -1,8 +1,8 @@ defmodule Picape.Ingredients do import Ecto.Query + require Logger - alias Picape.Repo - alias Picape.Supermarket + alias Picape.{Picnic, Repo, Settings, Supermarket} alias Picape.Recipe.{Ingredient, IngredientTag} @doc """ @@ -103,6 +103,16 @@ defmodule Picape.Ingredients do |> Map.new(fn ingredient -> {ingredient.supermarket_product_id, ingredient} end) end + @doc "The ingredients behind a set of Picnic product ids, keyed by that id. Non-string ids are dropped: checklist rows key items by ingredient id." + def by_picnic_product_ids(picnic_ids) do + result = + from(i in Ingredient, where: i.picnic_product_id in ^Enum.filter(picnic_ids, &is_binary/1)) + |> Repo.all() + |> Map.new(fn ingredient -> {ingredient.picnic_product_id, ingredient} end) + + {:ok, result} + end + def by_supermarket_id(supermarket_id) do Repo.one(from(i in Ingredient, where: i.supermarket_product_id == ^supermarket_id)) end @@ -115,11 +125,44 @@ defmodule Picape.Ingredients do def edit_ingredient(params) do ingredient = Repo.get(Ingredient, params[:ingredient_id]) |> Repo.preload(:tags) - with {:ok, params} <- put_product_raw(params, ingredient) do - ingredient - |> Ingredient.edit_changeset(params) - |> put_tags(params) - |> Repo.update() + with {:ok, params} <- put_product_raw(params, ingredient), + {:ok, edited} <- + ingredient + |> Ingredient.edit_changeset(params) + |> put_tags(params) + |> Repo.update() do + remove_replaced_picnic_product(ingredient, edited) + {:ok, edited} + end + end + + # The Picnic cart is keyed by selling unit id, so a remap leaves the old + # product in it. In picnic mode the old mapping's product comes out; a sync + # adds the new one. + defp remove_replaced_picnic_product(%{picnic_product_id: old}, %{picnic_product_id: new}) + when is_binary(old) and old != new do + if Settings.picnic?() do + case picnic_cart_quantity(old) do + nil -> :ok + quantity -> Picnic.remove_product(old, quantity) + end + end + rescue + error -> Logger.warning("removing the replaced Picnic product failed: #{Exception.message(error)}") + end + + defp remove_replaced_picnic_product(_old, _new), do: :ok + + defp picnic_cart_quantity(product_id) do + Picnic.cart()["items"] + |> Enum.flat_map(& &1["items"]) + |> Enum.find(&(&1["id"] == product_id)) + |> case do + nil -> + nil + + article -> + Enum.find(article["decorators"] || [], &(&1["type"] == "QUANTITY"))["quantity"] end end @@ -137,6 +180,9 @@ defmodule Picape.Ingredients do defp put_product_raw(params, _ingredient), do: {:ok, params} + # A picnic-only ingredient has no supermarket product to fetch. + defp fetch_product_raw(params, nil), do: {:ok, params} + defp fetch_product_raw(params, product_id) do {:ok, Map.put(params, :supermarket_product_raw, Supermarket.products_by_id(product_id))} rescue diff --git a/lib/picape/mcp/tools.ex b/lib/picape/mcp/tools.ex index 1fbe1f99..4216feb6 100644 --- a/lib/picape/mcp/tools.ex +++ b/lib/picape/mcp/tools.ex @@ -7,7 +7,7 @@ defmodule Picape.MCP.Tools do GraphQL API hands out. """ - alias Picape.{Bonus, Checklist, Ingredients, Order, Recipe, Seasonal, Settings, Supermarket} + alias Picape.{Bonus, Checklist, Ingredients, Order, Picnic, Recipe, Seasonal, Settings, Supermarket} # The GraphQL resolvers hardcode the same order id: there is one open order. @order_id "1" @@ -36,28 +36,72 @@ defmodule Picape.MCP.Tools do %{ name: "search_supermarket", description: - "Search the supermarket's product catalogue for products Picape does not know yet. The `id` " <> - "in the result is a supermarket product ID, not a Picape ingredient ID; pass it to add_ingredient.", + "Search the active store's product catalogue for products Picape does not know yet: the " <> + "supermarket's catalogue, or Picnic's in picnic mode (see set_mode). The `id` in the " <> + "result is a store product ID, not a Picape ingredient ID; pass it to add_ingredient.", inputSchema: %{ type: "object", properties: %{query: %{type: "string", description: "Part of a product name, in Dutch"}}, required: ["query"] } }, + %{ + name: "search_picnic", + description: + "Search the Picnic product catalogue for products Picape does not know yet. The `id` " <> + "in the result is a Picnic selling unit id like \"s1016186\", not a Picape ingredient ID; " <> + "pass it to map_ingredient_picnic, together with name, unit_quantity, image_id and price " <> + "so the ingredient keeps them cached. `price` is in cents.", + inputSchema: %{ + type: "object", + properties: %{query: %{type: "string", description: "Part of a product name, in Dutch"}}, + required: ["query"] + } + }, + %{ + name: "map_ingredient_picnic", + description: + "Set or clear the Picnic product behind an ingredient. In picnic mode (see set_mode) an " <> + "ingredient with a Picnic product syncs into the Picnic cart; without one it stays on " <> + "the checklist. Pass `picnic_product_id` null to clear the mapping. Copy `name`, " <> + "`unit_quantity`, `image_id` and `price` from a search_picnic result so the shopping " <> + "list shows them without another lookup. This only writes the mapping; it never places, " <> + "confirms or checks out a Picnic order.", + inputSchema: %{ + type: "object", + properties: %{ + ingredient_id: @integer, + picnic_product_id: %{ + type: ["string", "null"], + description: "The `id` from a search_picnic result, or null to clear" + }, + name: %{type: "string", description: "The product name from the search result"}, + unit_quantity: %{type: "string", description: "The unit size from the search result"}, + image_id: %{type: "string", description: "The image id from the search result"}, + price: %{type: "integer", description: "The price in cents from the search result"} + }, + required: ["ingredient_id", "picnic_product_id"] + } + }, %{ name: "get_shopping_list", description: "Read the current order: every item with its quantity, plus the total item count and price " <> - "in cents. `mode` says where the list lives: 'ah' (the supermarket basket) or 'checklist' " <> - "(Picape's own list — see set_mode). In checklist mode `checked` marks the items ticked " <> - "off and the availability fields keep their defaults. While the supermarket is " <> - "unreachable an 'ah' order is served as the checklist too, with `supermarket_reachable` " <> - "false. Items that map to a Picape ingredient carry that ingredient and the recipes " <> - "that asked for it. `is_orderable` false marks products the supermarket cannot deliver " <> - "right now; `substituted_for` names the ingredient a product replaced. Pass " <> - "`only_unavailable` to get just the problem items. `is_placed` tells you the order was " <> - "paid: Picape then freezes its side until delivery, so set_ingredient_quantity and " <> - "plan_recipe queue without reaching the supermarket.", + "in cents. `mode` says where the list lives: 'ah' (the supermarket basket), 'picnic' " <> + "(the Picnic cart) or 'checklist' (Picape's own list — see set_mode). `store` says per " <> + "item which of the three it comes from; in picnic mode an ingredient without a Picnic " <> + "mapping shows up as a 'checklist' item. In checklist mode `checked` marks the items " <> + "ticked off and the availability fields keep their defaults. While the supermarket is " <> + "unreachable an 'ah' or 'picnic' order is served as the checklist too, with " <> + "`supermarket_reachable` false. Items that map to a Picape ingredient carry that " <> + "ingredient and the recipes that asked for it. `is_orderable` false marks products the " <> + "supermarket cannot deliver right now; `substituted_for` names the ingredient a product " <> + "replaced. Pass `only_unavailable` to get just the problem items. `is_placed` tells you " <> + "the order was paid: Picape then freezes its side until delivery, so " <> + "set_ingredient_quantity and plan_recipe queue without reaching the supermarket. In " <> + "picnic mode `is_placed` stays false: Picape cannot see a Picnic checkout, so after " <> + "checking out in the Picnic app the order is closed by tapping \"Bestelling ontvangen\" " <> + "in Picape (start_shopping, or the button in the app).", inputSchema: %{ type: "object", properties: %{ @@ -93,20 +137,28 @@ defmodule Picape.MCP.Tools do %{ name: "add_ingredient", description: - "Teach Picape a new ingredient, backed by a supermarket product. Find the product with " <> - "search_supermarket first and pass its `id`. Adding an ingredient does not put it on the " <> - "shopping list; use set_ingredient_quantity for that.", + "Teach Picape a new ingredient, backed by a product at one of the stores. Find the product " <> + "with search_supermarket or search_picnic first and pass its `id`; you can pass both. " <> + "Adding an ingredient does not put it on the shopping list; use set_ingredient_quantity " <> + "for that.", inputSchema: %{ type: "object", properties: %{ name: %{type: "string", description: "The name Picape shows, in Dutch"}, supermarket_product_id: %{type: "integer", description: "The `id` from a search_supermarket result"}, + picnic_product_id: %{ + type: "string", + description: "The `id` from a search_picnic result, like \"s1016186\"" + }, + unit_quantity: %{type: "string", description: "The unit size from a search_picnic result"}, + image_id: %{type: "string", description: "The image id from a search_picnic result"}, + price: %{type: "integer", description: "The price in cents from a search_picnic result"}, is_essential: %{ type: "boolean", description: "Essentials are staples you always have; they are left out of recipe totals" } }, - required: ["name", "supermarket_product_id"] + required: ["name"] } }, %{ @@ -298,15 +350,20 @@ defmodule Picape.MCP.Tools do name: "set_mode", description: "Switch where the shopping list lives. 'ah' is the supermarket basket: the app orders from it " <> - "and syncs the plan into it. 'checklist' is a self-managed list inside Picape's own database, " <> - "for when the supermarket API is unreachable: plan_recipe, set_ingredient_quantity and " <> - "get_shopping_list keep working, and items can be ticked off with check_item. Switching back " <> - "to 'ah' pushes the accumulated list into the supermarket basket; if the supermarket is " <> - "still down the switch still happens and the reply says the push failed.", + "and syncs the plan into it. 'picnic' is the Picnic cart: the plan syncs into it for every " <> + "ingredient that has a Picnic product (see map_ingredient_picnic); the rest stay on the " <> + "checklist. Picape never checks out or pays at Picnic — ordering finishes in the Picnic " <> + "app. 'checklist' is a self-managed list inside Picape's own database, for when the " <> + "supermarket API is unreachable: plan_recipe, set_ingredient_quantity and " <> + "get_shopping_list keep working, and items can be ticked off with check_item. Switching " <> + "to 'ah' or 'picnic' pushes the accumulated list into that basket; if it is still down " <> + "the switch still happens and the reply says the push failed. In picnic mode Picape " <> + "never checks out: after checking out in the Picnic app, the order is closed by tapping " <> + "\"Bestelling ontvangen\" in Picape (start_shopping, or the button in the app).", inputSchema: %{ type: "object", properties: %{ - mode: %{type: "string", enum: ["ah", "checklist"]} + mode: %{type: "string", enum: ["ah", "checklist", "picnic"]} }, required: ["mode"] } @@ -315,8 +372,8 @@ defmodule Picape.MCP.Tools do name: "check_item", description: "Tick an item off the checklist, or untick it with checked=false. Works in checklist " <> - "mode, and while the supermarket is unreachable and the order is served as the " <> - "checklist; see set_mode.", + "and picnic mode, and while the supermarket is unreachable and the order is served as " <> + "the checklist; see set_mode.", inputSchema: %{ type: "object", properties: %{ @@ -355,18 +412,55 @@ defmodule Picape.MCP.Tools do end defp run("search_supermarket", args) do + if Settings.picnic?() do + run("search_picnic", args) + else + products = + args["query"] + |> Supermarket.search() + |> Enum.map(&%{id: &1.id, name: &1.name, price: &1.price, unit_quantity: &1.unit_quantity}) + + {:ok, products} + end + end + + defp run("search_picnic", args) do products = args["query"] - |> Supermarket.search() - |> Enum.map(&%{id: &1.id, name: &1.name, price: &1.price, unit_quantity: &1.unit_quantity}) + |> Picnic.search() + |> Enum.map( + &%{ + id: &1.id, + name: &1.name, + price: &1.price, + unit_quantity: &1.unit_quantity, + image_id: &1.image_id + } + ) {:ok, products} end + defp run("map_ingredient_picnic", args) do + with {:ok, ingredient} <- fetch_ingredient(args["ingredient_id"]) do + %{ + ingredient_id: ingredient.id, + picnic_product_id: args["picnic_product_id"], + picnic_product_raw: picnic_raw(args) + } + |> Ingredients.edit_ingredient() + |> case do + {:ok, edited} -> {:ok, List.first(render_ingredients([edited]))} + {:error, reason} -> render_error(reason) + end + end + end + defp run("get_shopping_list", args) do {:ok, line} = Order.current() - {:ok, ingredients} = Recipe.ingredients_by_item_ids(Enum.map(line.items, & &1.id)) - {:ok, recipes} = Order.recipes_planned_for_ingredient_ids(@order_id, Enum.map(Map.values(ingredients), & &1.id)) + {:ok, ingredients} = list_ingredients(line) + ingredient_ids = ingredients |> Map.values() |> Enum.reject(&is_nil/1) |> Enum.map(& &1.id) + {:ok, recipes} = Order.recipes_planned_for_ingredient_ids(@order_id, ingredient_ids) substitutions = Order.substitutions(@order_id) items = @@ -376,11 +470,12 @@ defmodule Picape.MCP.Tools do %{ name: item.name, quantity: item.quantity, + store: item.store, is_orderable: item.is_orderable, availability_label: item.availability_label, substituted_for: get_in(substitutions, [item.id, Access.key(:name)]), checked: item.checked, - ingredient: render_list_ingredient(ingredients[item.id], recipes) + ingredient: render_list_ingredient(ingredients[item.id] || ingredients[item.ingredient_id], recipes) } end) @@ -428,6 +523,8 @@ defmodule Picape.MCP.Tools do %{ name: args["name"], supermarket_product_id: args["supermarket_product_id"], + picnic_product_id: args["picnic_product_id"], + picnic_product_raw: picnic_raw(args), is_essential: args["is_essential"] || false } |> Ingredients.add_ingredient() @@ -607,6 +704,35 @@ defmodule Picape.MCP.Tools do end end + # Maps each cart row's id to the ingredient behind it. In picnic mode cart + # rows are keyed by selling unit id and checklist rows by ingredient id, so + # both lookups run and the maps merge — the two key spaces never collide. + defp list_ingredients(line) do + if Settings.picnic?() do + {:ok, by_product} = Ingredients.by_picnic_product_ids(Enum.map(line.items, & &1.id)) + ingredient_ids = line.items |> Enum.map(& &1.ingredient_id) |> Enum.reject(&is_nil/1) + {:ok, by_id} = Ingredients.ingredients_by_ids(ingredient_ids) + + {:ok, Map.merge(by_product, by_id)} + else + Recipe.ingredients_by_item_ids(Enum.map(line.items, & &1.id)) + end + end + + defp picnic_raw(%{"picnic_product_id" => nil}), do: nil + + defp picnic_raw(args) do + %{ + "id" => args["picnic_product_id"], + "name" => args["name"], + "unit_quantity" => args["unit_quantity"], + "image_id" => args["image_id"], + "display_price" => args["price"] + } + |> Enum.reject(fn {_key, value} -> is_nil(value) end) + |> Map.new() + end + defp title_matches?(recipe, query) do String.contains?(String.downcase(recipe.title), String.downcase(query)) end @@ -620,6 +746,7 @@ defmodule Picape.MCP.Tools do name: ingredient.name, is_essential: ingredient.is_essential, supermarket_product_id: ingredient.supermarket_product_id, + picnic_product_id: ingredient.picnic_product_id, replacement_ingredient_id: ingredient.replacement_ingredient_id, unit_quantity: ingredient[:unit_quantity], nutriscore: ingredient[:nutriscore], @@ -637,7 +764,12 @@ defmodule Picape.MCP.Tools do %{quantity: ref.quantity, recipe_id: ref.recipe.id, title: ref.recipe.title} end) - %{id: ingredient.id, name: ingredient.name, planned_recipes: planned} + %{ + id: ingredient.id, + name: ingredient.name, + picnic_product_id: ingredient.picnic_product_id, + planned_recipes: planned + } end defp render_recipes(recipes) do diff --git a/lib/picape/order.ex b/lib/picape/order.ex index 351af474..5e7606a1 100644 --- a/lib/picape/order.ex +++ b/lib/picape/order.ex @@ -6,6 +6,7 @@ defmodule Picape.Order do Line, Item, LineFromSupermarket, + LineFromPicnic, LineFromDb, PlannedRecipe, ManualIngredient, @@ -13,28 +14,39 @@ defmodule Picape.Order do Sync } - alias Picape.{Repo, Supermarket, Recipe, Shopping, Ingredients, Settings, Checklist} + alias Picape.{Repo, Supermarket, Picnic, Recipe, Shopping, Ingredients, Settings, Checklist} defmodule(Product, do: defstruct([:id, :quantity])) @doc """ Returns the currently active cart. In checklist mode that is the list Picape computed, with the ticked-off state overlaid — no supermarket call happens. - An `ah` order whose supermarket does not answer is served the same way, - flagged `supermarket_reachable: false`, so a dead API does not take the - list down with it. + In picnic mode it is the Picnic cart plus the planned items that have no + Picnic mapping, which stay on the checklist. An `ah` or `picnic` order whose + supermarket does not answer is served the same way, flagged + `supermarket_reachable: false`, so a dead API does not take the list down + with it. """ def current() do - if Settings.checklist?() do - {:ok, cart} = cart("1") - {:ok, checklist_line(LineFromDb.convert(cart))} - else - try do - line = LineFromSupermarket.convert(Supermarket.cart()) - {:ok, %{line | is_placed: order_placed?(), supermarket_reachable: true}} - rescue - error -> fallback_line(error) - end + cond do + Settings.checklist?() -> + {:ok, cart} = cart("1") + {:ok, checklist_line(LineFromDb.convert(cart))} + + Settings.picnic?() -> + try do + {:ok, picnic_line(Picnic.cart())} + rescue + error -> fallback_line(error) + end + + true -> + try do + line = LineFromSupermarket.convert(Supermarket.cart()) + {:ok, %{line | is_placed: order_placed?(), supermarket_reachable: true}} + rescue + error -> fallback_line(error) + end end end @@ -189,6 +201,9 @@ defmodule Picape.Order do Settings.checklist?() -> current() + Settings.picnic?() -> + sync_picnic(order_id) + order_placed?() -> archive_placed_order(order_id) current() @@ -210,16 +225,17 @@ defmodule Picape.Order do end @doc """ - Switches between the supermarket basket ("ah") and Picape's own checklist - ("checklist"). Switching back to "ah" pushes the list that accumulated while - the supermarket was away into the basket; a supermarket that is still - unreachable does not block the switch, the next sync retries. + Switches where the current order lives: the supermarket basket ("ah"), the + Picnic cart ("picnic") or Picape's own checklist ("checklist"). Switching to + "ah" or "picnic" pushes the list that accumulated while the supermarket was + away into that basket; a supermarket that is still unreachable does not + block the switch, the next sync retries. """ - def set_mode(mode) when mode in ["ah", "checklist"] do - was_checklist = Settings.checklist?() + def set_mode(mode) when mode in ["ah", "checklist", "picnic"] do + previous = Settings.mode() {:ok, _} = Settings.set("mode", mode) - if mode == "ah" and was_checklist do + if mode != previous and mode in ["ah", "picnic"] do try do {:ok, line} = sync_supermarket("1") @@ -272,7 +288,7 @@ defmodule Picape.Order do def ingredients_ordered_quantity(_order_id, ingredient_ids) do with {:ok, line} <- current(), {:ok, items} <- ordered_item_quantities(line), - {:ok, items_map} <- Recipe.ingredients_by_item_ids_reverse(Map.keys(items)) do + {:ok, items_map} <- item_ingredient_ids(Map.keys(items)) do {:ok, Map.new(ingredient_ids, fn id -> {id, items[items_map[id]] || 0} end)} end end @@ -468,6 +484,154 @@ defmodule Picape.Order do # --- private + # The Picnic cart plus the planned ingredients that have no Picnic mapping, + # which fall back to the checklist. Products added in the Picnic app itself + # carry no ingredient, like the supermarket's external items. + defp picnic_line(cart) do + line = LineFromPicnic.convert(cart) + {:ok, by_product} = Ingredients.by_picnic_product_ids(Enum.map(line.items, & &1.id)) + {:ok, db_cart} = cart("1") + checked = Checklist.checked_ids() + + unmapped = + db_cart + |> Map.values() + |> Enum.filter(&is_nil(&1.ingredient.picnic_product_id)) + |> Enum.map(&LineFromDb.convert_item/1) + + items = + Enum.map(line.items, fn item -> + %{item | ingredient_id: get_in(by_product, [item.id, Access.key(:id)])} + end) + + items = Enum.map(items ++ unmapped, &%{&1 | checked: MapSet.member?(checked, &1.ingredient_id)}) + + %{ + line + | items: items, + total_count: line.total_count + length(unmapped), + supermarket_reachable: true + } + end + + # Pushes what the plan wants into the Picnic cart. Only the Picnic cart rows + # (`store == "picnic"`) count as existing; checklist items and products the + # Picnic app added itself are left alone — the diff only names mapped ids. + defp sync_picnic(order_id) do + try do + {:ok, wanted} = planned_picnic_quantities(order_id) + {:ok, manual} = manual_ingredient_quantities(order_id) + {:ok, manual_by_id} = Ingredients.ingredients_by_ids(Map.keys(manual)) + # The cached cart can be five hours old; the diff is only as correct as + # the cart it is computed against, so sync reads a fresh one. + Picnic.invalidate_cart() + {:ok, line} = current() + + # A manual row wins over the plan, including quantity 0: it takes the + # product out of the Picnic cart the same way it empties the AH basket. + manual = + for {ingredient_id, quantity} <- manual, + ingredient = manual_by_id[ingredient_id], + not is_nil(ingredient) and not is_nil(ingredient.picnic_product_id), + into: %{}, + do: {ingredient.picnic_product_id, quantity} + + existing = picnic_quantities(line) + + with {:ok, changes} <- Sync.changes(wanted, manual, existing) do + push_picnic(changes, existing, line) + end + rescue + error -> Logger.warning("syncing the Picnic cart failed: #{Exception.message(error)}") + end + + current() + end + + # What the plan wants in the Picnic cart, keyed by selling unit id. Keyed on + # the ingredient, not the AH product id, so a picnic-only ingredient syncs too. + # Unplanned recipes come back at quantity 0, the same way + # recipe_ingredient_quantities/1 works: a sync after an unplan then removes + # the products instead of leaving them in the cart. + defp planned_picnic_quantities(order_id) do + query = + from( + p in PlannedRecipe, + join: r in Recipe.IngredientRef, + on: r.recipe_id == p.recipe_id, + join: i in assoc(r, :ingredient), + where: + p.line_id == ^order_id and i.is_essential == false and + not is_nil(i.picnic_product_id), + select: {i.picnic_product_id, fragment("? * ? * Cast(NOT ? as integer)", p.quantity, r.quantity, p.unplanned)} + ) + + wanted = + query + |> Repo.all() + |> Enum.reduce(%{}, fn {product_id, quantity}, acc -> + Map.update(acc, product_id, quantity, &(&1 + quantity)) + end) + + {:ok, wanted} + end + + defp manual_ingredient_quantities(order_id) do + query = + from( + m in ManualIngredient, + where: m.line_id == ^order_id, + select: {m.ingredient_id, m.quantity} + ) + + {:ok, Enum.into(Repo.all(query), %{})} + end + + # The cart can carry the same selling unit on two ORDER_LINE groups, so + # quantities sum per product id instead of the later row overwriting the + # earlier one. + defp picnic_quantities(line) do + Enum.reduce(line.items, %{}, fn + %{store: "picnic"} = item, acc -> + Map.update(acc, item.id, item.quantity, &(&1 + item.quantity)) + + _item, acc -> + acc + end) + end + + # A line served from the fallback produced no changes to push, and a dead + # Picnic answers none. The plan rows are already written, so the next sync + # that reaches Picnic pushes them. + defp push_picnic(_changes, _existing, %{supermarket_reachable: false}), do: :ok + + defp push_picnic(changes, existing, _line) do + Picnic.apply_changes(changes, existing) + rescue + error -> Logger.warning("pushing the list to Picnic failed: #{Exception.message(error)}") + end + + # The cart rows carry different keys per mode: a supermarket product id in + # ah, a Picnic selling unit id for cart rows in picnic, and a supermarket + # product id again for the checklist rows picnic mode falls back to. Returns + # `ingredient_id => item id`. + defp item_ingredient_ids(item_ids) do + if Settings.picnic?() do + {:ok, by_item} = Recipe.ingredients_by_item_ids_reverse(Enum.filter(item_ids, &is_integer/1)) + {:ok, by_product} = Ingredients.by_picnic_product_ids(item_ids) + + items_map = + Map.merge( + by_item, + Map.new(by_product, fn {product_id, ingredient} -> {ingredient.id, product_id} end) + ) + + {:ok, items_map} + else + Recipe.ingredients_by_item_ids_reverse(item_ids) + end + end + defp checklist_line(line) do checked = Checklist.checked_ids() @@ -602,8 +766,14 @@ defmodule Picape.Order do # In checklist mode or with the supermarket down there is no basket to # snapshot; the plan rows alone record the order then, like before snapshots. + # A picnic order keeps its plan rows too: `order_item.product_id` is numeric + # and Picnic's selling unit ids are strings, so they cannot be stored yet. defp supermarket_items() do - Supermarket.cart()["items"] || [] + if Settings.picnic?() do + [] + else + Supermarket.cart()["items"] || [] + end rescue _ -> [] end diff --git a/lib/picape/order/item.ex b/lib/picape/order/item.ex index 5460250b..e3344a9e 100644 --- a/lib/picape/order/item.ex +++ b/lib/picape/order/item.ex @@ -11,6 +11,7 @@ defmodule Picape.Order.Item do field(:is_orderable, :boolean, default: true, virtual: true) field(:availability_label, :string, virtual: true) field(:checked, :boolean, virtual: true, default: false) + field(:store, :string, virtual: true) field(:recipe_ids, {:array, :integer}) field(:line_id, :string) field(:ingredient_id, :id) diff --git a/lib/picape/order/line_from_db.ex b/lib/picape/order/line_from_db.ex index 03d63ce8..681e3a24 100644 --- a/lib/picape/order/line_from_db.ex +++ b/lib/picape/order/line_from_db.ex @@ -32,7 +32,8 @@ defmodule Picape.Order.LineFromDb do name: item.ingredient.name, image_url: Supermarket.image_url(item.ingredient.supermarket_product_raw), quantity: item.quantity, - ingredient_id: item.ingredient.id + ingredient_id: item.ingredient.id, + store: "checklist" } end end diff --git a/lib/picape/order/line_from_picnic.ex b/lib/picape/order/line_from_picnic.ex new file mode 100644 index 00000000..de32c7cd --- /dev/null +++ b/lib/picape/order/line_from_picnic.ex @@ -0,0 +1,44 @@ +defmodule Picape.Order.LineFromPicnic do + @moduledoc """ + Converts the Picnic cart into an order line. The cart's `items` are + ORDER_LINE groups that each hold ORDER_ARTICLEs — flattened into items + whose `id` is the Picnic selling unit id, like `s1002987`. + """ + alias Picape.Order.{Line, Item} + alias Picape.Picnic + + def convert(%{"items" => groups} = cart) when is_list(groups) do + items = groups |> Enum.flat_map(&(&1["items"] || [])) |> Enum.map(&convert_item/1) + + %Line{ + id: 1, + items: items, + total_count: cart["total_count"] || Enum.count(items), + total_price: cart["total_price"] || 0, + total_discount: 0, + is_placed: false + } + end + + def convert(_cart) do + %Line{id: 1, items: [], total_count: 0, total_price: 0, total_discount: 0, is_placed: false} + end + + defp convert_item(item = %{}) do + %Item{ + id: item["id"], + name: item["name"], + image_url: Picnic.image_url(List.first(item["image_ids"] || [])), + quantity: quantity(item), + store: "picnic" + } + end + + # The article's quantity sits in a QUANTITY decorator, the same spot the + # pre-v15 API kept it. + defp quantity(item) do + Enum.find(item["decorators"] || [], %{"quantity" => 0}, fn dec -> dec["type"] == "QUANTITY" end)[ + "quantity" + ] + end +end diff --git a/lib/picape/order/line_from_supermarket.ex b/lib/picape/order/line_from_supermarket.ex index 2b80afa5..bae1b183 100644 --- a/lib/picape/order/line_from_supermarket.ex +++ b/lib/picape/order/line_from_supermarket.ex @@ -56,7 +56,8 @@ defmodule Picape.Order.LineFromSupermarket do image_url: Supermarket.image_url(product), quantity: item["quantity"], is_orderable: orderable?(availability), - availability_label: availability["availabilityLabel"] + availability_label: availability["availabilityLabel"], + store: "ah" } end diff --git a/lib/picape/picnic.ex b/lib/picape/picnic.ex new file mode 100644 index 00000000..bb774e1d --- /dev/null +++ b/lib/picape/picnic.ex @@ -0,0 +1,189 @@ +defmodule Picape.Picnic do + @moduledoc """ + HTTP client for Picnic's `api/15` endpoints. Covers only what picnic mode + needs: search, the cart, and adding or removing products in it. + + There is no checkout, payment or delivery-slot endpoint here on purpose. + Orders are always finished in the Picnic app itself; Picape only keeps the + cart in step with the plan. + + Auth is an auth key sent as the `x-picnic-auth` header on every request. + The key is the one the Picnic app's own session carries; it is long-lived + and the storefront api never refreshes it. It is configured with + `PICNIC_AUTH_KEY`, the same way the supermarket's secrets come from env + vars. + """ + use HTTPoison.Base + + alias Picape.Picnic.SearchResult + + @default_base_url "https://storefront-prod.nl.picnicinternational.com/api/15" + @default_agent "30100;1.15.77-10293" + + def search(""), do: [] + + def search(query) do + auth_key!() + + get!("/pages/search-page-results?#{URI.encode_query(%{"search_term" => query})}").body + |> SearchResult.from_result() + end + + def cart() do + auth_key!() + + ConCache.get_or_store(:supermarket, :picnic_cart, fn -> + get!("/cart").body + end) + end + + @doc """ + Adds `count` of a selling unit to the cart. The answer is the whole cart, + so it refreshes the cached copy instead of needing another read. + """ + def add_product(product_id, count \\ 1) do + %{"product_id" => product_id, "count" => count} + |> post_cart("/cart/add_product") + end + + @doc "Removes `count` of a selling unit from the cart." + def remove_product(product_id, count \\ 1) do + %{"product_id" => product_id, "count" => count} + |> post_cart("/cart/remove_product") + end + + @doc """ + Pushes an `Order.Sync.Changes` diff into the Picnic cart. `existing` maps + each Picnic product id to its current cart quantity: Picnic's mutations are + deltas, not absolute quantities, so each change becomes an add or remove of + the difference. Products in the cart that the diff does not name are left + alone. + """ + def apply_changes(changes, existing) do + Enum.each(changes.remove, fn %{id: id, quantity: quantity} -> + remove_product(id, (existing[id] || 0) - quantity) + end) + + Enum.each(changes.add, fn %{id: id, quantity: quantity} -> + add_product(id, quantity - (existing[id] || 0)) + end) + + {:ok, :synced} + end + + def invalidate_cart() do + ConCache.delete(:supermarket, :picnic_cart) + end + + def image_url(image_id) when is_binary(image_id) do + static_base_url() <> "/static/images/" <> image_id <> "/small.png" + end + + def image_url(_), do: "http://placekitten.com/64/64" + + # --- + + defp post_cart(body, path) do + auth_key!() + cart = post!(path, body, "Content-Type": "application/json").body + ConCache.put(:supermarket, :picnic_cart, cart) + cart + end + + defp static_base_url() do + (config(:base_url) || @default_base_url) |> String.replace(~r|/api/.*$|, "") + end + + def process_request_url(url) do + (config(:base_url) || @default_base_url) <> url + end + + # Picnic answers some mutations with an empty 200. + def process_response_body(""), do: %{} + + def process_response_body(body) do + case Poison.decode(body) do + {:ok, value} -> value + _ -> body + end + end + + def process_response(%HTTPoison.Response{body: body, status_code: status_code} = response) do + cond do + is_binary(body) -> + raise Picape.Supermarket.Error, + message: + "Picnic answered HTTP #{status_code} with a non-JSON body: " <> + String.slice(body, 0, 200) + + status_code not in 200..299 -> + raise Picape.Supermarket.Error, + message: "Picnic answered HTTP #{status_code}: " <> String.slice(inspect(body), 0, 200) + + is_map(body) and Map.has_key?(body, "error") -> + raise Picape.Supermarket.Error, + message: "Picnic answered an error: " <> String.slice(inspect(body["error"]), 0, 200) + + true -> + response + end + end + + def process_request_headers(headers) do + headers + |> Keyword.put_new(:Accept, "*/*") + |> Keyword.put_new(:"Accept-Language", "nl-NL") + |> Keyword.put_new(:"User-Agent", config(:user_agent) || "Picape") + |> Keyword.put_new(:"x-picnic-agent", config(:agent) || @default_agent) + |> Keyword.put_new(:"x-picnic-did", config(:did) || default_did()) + |> Keyword.put_new(:"x-picnic-country", "NL") + |> put_auth_key() + end + + defp put_auth_key(headers) do + if auth_key = config(:auth_key) do + Keyword.put(headers, :"x-picnic-auth", auth_key) + else + headers + end + end + + defp auth_key!() do + config(:auth_key) || + raise(Picape.Supermarket.Error, + message: "the Picnic auth key is not configured; set PICNIC_AUTH_KEY" + ) + end + + # The device id identifies this installation to Picnic, the way the app's own + # does. It is generated once per boot so a caller that does not configure one + # still sends a stable value. + defp default_did() do + case :persistent_term.get({__MODULE__, :did}, nil) do + nil -> + did = Ecto.UUID.generate() + :persistent_term.put({__MODULE__, :did}, did) + did + + did -> + did + end + end + + def process_request_body(""), do: "" + + def process_request_body(body) do + Poison.encode!(body) + end + + def process_request_options(options) do + Keyword.merge(options, hackney: config(:hackney) || []) + end + + defp config(key) do + case Application.get_env(:picape, __MODULE__, [])[key] do + "" -> nil + value -> value + end + end +end diff --git a/lib/picape/picnic/search_result.ex b/lib/picape/picnic/search_result.ex new file mode 100644 index 00000000..89fc3ebf --- /dev/null +++ b/lib/picape/picnic/search_result.ex @@ -0,0 +1,49 @@ +defmodule Picape.Picnic.SearchResult do + @moduledoc """ + One `sellingUnit` from a Picnic search page, normalised to the small shape + the tools and the ingredient cache read. `price` is `display_price`, cents. + """ + + defstruct [:id, :name, :price, :unit_quantity, :image_id, :max_count] + + alias Picape.Picnic.SearchResult + + def from_result(page) when is_map(page) do + page |> selling_units() |> Enum.map(&convert/1) + end + + def from_result(_), do: [] + + # Every `sellingUnit` value anywhere in the page tree — the JSONPath + # `$..sellingUnit` the other Picnic clients extract. + defp selling_units(node) when is_map(node) do + Enum.flat_map(node, fn + {"sellingUnit", %{} = unit} -> [unit | selling_units(unit)] + {"sellingUnit", _} -> [] + {_key, value} -> selling_units(value) + end) + end + + defp selling_units(list) when is_list(list), do: Enum.flat_map(list, &selling_units/1) + + defp selling_units(_), do: [] + + defp convert(unit = %{}) do + %SearchResult{ + id: unit["id"], + name: unit["name"], + price: unit["display_price"] || price_range(unit["price_ranges"]), + unit_quantity: unit["unit_quantity"], + image_id: unit["image_id"], + max_count: unit["max_count"] + } + end + + # Promotional tiles carry price_ranges instead of display_price: a list of + # {price, from_quantity} tiers. The earliest tier is the per-piece price. + defp price_range([_ | _] = ranges) do + ranges |> Enum.min_by(&(&1["from_quantity"] || 0)) |> Map.get("price") + end + + defp price_range(_), do: nil +end diff --git a/lib/picape/recipe/ingredient.ex b/lib/picape/recipe/ingredient.ex index c2f5a38e..9917d607 100644 --- a/lib/picape/recipe/ingredient.ex +++ b/lib/picape/recipe/ingredient.ex @@ -11,6 +11,8 @@ defmodule Picape.Recipe.Ingredient do field(:seasonal_name, :string) field(:supermarket_product_id, :integer) field(:supermarket_product_raw, :map) + field(:picnic_product_id, :string) + field(:picnic_product_raw, :map) belongs_to(:replacement, Picape.Recipe.Ingredient, foreign_key: :replacement_ingredient_id) @@ -127,10 +129,14 @@ defmodule Picape.Recipe.Ingredient do :is_essential, :supermarket_product_id, :supermarket_product_raw, + :picnic_product_id, + :picnic_product_raw, :replacement_ingredient_id ]) |> validate_required([:name, :is_essential]) + |> validate_format(:picnic_product_id, ~r/^s\d+$/) |> unique_constraint(:supermarket_product_id) + |> unique_constraint(:picnic_product_id, name: :recipe_ingredient_picnic_selling_unit_index) end @doc false @@ -141,10 +147,25 @@ defmodule Picape.Recipe.Ingredient do :is_essential, :supermarket_product_id, :supermarket_product_raw, + :picnic_product_id, + :picnic_product_raw, :replacement_ingredient_id ]) - |> validate_required([:name, :is_essential, :supermarket_product_id]) + |> validate_required([:name, :is_essential]) + |> validate_product_id() + |> validate_format(:picnic_product_id, ~r/^s\d+$/) |> unique_constraint(:supermarket_product_id) + |> unique_constraint(:picnic_product_id, name: :recipe_ingredient_picnic_selling_unit_index) + end + + # An ingredient needs a product at one of the stores or it can never be + # ordered. + defp validate_product_id(changeset) do + if get_field(changeset, :supermarket_product_id) || get_field(changeset, :picnic_product_id) do + changeset + else + add_error(changeset, :supermarket_product_id, "or a Picnic product id is required") + end end def raw_changeset(%Ingredient{} = ingredient, attrs) do diff --git a/lib/picape/settings.ex b/lib/picape/settings.ex index c5879a72..52c422c2 100644 --- a/lib/picape/settings.ex +++ b/lib/picape/settings.ex @@ -2,7 +2,8 @@ defmodule Picape.Settings do @moduledoc """ Key-value settings that live in the database so they can change at runtime. Currently holds only `mode`: `"ah"` syncs the plan into the supermarket - basket, `"checklist"` keeps it as Picape's own shopping list instead. + basket, `"picnic"` syncs it into the Picnic cart, and `"checklist"` keeps it + as Picape's own shopping list instead. """ alias Picape.Repo @@ -21,8 +22,10 @@ defmodule Picape.Settings do |> Repo.insert(on_conflict: [set: [value: value]], conflict_target: :key) end - @doc "The current shopping mode: ah syncs into the supermarket basket, checklist keeps the list in Picape." + @doc "The current shopping mode: ah or picnic sync into that store's basket, checklist keeps the list in Picape." def mode(), do: get("mode") || "ah" def checklist?(), do: mode() == "checklist" + + def picnic?(), do: mode() == "picnic" end diff --git a/lib/picape_web/graphql/resolver/order.ex b/lib/picape_web/graphql/resolver/order.ex index ac3302ec..bd4fc1c1 100644 --- a/lib/picape_web/graphql/resolver/order.ex +++ b/lib/picape_web/graphql/resolver/order.ex @@ -128,7 +128,7 @@ defmodule PicapeWeb.Graphql.Resolver.Order do def set_mode(attributes, _info) do case Order.set_mode(attributes[:mode]) do {:ok, %{pushed_to_supermarket: false, error: error}} -> - {:error, "switched to 'ah' but pushing the list to the supermarket failed: #{error}"} + {:error, "switched to '#{attributes[:mode]}' but pushing the list to the supermarket failed: #{error}"} {:ok, _result} -> Order.current() diff --git a/lib/picape_web/graphql/resolver/recipe.ex b/lib/picape_web/graphql/resolver/recipe.ex index 2b516981..e011513e 100644 --- a/lib/picape_web/graphql/resolver/recipe.ex +++ b/lib/picape_web/graphql/resolver/recipe.ex @@ -1,5 +1,5 @@ defmodule PicapeWeb.Graphql.Resolver.Recipe do - alias Picape.{Recipe, Ingredients, Repo} + alias Picape.{Recipe, Ingredients, Repo, Settings} alias Absinthe.Relay # Queries @@ -58,8 +58,18 @@ defmodule PicapeWeb.Graphql.Resolver.Recipe do Recipe.recipes_by_ids(ids) end + # Item ids are keyed per store: a supermarket product id in ah and checklist + # mode, a Picnic selling unit id for cart rows in picnic mode. The two key + # spaces never collide. def ingredients_by_item_ids(_, item_ids) do - Recipe.ingredients_by_item_ids(item_ids) + if Settings.picnic?() do + {:ok, by_product} = Recipe.ingredients_by_item_ids(Enum.filter(item_ids, &is_integer/1)) + {:ok, by_picnic} = Ingredients.by_picnic_product_ids(item_ids) + + {:ok, Map.merge(by_product, by_picnic)} + else + Recipe.ingredients_by_item_ids(item_ids) + end end def ingredients_by_recipe_ids(_, recipe_ids) do diff --git a/lib/picape_web/graphql/resolver/supermarket.ex b/lib/picape_web/graphql/resolver/supermarket.ex index d1d243e4..6fc2bb1d 100644 --- a/lib/picape_web/graphql/resolver/supermarket.ex +++ b/lib/picape_web/graphql/resolver/supermarket.ex @@ -1,9 +1,30 @@ defmodule PicapeWeb.Graphql.Resolver.Supermarket do - alias Picape.Supermarket + alias Picape.{Picnic, Supermarket} def search(_parent, attributes, _info) do {:ok, Supermarket.search(attributes[:query])} rescue _ -> {:error, "the supermarket is unreachable"} end + + # Picnic sells in "selling units" with s-prefixed ids; the search result type + # is shared, with the image built from the image_id the tile carries. + def search_picnic(_parent, attributes, _info) do + results = + attributes[:query] + |> Picnic.search() + |> Enum.map( + &%{ + id: &1.id, + name: &1.name, + price: &1.price, + unit_quantity: &1.unit_quantity, + image_url: Picnic.image_url(&1.image_id) + } + ) + + {:ok, results} + rescue + _ -> {:error, "the supermarket is unreachable"} + end end diff --git a/lib/picape_web/graphql/schema.ex b/lib/picape_web/graphql/schema.ex index 78e900a8..fe2aef41 100644 --- a/lib/picape_web/graphql/schema.ex +++ b/lib/picape_web/graphql/schema.ex @@ -95,6 +95,12 @@ defmodule PicapeWeb.Graphql.Schema do resolve(&Resolver.Supermarket.search/3) end + @desc "Search Picnic products using a query string." + field :search_picnic, list_of(:supermarket_search_result) do + arg(:query, non_null(:string)) + resolve(&Resolver.Supermarket.search_picnic/3) + end + @desc """ Search ingredients using a query string, excluding of ingredient ids possible. @@ -148,14 +154,14 @@ defmodule PicapeWeb.Graphql.Schema do resolve(handle_errors(&Resolver.Order.stop_shopping/2)) end - @desc "Tick an item off the checklist, or untick it. Checklist mode only." + @desc "Tick an item off the checklist, or untick it. Checklist and picnic mode only." field :check_item, :order do arg(:ingredient_id, non_null(:id)) arg(:checked, :boolean, default_value: true) resolve(handle_errors(&Resolver.Order.check_item/2)) end - @desc "Switch where the current order lives: the supermarket basket (ah) or Picape's own checklist." + @desc "Switch where the current order lives: the supermarket basket (ah), the Picnic cart (picnic) or Picape's own checklist." field :set_mode, :order do arg(:mode, non_null(:string)) resolve(handle_errors(&Resolver.Order.set_mode/2)) @@ -184,11 +190,12 @@ defmodule PicapeWeb.Graphql.Schema do resolve(handle_errors(&Resolver.Bonus.activate/2)) end - @desc "Add a new ingredient." + @desc "Add a new ingredient, backed by a supermarket product, a Picnic product, or both." field :add_ingredient, :ingredient do arg(:name, non_null(:string)) arg(:is_essential, non_null(:boolean)) - arg(:supermarket_product_id, non_null(:string)) + arg(:supermarket_product_id, :string) + arg(:picnic_product_id, :string) resolve(handle_errors(&Resolver.Recipe.add_ingredient/3)) end diff --git a/lib/picape_web/graphql/types.ex b/lib/picape_web/graphql/types.ex index 0a99ef36..ca514759 100644 --- a/lib/picape_web/graphql/types.ex +++ b/lib/picape_web/graphql/types.ex @@ -20,7 +20,7 @@ defmodule PicapeWeb.Graphql.Types do @desc "False while the supermarket does not answer and this order is served as the checklist instead. Only set while the order lives in the supermarket basket." field(:supermarket_reachable, :boolean) - @desc "Where the order lives: the supermarket basket or Picape's own checklist." + @desc "Where the order lives: the supermarket basket, the Picnic cart or Picape's own checklist." field(:mode, :string, resolve: fn _parent, _args, _ctx -> {:ok, Picape.Settings.mode()} end) @desc "When the order closed. Only set on previous orders." @@ -51,9 +51,12 @@ defmodule PicapeWeb.Graphql.Types do @desc "The name of the ingredient this product stands in for, when it is a replacement." field(:substituted_for, :string, resolve: batched({Resolver.Order, :substitutions_for_items})) - @desc "Ticked off the checklist. Only set in checklist mode." + @desc "Ticked off the checklist. Only set in checklist and picnic mode." field(:checked, :boolean) + @desc "Where the item lives: the supermarket basket (ah), the Picnic cart (picnic) or Picape's own checklist." + field(:store, :string) + field( :ingredient, :ingredient, @@ -93,6 +96,23 @@ defmodule PicapeWeb.Graphql.Types do field(:name, :string) field(:seasonal_name, :string) field(:supermarket_product_id, :string) + field(:picnic_product_id, :string) + + @desc "The Picnic product's name, cached when the mapping was made." + field :picnic_name, :string do + resolve(fn parent, _args, _ctx -> + {:ok, get_in(parent.picnic_product_raw || %{}, ["name"])} + end) + end + + @desc "The Picnic product's image, built from the image id cached at mapping time." + field :picnic_image_url, :string do + resolve(fn parent, _args, _ctx -> + image_id = get_in(parent.picnic_product_raw || %{}, ["image_id"]) + {:ok, image_id && Picape.Picnic.image_url(image_id)} + end) + end + field(:is_essential, :boolean) field(:tags, list_of(:ingredient_tag)) field(:image_url, :string, resolve: from_object(:image_url)) @@ -217,7 +237,8 @@ defmodule PicapeWeb.Graphql.Types do @desc "Edit an ingredient" input_object :edit_ingredient_input do field(:ingredient_id, non_null(:id)) - field(:supermarket_product_id, non_null(:string)) + field(:supermarket_product_id, :string) + field(:picnic_product_id, :string) field(:name, non_null(:string)) field(:seasonal_name, :string) field(:is_essential, non_null(:boolean)) diff --git a/priv/graphql/schema.graphql b/priv/graphql/schema.graphql index ec05e460..0cd91c74 100644 --- a/priv/graphql/schema.graphql +++ b/priv/graphql/schema.graphql @@ -46,6 +46,9 @@ type RootQueryType { "Search Supermarket products using a query string." searchSupermarket(query: String!): [SupermarketSearchResult] + "Search Picnic products using a query string." + searchPicnic(query: String!): [SupermarketSearchResult] + """ Search ingredients using a query string, excluding of ingredient ids possible. @@ -75,10 +78,10 @@ type RootMutationType { "Stops shopping" stopShopping: Order - "Tick an item off the checklist, or untick it. Checklist mode only." + "Tick an item off the checklist, or untick it. Checklist and picnic mode only." checkItem(ingredientId: ID!, checked: Boolean): Order - "Switch where the current order lives: the supermarket basket (ah) or Picape's own checklist." + "Switch where the current order lives: the supermarket basket (ah), the Picnic cart (picnic) or Picape's own checklist." setMode(mode: String!): Order "Buy ingredient" @@ -93,8 +96,8 @@ type RootMutationType { """ activateBonusOffer(offerId: String!): Bonus - "Add a new ingredient." - addIngredient(name: String!, isEssential: Boolean!, supermarketProductId: String!): Ingredient + "Add a new ingredient, backed by a supermarket product, a Picnic product, or both." + addIngredient(name: String!, isEssential: Boolean!, supermarketProductId: String, picnicProductId: String): Ingredient "Edit an new ingredient." editIngredient(input: EditIngredientInput!): Ingredient @@ -146,7 +149,7 @@ type Order implements Node { "False while the supermarket does not answer and this order is served as the checklist instead. Only set while the order lives in the supermarket basket." supermarketReachable: Boolean - "Where the order lives: the supermarket basket or Picape's own checklist." + "Where the order lives: the supermarket basket, the Picnic cart or Picape's own checklist." mode: String "When the order closed. Only set on previous orders." @@ -176,9 +179,12 @@ type OrderItem implements Node { "The name of the ingredient this product stands in for, when it is a replacement." substitutedFor: String - "Ticked off the checklist. Only set in checklist mode." + "Ticked off the checklist. Only set in checklist and picnic mode." checked: Boolean + "Where the item lives: the supermarket basket (ah), the Picnic cart (picnic) or Picape's own checklist." + store: String + ingredient: Ingredient } @@ -212,6 +218,14 @@ type Ingredient implements Node { supermarketProductId: String + picnicProductId: String + + "The Picnic product's name, cached when the mapping was made." + picnicName: String + + "The Picnic product's image, built from the image id cached at mapping time." + picnicImageUrl: String + isEssential: Boolean tags: [IngredientTag] @@ -304,7 +318,8 @@ enum OrderDirection { "Edit an ingredient" input EditIngredientInput { ingredientId: ID! - supermarketProductId: String! + supermarketProductId: String + picnicProductId: String name: String! seasonalName: String isEssential: Boolean! diff --git a/priv/repo/migrations/20261018120000_add_ingredient_picnic_product.exs b/priv/repo/migrations/20261018120000_add_ingredient_picnic_product.exs new file mode 100644 index 00000000..5a4b2a3e --- /dev/null +++ b/priv/repo/migrations/20261018120000_add_ingredient_picnic_product.exs @@ -0,0 +1,14 @@ +defmodule Picape.Repo.Migrations.AddIngredientPicnicProduct do + use Ecto.Migration + + def change do + alter table(:recipe_ingredient) do + add :picnic_product_id, :string + add :picnic_product_raw, :map + end + + create unique_index(:recipe_ingredient, [:picnic_product_id], + name: :recipe_ingredient_picnic_selling_unit_index + ) + end +end diff --git a/test/fixtures/supermarket/picnic_cart.json b/test/fixtures/supermarket/picnic_cart.json new file mode 100644 index 00000000..bd9d800b --- /dev/null +++ b/test/fixtures/supermarket/picnic_cart.json @@ -0,0 +1,25 @@ +{ + "type": "ORDER", + "id": "shopping_cart", + "items": [ + { + "type": "ORDER_LINE", + "id": "10_11", + "items": [ + { + "type": "ORDER_ARTICLE", + "id": "s2001", + "name": "Volkoren brood", + "price": 189, + "image_ids": ["fake0000fake0000fake0000fake0000fake0000fake0000fake0000fake0001"], + "decorators": [{ "type": "QUANTITY", "quantity": 1 }], + "max_count": 50, + "unit_quantity": "800 g" + } + ], + "price": 189 + } + ], + "total_count": 1, + "total_price": 189 +} diff --git a/test/fixtures/supermarket/picnic_search.json b/test/fixtures/supermarket/picnic_search.json new file mode 100644 index 00000000..5e6da8bc --- /dev/null +++ b/test/fixtures/supermarket/picnic_search.json @@ -0,0 +1,52 @@ +{ + "body": { + "child": { + "type": "CONTAINER", + "id": "search-page", + "children": [ + { + "type": "STACK", + "id": "results", + "children": [ + { + "type": "SELLING_UNIT_TILE", + "id": "tile-s2001", + "content": { + "type": "SELLING_UNIT_TILE", + "sellingUnit": { + "type": "SELLING_UNIT", + "id": "s2001", + "name": "Volkoren brood", + "image_id": "fake0000fake0000fake0000fake0000fake0000fake0000fake0000fake0001", + "display_price": 189, + "unit_quantity": "800 g", + "max_count": 50, + "decorators": [], + "price_ranges": null + } + } + }, + { + "type": "SELLING_UNIT_TILE", + "id": "tile-s2002", + "content": { + "type": "SELLING_UNIT_TILE", + "sellingUnit": { + "type": "SELLING_UNIT", + "id": "s2002", + "name": "Halfvolle melk", + "image_id": "fake0000fake0000fake0000fake0000fake0000fake0000fake0000fake0002", + "display_price": 119, + "unit_quantity": "1 l", + "max_count": 30, + "decorators": [{ "type": "UNIT_QUANTITY", "unit_quantity_text": "1 l" }], + "price_ranges": null + } + } + } + ] + } + ] + } + } +} diff --git a/test/mcp_test.exs b/test/mcp_test.exs index 541f9f17..0a31b754 100644 --- a/test/mcp_test.exs +++ b/test/mcp_test.exs @@ -27,6 +27,8 @@ defmodule Picape.MCPTest do assert Enum.map(tools, & &1["name"]) == [ "search_ingredients", "search_supermarket", + "search_picnic", + "map_ingredient_picnic", "get_shopping_list", "get_previous_orders", "set_ingredient_quantity", @@ -109,6 +111,51 @@ defmodule Picape.MCPTest do end end + describe "search_picnic and map_ingredient_picnic" do + test "search_picnic returns selling units from the Picnic catalogue" do + assert [%{"id" => "s2001", "name" => "Volkoren brood", "price" => 189} | _] = + call!("search_picnic", %{query: "brood"}) + end + + test "map_ingredient_picnic stores and clears the mapping, keeping the AH one" do + ingredient = insert!(:ingredient, name: "Brood", supermarket_product_id: 519_017) + + assert %{"picnic_product_id" => "s2001", "supermarket_product_id" => 519_017} = + call!("map_ingredient_picnic", %{ + ingredient_id: ingredient.id, + picnic_product_id: "s2001", + name: "Volkoren brood", + unit_quantity: "800 g", + image_id: "fake0000fake0000fake0000fake0000fake0000fake0000fake0000fake0001", + price: 189 + }) + + saved = Repo.get!(Ingredient, ingredient.id) + assert saved.picnic_product_id == "s2001" + assert saved.picnic_product_raw["name"] == "Volkoren brood" + assert saved.supermarket_product_id == 519_017 + + assert %{"picnic_product_id" => nil} = + call!("map_ingredient_picnic", %{ + ingredient_id: ingredient.id, + picnic_product_id: nil + }) + + assert Repo.get!(Ingredient, ingredient.id).picnic_product_raw == nil + end + + test "map_ingredient_picnic reports an unknown ingredient and a taken product" do + assert call_error("map_ingredient_picnic", %{ingredient_id: 999_999, picnic_product_id: "s2001"}) == + "no ingredient with id 999999" + + insert!(:ingredient, name: "Brood", picnic_product_id: "s2001") + ingredient = insert!(:ingredient, name: "Melk") + + assert call_error("map_ingredient_picnic", %{ingredient_id: ingredient.id, picnic_product_id: "s2001"}) =~ + "has already been taken" + end + end + describe "get_shopping_list" do test "returns the cart and links items to known ingredients" do insert!(:ingredient, name: "Roomboter", supermarket_product_id: 10_567_923) @@ -188,6 +235,26 @@ defmodule Picape.MCPTest do "Flower Farm Bakken zonder palm" end + test "accepts a Picnic product without a supermarket product" do + assert %{"name" => "Wasabinoten", "picnic_product_id" => "s2002"} = + call!("add_ingredient", %{ + name: "Wasabinoten", + picnic_product_id: "s2002", + unit_quantity: "100 g", + price: 349 + }) + + ingredient = Repo.get_by!(Ingredient, name: "Wasabinoten") + + assert ingredient.supermarket_product_id == nil + assert ingredient.picnic_product_id == "s2002" + assert ingredient.picnic_product_raw["display_price"] == 349 + end + + test "refuses an ingredient with no product at either store" do + assert call_error("add_ingredient", %{name: "Blaar"}) =~ "supermarket_product_id" + end + test "refuses a supermarket product that is already an ingredient" do call!("add_ingredient", %{name: "Roomboter", supermarket_product_id: 10_567_923}) @@ -590,6 +657,37 @@ defmodule Picape.MCPTest do assert call_error("set_mode", %{mode: "floef"}) =~ "unknown mode" end + test "picnic mode serves the Picnic cart and the checklist for unmapped items" do + brood = insert!(:ingredient, name: "Brood", picnic_product_id: "s2001") + insert!(:manual_ingredient, ingredient_id: brood.id, quantity: 1) + rijst = insert!(:ingredient, name: "Rijst", supermarket_product_id: 10_583_837) + insert!(:manual_ingredient, ingredient_id: rijst.id, quantity: 2) + + assert %{"mode" => "picnic"} = call!("set_mode", %{mode: "picnic"}) + + list = call!("get_shopping_list") + assert list["mode"] == "picnic" + + brood_item = Enum.find(list["items"], &(&1["name"] == "Volkoren brood")) + assert brood_item["store"] == "picnic" + assert brood_item["ingredient"]["name"] == "Brood" + + rijst_item = Enum.find(list["items"], &(&1["name"] == "Rijst")) + assert rijst_item["store"] == "checklist" + assert rijst_item["ingredient"]["name"] == "Rijst" + assert rijst_item["checked"] == false + + assert %{"checked" => true} = call!("check_item", %{ingredient_id: rijst.id}) + assert Enum.find(call!("get_shopping_list")["items"], &(&1["name"] == "Rijst"))["checked"] + end + + test "in ah mode every item names the supermarket as its store" do + list = call!("get_shopping_list") + + assert list["mode"] == "ah" + assert Enum.all?(list["items"], &(&1["store"] == "ah")) + end + test "a down supermarket serves the checklist, flagged unreachable" do rijst = insert!(:ingredient, name: "Rijst", supermarket_product_id: 10_583_837) insert!(:manual_ingredient, ingredient_id: rijst.id, line_id: "1", quantity: 2) diff --git a/test/picnic_mode_test.exs b/test/picnic_mode_test.exs new file mode 100644 index 00000000..3bd35dad --- /dev/null +++ b/test/picnic_mode_test.exs @@ -0,0 +1,221 @@ +defmodule Picape.PicnicModeTest do + use Picape.DataCase + + alias Picape.Recipe.Ingredient + alias Picape.{Checklist, Ingredients, Order, Picnic, Repo, Settings, Supermarket} + alias Picape.SupermarketFake + + test "picnic mode reads the Picnic cart plus the checklist fallback" do + brood = + insert!(:ingredient, name: "Brood", supermarket_product_id: 519_017, picnic_product_id: "s2001") + + insert!(:manual_ingredient, ingredient_id: brood.id, quantity: 1) + rijst = insert!(:ingredient, name: "Rijst", supermarket_product_id: 10_583_837) + insert!(:manual_ingredient, ingredient_id: rijst.id, quantity: 2) + + {:ok, %{mode: "picnic"}} = Order.set_mode("picnic") + + assert {:ok, line} = Order.current() + + brood_item = Enum.find(line.items, &(&1.name == "Volkoren brood")) + assert brood_item.store == "picnic" + assert brood_item.ingredient_id == brood.id + + rijst_item = Enum.find(line.items, &(&1.name == "Rijst")) + assert rijst_item.store == "checklist" + assert rijst_item.ingredient_id == rijst.id + assert rijst_item.checked == false + end + + test "syncing pushes mapped ingredients into the Picnic cart" do + melk = insert!(:ingredient, name: "Melk", picnic_product_id: "s2002") + insert!(:manual_ingredient, ingredient_id: melk.id, quantity: 3) + + assert {:ok, %{mode: "picnic", pushed_to_supermarket: true}} = Order.set_mode("picnic") + + assert picnic_quantity(Picnic.cart(), "s2002") == 3 + # A product the Picnic app added itself is left alone. + assert picnic_quantity(Picnic.cart(), "s2001") == 1 + end + + test "unplanning a recipe takes its products out of the Picnic cart" do + melk = insert!(:ingredient, name: "Melk", picnic_product_id: "s2002") + recipe = insert!(:recipe, title: "Nasi", ingredients: [melk]) + + {:ok, _} = Order.set_mode("picnic") + assert {:ok, _} = Order.plan_recipe("1", recipe.id) + assert picnic_quantity(Picnic.cart(), "s2002") == 1 + + assert {:ok, _} = Order.plan_recipe("1", recipe.id, true) + assert picnic_article(Picnic.cart(), "s2002") == nil + end + + test "a rejected Picnic auth key falls back to the checklist" do + rijst = + insert!(:ingredient, + name: "Rijst", + supermarket_product_id: 10_583_837, + picnic_product_id: "s2002" + ) + + insert!(:manual_ingredient, ingredient_id: rijst.id, quantity: 2) + + HTTPoison.post!("http://localhost:4021/__picnic_auth_error", "") + + assert {:ok, %{mode: "picnic", pushed_to_supermarket: false}} = Order.set_mode("picnic") + + assert {:ok, line} = Order.current() + assert line.supermarket_reachable == false + assert [%{name: "Rijst", quantity: 2, store: "checklist"}] = line.items + end + + test "an unmapped ingredient reports its ordered quantity" do + rijst = insert!(:ingredient, name: "Rijst", supermarket_product_id: 10_583_837) + insert!(:manual_ingredient, ingredient_id: rijst.id, quantity: 2) + + {:ok, _} = Order.set_mode("picnic") + + assert {:ok, quantities} = Order.ingredients_ordered_quantity("1", [rijst.id]) + assert quantities[rijst.id] == 2 + end + + test "a mapped ingredient reports its ordered quantity from the Picnic cart" do + brood = + insert!(:ingredient, + name: "Brood", + supermarket_product_id: 519_017, + picnic_product_id: "s2001" + ) + + {:ok, _} = Order.set_mode("picnic") + + assert {:ok, quantities} = Order.ingredients_ordered_quantity("1", [brood.id]) + assert quantities[brood.id] == 1 + end + + test "quantity 0 takes the product out of the Picnic cart" do + brood = insert!(:ingredient, name: "Brood", picnic_product_id: "s2001") + insert!(:manual_ingredient, ingredient_id: brood.id, quantity: 1) + + {:ok, _} = Order.set_mode("picnic") + assert {:ok, _} = Order.order_ingredient("1", brood.id, 0) + + assert picnic_article(Picnic.cart(), "s2001") == nil + end + + test "unmapped ingredients stay tickable checklist items" do + rijst = insert!(:ingredient, name: "Rijst", supermarket_product_id: 10_583_837) + insert!(:manual_ingredient, ingredient_id: rijst.id, quantity: 1) + + {:ok, _} = Order.set_mode("picnic") + + assert {:ok, _} = Checklist.check(rijst.id, true) + + assert {:ok, line} = Order.current() + assert %{checked: true, store: "checklist"} = Enum.find(line.items, &(&1.name == "Rijst")) + end + + test "picnic sync leaves the supermarket basket and the AH mapping untouched" do + melk = + insert!(:ingredient, + name: "Melk", + supermarket_product_id: 10_583_837, + picnic_product_id: "s2002" + ) + + insert!(:manual_ingredient, ingredient_id: melk.id, quantity: 3) + + before = Supermarket.cart() + + {:ok, _} = Order.set_mode("picnic") + + Supermarket.invalidate_cart() + assert Supermarket.cart() == before + assert Repo.get!(Ingredient, melk.id).supermarket_product_id == 10_583_837 + end + + test "a dead Picnic falls back to the checklist" do + rijst = + insert!(:ingredient, + name: "Rijst", + supermarket_product_id: 10_583_837, + picnic_product_id: "s2002" + ) + + insert!(:manual_ingredient, ingredient_id: rijst.id, quantity: 2) + + {:ok, _} = Order.set_mode("picnic") + supermarket_down() + + assert {:ok, line} = Order.current() + assert line.supermarket_reachable == false + assert [%{name: "Rijst", quantity: 2, store: "checklist"}] = line.items + end + + test "switching to picnic while Picnic is down still switches" do + supermarket_down() + + assert {:ok, %{mode: "picnic", pushed_to_supermarket: false, error: error}} = + Order.set_mode("picnic") + + assert error =~ "unreachable" + assert Settings.mode() == "picnic" + end + + test "remapping to another Picnic product takes the old one out of the cart" do + brood = insert!(:ingredient, name: "Brood", picnic_product_id: "s2001") + insert!(:manual_ingredient, ingredient_id: brood.id, quantity: 1) + {:ok, _} = Order.set_mode("picnic") + + assert {:ok, _} = + Ingredients.edit_ingredient(%{ingredient_id: brood.id, picnic_product_id: "s2002"}) + + assert %{ + method: "POST", + path: "/api/15/cart/remove_product", + body: %{"product_id" => "s2001", "count" => 1} + } = List.last(SupermarketFake.requests()) + + Picnic.invalidate_cart() + assert picnic_article(Picnic.cart(), "s2001") == nil + end + + test "switching back to ah pushes the list into the supermarket basket" do + rijst = insert!(:ingredient, name: "Rijst", supermarket_product_id: 10_583_837) + + {:ok, _} = Order.set_mode("picnic") + {:ok, _} = Order.order_ingredient("1", rijst.id, 2) + + assert {:ok, %{mode: "ah", pushed_to_supermarket: true}} = Order.set_mode("ah") + + Supermarket.invalidate_cart() + assert product_quantity(Supermarket.cart(), 10_583_837) == 2 + end + + defp supermarket_down() do + HTTPoison.post!("http://localhost:4021/__down", "") + Picnic.invalidate_cart() + Supermarket.invalidate_cart() + Supermarket.invalidate_orders() + end + + defp picnic_article(cart, product_id) do + cart["items"] + |> Enum.flat_map(& &1["items"]) + |> Enum.find(&(&1["id"] == product_id)) + end + + defp picnic_quantity(cart, product_id) do + case picnic_article(cart, product_id) do + nil -> nil + article -> Enum.find(article["decorators"], &(&1["type"] == "QUANTITY"))["quantity"] + end + end + + defp product_quantity(cart, product_id) do + Enum.find_value(cart["items"], fn + %{"product" => %{"id" => ^product_id}, "quantity" => quantity} -> quantity + _ -> nil + end) + end +end diff --git a/test/picnic_product_index_test.exs b/test/picnic_product_index_test.exs new file mode 100644 index 00000000..7319862c --- /dev/null +++ b/test/picnic_product_index_test.exs @@ -0,0 +1,38 @@ +defmodule Picape.PicnicProductIndexTest do + use Picape.DataCase, async: false + + alias Picape.Recipe.Ingredient + alias Picape.Repo + + # Prod carries an index named recipe_ingredient_picnic_product_id_index on + # supermarket_product_id, left over from a column rename — the same name + # Ecto picks by default for a unique index on picnic_product_id, so the + # migration must name its index explicitly or release fails on the + # collision. Recreate that prod state and run the real migration over it. + # The sandbox holds only one connection and Ecto.Migrator needs two, so the + # migration runs in a subprocess against the test database: down commits, + # the leftover index is created, up commits, then the leftover is dropped. + test "migration runs with prod's leftover index and duplicate picnic ids stay changeset errors" do + script = """ + Code.require_file("priv/repo/migrations/20261018120000_add_ingredient_picnic_product.exs") + mod = Picape.Repo.Migrations.AddIngredientPicnicProduct + Picape.Repo.query!("ALTER INDEX IF EXISTS recipe_ingredient_picnic_product_id_index RENAME TO recipe_ingredient_picnic_selling_unit_index") + Ecto.Migrator.down(Picape.Repo, 20261018120000, mod) + Picape.Repo.query!("CREATE UNIQUE INDEX recipe_ingredient_picnic_product_id_index ON recipe_ingredient (supermarket_product_id)") + Ecto.Migrator.up(Picape.Repo, 20261018120000, mod) + Picape.Repo.query!("DROP INDEX recipe_ingredient_picnic_product_id_index") + IO.puts("migration_ok") + """ + + {out, status} = + System.cmd("mix", ["run", "-e", script], env: [{"MIX_ENV", "test"}], cd: File.cwd!()) + + assert status == 0, out + assert out =~ "migration_ok" + + attrs = %{name: "Sugar", picnic_product_id: "s1"} + assert {:ok, _} = %Ingredient{} |> Ingredient.add_changeset(attrs) |> Repo.insert() + assert {:error, changeset} = %Ingredient{} |> Ingredient.add_changeset(attrs) |> Repo.insert() + assert %{picnic_product_id: ["has already been taken"]} = errors_on(changeset) + end +end diff --git a/test/picnic_test.exs b/test/picnic_test.exs new file mode 100644 index 00000000..36581a10 --- /dev/null +++ b/test/picnic_test.exs @@ -0,0 +1,126 @@ +defmodule Picape.PicnicTest do + use Picape.DataCase + + alias Picape.Order.Sync + alias Picape.{Picnic, SupermarketFake} + + test "search returns the selling units the page carries" do + assert [ + %{id: "s2001", name: "Volkoren brood", price: 189, unit_quantity: "800 g"}, + %{id: "s2002", name: "Halfvolle melk", price: 119, unit_quantity: "1 l"} + ] = Picnic.search("brood") + end + + test "search sends the query as search_term" do + Picnic.search("volkoren brood") + + request = List.last(SupermarketFake.requests()) + assert request.method == "GET" + assert request.path == "/api/15/pages/search-page-results" + assert request.query == "search_term=volkoren+brood" + end + + test "the fake refuses a search without search_term" do + assert %HTTPoison.Response{status_code: 400} = + HTTPoison.get!("http://localhost:4021/api/15/pages/search-page-results") + end + + test "every request carries the Picnic headers" do + Picnic.cart() + + request = List.last(SupermarketFake.requests()) + assert request.headers["x-picnic-auth"] == "test-auth-key" + assert is_binary(request.headers["x-picnic-agent"]) and request.headers["x-picnic-agent"] != "" + assert is_binary(request.headers["x-picnic-did"]) and request.headers["x-picnic-did"] != "" + assert request.headers["x-picnic-country"] == "NL" + end + + test "search with an empty query asks nothing" do + assert Picnic.search("") == [] + end + + test "cart reads the order Picnic reports" do + cart = Picnic.cart() + + assert cart["total_count"] == 1 + assert cart["total_price"] == 189 + assert picnic_quantity(cart, "s2001") == 1 + end + + test "add_product and remove_product move selling units in and out" do + cart = Picnic.add_product("s2002", 3) + assert picnic_quantity(cart, "s2002") == 3 + + cart = Picnic.remove_product("s2002", 1) + assert picnic_quantity(cart, "s2002") == 2 + + cart = Picnic.remove_product("s2002", 2) + assert picnic_article(cart, "s2002") == nil + end + + test "add_product returns and caches the whole cart" do + cart = Picnic.add_product("s2002", 1) + + assert Picnic.cart() == cart + end + + test "apply_changes posts the deltas a target-quantity diff asks for" do + {:ok, changes} = Sync.changes(%{"s2001" => 3, "s2002" => 1}, %{}, %{"s2001" => 1}) + + assert {:ok, :synced} = Picnic.apply_changes(changes, %{"s2001" => 1}) + + cart = Picnic.cart() + assert picnic_quantity(cart, "s2001") == 3 + assert picnic_quantity(cart, "s2002") == 1 + end + + test "apply_changes removes down to the wanted quantity" do + {:ok, changes} = Sync.changes(%{}, %{"s2001" => 0}, %{"s2001" => 1}) + + assert {:ok, :synced} = Picnic.apply_changes(changes, %{"s2001" => 1}) + + assert picnic_article(Picnic.cart(), "s2001") == nil + end + + test "a dead Picnic raises the shared supermarket error" do + HTTPoison.post!("http://localhost:4021/__down", "") + Picnic.invalidate_cart() + + error = assert_raise Picape.Supermarket.Error, fn -> Picnic.cart() end + assert error.message =~ "503" + end + + test "a rejected auth key raises the shared supermarket error" do + HTTPoison.post!("http://localhost:4021/__picnic_auth_error", "") + Picnic.invalidate_cart() + + error = assert_raise Picape.Supermarket.Error, fn -> Picnic.cart() end + assert error.message =~ "401" + assert error.message =~ "AUTH_ERROR" + end + + test "without an auth key the client refuses before it asks" do + key = Application.get_env(:picape, Picape.Picnic)[:auth_key] + Application.put_env(:picape, Picape.Picnic, base_url: "http://localhost:4021/api/15") + + on_exit(fn -> + Application.put_env(:picape, Picape.Picnic, base_url: "http://localhost:4021/api/15", auth_key: key) + end) + + error = assert_raise Picape.Supermarket.Error, fn -> Picnic.cart() end + assert error.message =~ "PICNIC_AUTH_KEY" + end + + defp picnic_article(cart, product_id) do + cart["items"] + |> Enum.flat_map(& &1["items"]) + |> Enum.find(&(&1["id"] == product_id)) + end + + defp picnic_quantity(cart, product_id) do + case picnic_article(cart, product_id) do + nil -> nil + article -> Enum.find(article["decorators"], &(&1["type"] == "QUANTITY"))["quantity"] + end + end +end diff --git a/test/support/supermarket_fake.ex b/test/support/supermarket_fake.ex index 53e27ec6..3d383f58 100644 --- a/test/support/supermarket_fake.ex +++ b/test/support/supermarket_fake.ex @@ -13,10 +13,15 @@ defmodule Picape.SupermarketFake do @state __MODULE__.State @activations __MODULE__.Activations @orders __MODULE__.Orders + @picnic __MODULE__.Picnic @down __MODULE__.Down + @picnic_auth_error __MODULE__.PicnicAuthError + @requests __MODULE__.Requests plug(Plug.Parsers, parsers: [:json], json_decoder: Jason) plug(:maybe_down) + plug(:maybe_picnic_auth_error) + plug(:log_request) plug(:match) plug(:dispatch) @@ -24,7 +29,10 @@ defmodule Picape.SupermarketFake do {:ok, _} = Agent.start_link(fn -> fixture("basket.json") end, name: @state) {:ok, _} = Agent.start_link(fn -> MapSet.new() end, name: @activations) {:ok, _} = Agent.start_link(fn -> fixture("orders.json") end, name: @orders) + {:ok, _} = Agent.start_link(fn -> fixture("picnic_cart.json") end, name: @picnic) {:ok, _} = Agent.start_link(fn -> false end, name: @down) + {:ok, _} = Agent.start_link(fn -> false end, name: @picnic_auth_error) + {:ok, _} = Agent.start_link(fn -> [] end, name: @requests) Plug.Cowboy.http(__MODULE__, [], port: port) end @@ -41,9 +49,16 @@ defmodule Picape.SupermarketFake do Agent.update(@state, fn _ -> fixture("basket.json") end) Agent.update(@activations, fn _ -> MapSet.new() end) Agent.update(@orders, fn _ -> fixture("orders.json") end) + Agent.update(@picnic, fn _ -> fixture("picnic_cart.json") end) Agent.update(@down, fn _ -> false end) + Agent.update(@picnic_auth_error, fn _ -> false end) + Agent.update(@requests, fn _ -> [] end) + Picape.Picnic.invalidate_cart() end + @doc "Every request the fake answered, oldest first: method, path, query, body and headers." + def requests(), do: Agent.get(@requests, &Enum.reverse/1) + defp maybe_down(conn, _opts) do if Agent.get(@down, & &1) and not String.starts_with?(conn.request_path, "/__") do conn @@ -54,6 +69,42 @@ defmodule Picape.SupermarketFake do end end + # Picnic rejects a request whose auth key it does not know with a 401 and an + # error body; /__picnic_auth_error makes the api routes do that until reset. + defp maybe_picnic_auth_error(conn, _opts) do + if Agent.get(@picnic_auth_error, & &1) and String.starts_with?(conn.request_path, "/api/15/") do + conn + |> put_resp_content_type("application/json") + |> send_resp(401, Jason.encode!(%{"error" => %{"code" => "AUTH_ERROR"}})) + |> halt() + else + conn + end + end + + defp log_request(conn, _opts) do + body = + case conn.body_params do + %Plug.Conn.Unfetched{} -> nil + params -> params + end + + Agent.update(@requests, fn requests -> + [ + %{ + method: conn.method, + path: conn.request_path, + query: conn.query_string, + body: body, + headers: Map.new(conn.req_headers) + } + | requests + ] + end) + + conn + end + post "/graphql" do case conn.body_params do %{"operationName" => "FetchMyListBasket"} -> @@ -106,11 +157,42 @@ defmodule Picape.SupermarketFake do send_resp(conn, 204, "") end + # Pretends the Picnic auth key was rejected: every api/15 endpoint answers + # 401 with an AUTH_ERROR body, until /__reset. + post "/__picnic_auth_error" do + Agent.update(@picnic_auth_error, fn _ -> true end) + send_resp(conn, 204, "") + end + post "/__up" do Agent.update(@down, fn _ -> false end) send_resp(conn, 204, "") end + # The Picnic api/15 endpoints picnic mode uses. `add_product` and + # `remove_product` keep a basket the same way the basket fixture does: + # product ids are selling unit ids like "s2001". + get "/api/15/cart" do + json(conn, Agent.get(@picnic, & &1)) + end + + post "/api/15/cart/add_product" do + %{"product_id" => product_id, "count" => count} = conn.body_params + json(conn, Agent.get_and_update(@picnic, &picnic_cart(&1, product_id, count))) + end + + post "/api/15/cart/remove_product" do + %{"product_id" => product_id, "count" => count} = conn.body_params + json(conn, Agent.get_and_update(@picnic, &picnic_cart(&1, product_id, -count))) + end + + get "/api/15/pages/search-page-results" do + case conn.params["search_term"] do + term when is_binary(term) and term != "" -> json(conn, fixture("picnic_search.json")) + _ -> send_resp(conn, 400, "search_term is required") + end + end + get "/mobile-services/v4/order/summaries" do json(conn, Agent.get(@orders, & &1)) end @@ -178,6 +260,94 @@ defmodule Picape.SupermarketFake do %{"data" => %{"bonusPromotions" => [%{"__typename" => "Promotion", "id" => id, "products" => []}]}} end + # Picnic's cart is a list of ORDER_LINE groups, each holding ORDER_ARTICLEs + # whose quantity lives in a QUANTITY decorator. A positive delta bumps or + # appends, a negative one lowers and empties groups drop out. + defp picnic_cart(cart, product_id, delta) do + groups = + cart["items"] + |> Enum.map(&picnic_group_articles(&1, product_id, delta)) + |> Enum.reject(&(&1["items"] == [])) + + groups = + if delta > 0 and is_nil(picnic_article(cart, product_id)) do + groups ++ [picnic_group(product_id, delta)] + else + groups + end + + articles = Enum.flat_map(groups, & &1["items"]) + + cart + |> Map.put("items", groups) + |> Map.put("total_count", articles |> Enum.map(&picnic_quantity/1) |> Enum.sum()) + |> Map.put("total_price", articles |> Enum.map(&(&1["price"] * picnic_quantity(&1))) |> Enum.sum()) + |> then(&{&1, &1}) + end + + defp picnic_group_articles(group, product_id, delta) do + articles = + Enum.flat_map(group["items"], fn + %{"id" => ^product_id} = article -> + quantity = picnic_quantity(article) + delta + if quantity > 0, do: [picnic_quantity(article, quantity)], else: [] + + article -> + [article] + end) + + %{group | "items" => articles} + end + + defp picnic_article(cart, product_id) do + cart["items"] |> Enum.flat_map(& &1["items"]) |> Enum.find(&(&1["id"] == product_id)) + end + + defp picnic_quantity(article) do + Enum.find(article["decorators"], %{"quantity" => 0}, &(&1["type"] == "QUANTITY"))["quantity"] + end + + defp picnic_quantity(article, quantity) do + put_in(article["decorators"], [%{"type" => "QUANTITY", "quantity" => quantity}]) + end + + defp picnic_group(product_id, count) do + unit = + fixture("picnic_search.json") + |> picnic_selling_units() + |> Enum.find(&(&1["id"] == product_id)) || %{"id" => product_id, "name" => "Product #{product_id}"} + + %{ + "type" => "ORDER_LINE", + "id" => "group_#{product_id}", + "items" => [ + %{ + "type" => "ORDER_ARTICLE", + "id" => product_id, + "name" => unit["name"], + "price" => unit["display_price"] || 0, + "image_ids" => List.wrap(unit["image_id"]), + "decorators" => [%{"type" => "QUANTITY", "quantity" => count}], + "max_count" => unit["max_count"] || 50, + "unit_quantity" => unit["unit_quantity"] || "" + } + ], + "price" => (unit["display_price"] || 0) * count + } + end + + defp picnic_selling_units(node) when is_map(node) do + Enum.flat_map(node, fn + {"sellingUnit", %{} = unit} -> [unit | picnic_selling_units(unit)] + {_key, value} -> picnic_selling_units(value) + end) + end + + defp picnic_selling_units(list) when is_list(list), + do: Enum.flat_map(list, &picnic_selling_units/1) + + defp picnic_selling_units(_), do: [] + defp update_basket(response, items) do update_in(response, ["data", "basket"], fn basket -> basket = Enum.reduce(items, basket, &apply_item/2)