Como actualizar el precio según variante y suscepción ?

Buenas que tal?

Me encuentro trabajando en una block app donde se listan las variante y los selling plan groups con sus selling plans. El problema es que no he logrado de ninguna manera actualizar los selling plan groups que se listan para cada variante, y por consiguiente tampoco el precio que ve el cliente final.

Segun la documentacion de shopify hay que actualizar el objeto producto segun la variante seleccionada, pero realmente no he logrado entender como funciona esto, ya que cada vez que intento actualizarlo, no sucede nada.

Sin contar con que la documentacion sobre el objeto producto habla de un monton de props que el objeto no tiene, como por ejemplo la selected_variant, que seria de vital ayuda para estas modificaciones!

A continuacion dejo la documentacion que estoy siguiendo, y un ejemplo de codigo del mismo.

https://shopify.dev/themes/product-merchandising/variants#shopify-option-selection

https://shopify.dev/themes/pricing-payments/subscriptions/selling-plans#update-selling-plan-information

HTML

{%- liquid
assign current_variant = product.selected_or_first_available_variant | default: product.variants.first
assign current_selling_plan_allocation = current_variant.selected_selling_plan_allocation

if current_selling_plan_allocation == nil and current_variant.requires_selling_plan
assign current_selling_plan_allocation = current_variant.selling_plan_allocations | first
endif

assign offer = current_selling_plan_allocation | default: current_variant
-%}

## {{ product.title}}
{{ offer.price | money }}

{% if offer.compare_at_price > offer.price %}
~~{{ offer.compare_at_price | money }}~~
{% if offer.selling_plan %}Subscription{% else %}Sale{% endif %}
{% endif %}

{% form 'product', product, class:'shopify-product-form' %}

{% comment %}theme-check-disable ParserBlockingScriptTag{% endcomment %}
{{ 'option_selection.js' | shopify_asset_url | script_tag }}
{% comment %}theme-check-enable ParserBlockingScriptTag{% endcomment %}

{{ line_item.selling_plan_allocation.selling_plan.name }}

{% endform %}

{% schema %}
{
  "name": "Subscription",
  "target": "section",
  "stylesheet": "subscription.css",
  "javascript": "subscription.js",
  "templates": ["product"],
  "settings": []
}
{% endschema %}

JS

var sellingPlanContainer = document.querySelector(".selling-plan-fieldset");
var product = JSON.parse(sellingPlanContainer.dataset.product);
var productForm = document.querySelector(".shopify-product-form");

var findSelectedVariant = function () {
  var selectedVariantId = parseInt(
    document.querySelector('.shopify-product-form [name="id"]').value
  );
  var selectedVariant;

  for (var i = 0; i < product.variants.length; i++) {
    if (product.variants[i].id === selectedVariantId) {
      selectedVariant = product.variants[i];
      break;
    }
  }

  return selectedVariant;
};

// Watch for variant selection to update selling plan option selectors
productForm.addEventListener("change", function (e) {
  var selectedVariant = findSelectedVariant();
  var availableSellingPlanAllocations =
    selectedVariant.selling_plan_allocations;

  console.log("change", e.target.attributes);

  var radioValue = e.target?.attributes[2]?.value || null;
  console.log("radio", radioValue);

  if (availableSellingPlanAllocations) {
    var sellingId = document.querySelector('[name="selling_plan"]').value;
    for (const e of availableSellingPlanAllocations) {
      if (e.selling_plan_id == sellingId) {
        product.selected_or_first_available_variant == e;
      }
    }
  }

  console.log("selected?", availableSellingPlanAllocations || null);

  // Update the selling plan option selectors based on the available selling plan allocations
  // for the selected variant
});

// Watch for selling plan option change to update the selected selling plan
sellingPlanContainer
  .querySelectorAll("select")
  .forEach(function (optionSelector) {
    optionSelector.addEventListener("change", function (e) {
      var selectedVariant = findSelectedVariant();
      var availableSellingPlanAllocations =
        selectedVariant.selling_plan_allocations;
      var selectedSellingPlanId;

      console.log("En el segundo", availableSellingPlanAllocations);
      console.log("En el segundo e", e);

      let groupIdSelected = e.target.dataset.group;
      let itemSelected = e.target.value;
      let sellingPlanSelected = getSubscriptionPlanId(
        groupIdSelected,
        itemSelected
      );

      if (sellingPlanSelected) {
        selectedSellingPlanId = sellingPlanSelected;
      }

      selectedSellingPlanId =
        typeof selectedSellingPlanId === "undefined"
          ? ""
          : selectedSellingPlanId;
      document.querySelector('[name="selling_plan"]').value =
        selectedSellingPlanId;
    });
  });

const getSubscriptionPlanId = (selectedSellingGroupId, optionValue) => {
  let sellingPlanGroup = product.selling_plan_groups.find(
    (x) => x.id === selectedSellingGroupId
  );
  let sellingPlanSelected = sellingPlanGroup.selling_plans.find(
    (x) => x.options[0].value === optionValue
  ).id;
  return sellingPlanSelected;
};

var selectCallback = function (variant, selector) {
  console.log(product || null);
  console.log("variante", variant ? variant : "sin variante");
  this.variant = variant;
  console.log("selector", selector ? selector : "sin selector");

  selector.product.selected_variant = variant;

  document.querySelector('[name="id"]').value = variant.id;
};

new Shopify.OptionSelectors("product-select", {
  product: product,
  onVariantSelected: selectCallback,
});

Hola @GastonM ,

Gracias por tu mensaje y por compartir el código conmigo. Por curiosidad, ¿ese código es para una aplicación que estás creando?

Solo para darte un poco de contexto, aconsejamos que si tiene cualquier duda en relación con algo que involucra la API de Shopify, debe subir tu pregunta en el subforo Shopify APIs & SDKs. Tu pregunta se queda fuera del alcance del soporte de Shopify, sin embargo, hay desarrolladores que conocen la plataforma y participan activamente en esa comunidad. Es posible que podrás ya encontrar un hilo que trata del mismo asunto de tu duda.

Una otra cosa que puedes hacer es juntarte a nuestra comunidad de charla en Discord para desarrolladores.

Saludos