diff --git a/lib/simpleshop_theme/products.ex b/lib/simpleshop_theme/products.ex index 34c9d04..37d7beb 100644 --- a/lib/simpleshop_theme/products.ex +++ b/lib/simpleshop_theme/products.ex @@ -443,6 +443,15 @@ defmodule SimpleshopTheme.Products do |> Repo.all() end + @doc """ + Updates a product image with the given attributes. + """ + def update_product_image(%ProductImage{} = product_image, attrs) do + product_image + |> ProductImage.changeset(attrs) + |> Repo.update() + end + @doc """ Links a product image to a Media.Image by setting its image_id. """ diff --git a/lib/simpleshop_theme/sync/mockup_enricher.ex b/lib/simpleshop_theme/sync/mockup_enricher.ex index 958034a..3b6dc38 100644 --- a/lib/simpleshop_theme/sync/mockup_enricher.ex +++ b/lib/simpleshop_theme/sync/mockup_enricher.ex @@ -203,13 +203,32 @@ defmodule SimpleshopTheme.Sync.MockupEnricher do end defp append_images_to_product(product, extra_images) do - # Find the current max position so we append after existing images existing_images = Products.list_product_images(product.id) - max_position = existing_images |> Enum.map(& &1.position) |> Enum.max(fn -> -1 end) + existing_count = length(existing_images) + + # Sort extras: front views first, then the rest + sorted_extras = + Enum.sort_by(extra_images, fn img -> + title = String.downcase(img.alt || "") + if String.contains?(title, "front"), do: 0, else: 1 + end) + + has_front_extra = + Enum.any?(sorted_extras, fn img -> + String.contains?(String.downcase(img.alt || ""), "front") + end) + + # If we have a front extra, shift existing images down to make room + if has_front_extra do + shift_images_down(existing_images, length(sorted_extras)) + end + + # Insert extras: front extras at position 0+, others after existing + start_position = if has_front_extra, do: 0, else: existing_count results = - extra_images - |> Enum.with_index(max_position + 1) + sorted_extras + |> Enum.with_index(start_position) |> Enum.map(fn {img, position} -> attrs = %{ product_id: product.id, @@ -233,6 +252,13 @@ defmodule SimpleshopTheme.Sync.MockupEnricher do {:ok, count} end + # Bump all existing image positions up by `offset` to make room at the front + defp shift_images_down(existing_images, offset) do + Enum.each(existing_images, fn img -> + Products.update_product_image(img, %{position: img.position + offset}) + end) + end + # Check if this product already has extra angle images from a prior enrichment defp already_enriched?(product) do images = Products.list_product_images(product.id)