fix cart hydration for demo mode with mock products

Cart.hydrate/1 now falls back to PreviewData mock products when variant
IDs aren't found in the database, so add-to-cart works on fresh deploys
without synced Printify data.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
jamey 2026-02-09 08:20:59 +00:00
parent c5e353eba1
commit 90b0242a06

View File

@ -117,11 +117,18 @@ defmodule SimpleshopTheme.Cart do
else else
variants_map = Products.get_variants_with_products(variant_ids) variants_map = Products.get_variants_with_products(variant_ids)
# Fall back to mock data for variant IDs not found in DB (demo mode)
missing_ids = variant_ids -- Map.keys(variants_map)
mock_map = if missing_ids != [], do: mock_variants_map(missing_ids), else: %{}
cart_items cart_items
|> Enum.map(fn {variant_id, quantity} -> |> Enum.map(fn {variant_id, quantity} ->
case Map.get(variants_map, variant_id) do case Map.get(variants_map, variant_id) do
nil -> nil ->
nil case Map.get(mock_map, variant_id) do
nil -> nil
item -> %{item | quantity: quantity}
end
variant -> variant ->
%{ %{
@ -162,6 +169,37 @@ defmodule SimpleshopTheme.Cart do
end end
end end
# Build a lookup map from mock product data for variant IDs not in the DB.
# Allows the cart to work in demo mode when no real products are synced.
defp mock_variants_map(variant_ids) do
ids_set = MapSet.new(variant_ids)
SimpleshopTheme.Theme.PreviewData.products()
|> Enum.flat_map(fn product ->
(product[:variants] || [])
|> Enum.filter(fn v -> MapSet.member?(ids_set, v.id) end)
|> Enum.map(fn v ->
image =
case product[:image_url] do
"/mockups/" <> _ = url -> "#{url}-400.webp"
url -> url
end
{v.id,
%{
variant_id: v.id,
product_id: product.id,
name: product.name,
variant: format_variant_options(v.options),
price: v.price,
quantity: 1,
image: image
}}
end)
end)
|> Map.new()
end
# ============================================================================= # =============================================================================
# Helpers # Helpers
# ============================================================================= # =============================================================================