How to add a single gift with purchase using the cart transform API?

I’m trying to build a function so that if a customer adds a product with a specific tag, that will add a free gift to their cart. I’m using the expand operation to add the gift and set it’s price to 0 - this works fine.

expandedCartItems: [
  {
    merchandiseId: line.merchandise.id,
    quantity: 1,
    price: {
      adjustment: {
        fixedPricePerUnit: {
          amount: (line.cost.totalAmount.amount / line.quantity).toFixed(2),
        }
      }
    }
  },
  {
    merchandiseId: FREE_GIFT_VARIANT_ID,
    quantity: 1,
    price: {
      adjustment: {
        fixedPricePerUnit: {
          amount: 0,
        }
      }
    }
  },
]

The issue is, if the customer increases the quantity, the gift also increases. I want to limit the gift to a maximum of 1 in their cart, is this not possible using expand? If so, what is the alternative?

I’m ripping my hair out with 100 tabs open, and a hateful conversation with chat GPT - any help would be much appreciated, thanks!

You’ll need to also have a ‘Cart/Checkout validation function’ that ensures the quantity of that cart line is never > 1.

@bkspace Ok, does that mean that in order to limit the gift to 1, the qualifying product will also have to be limited to 1? I was kinda hoping the customer could buy 2x main product, and just receive 1x gift. Thank you!

It would be possible, but the UX is an open question. Let’s say you determined the cart line to expand via a line attribute. You could use that same line attribute and ensure there’s only 1 in the cart.

Because this all happens at the cart line level, you can definitely add another of the same item, but without the attribute.