Skip to content

exclude active freebie items from product kit discount calculation#703

Open
vitorrgg wants to merge 3 commits intomainfrom
freebie-kit
Open

exclude active freebie items from product kit discount calculation#703
vitorrgg wants to merge 3 commits intomainfrom
freebie-kit

Conversation

@vitorrgg
Copy link
Member

Problem

Freebie items (added via freebies_rules) were being included in product_kit_discounts calculations. For rules using discount_lowest_price: true and check_all_items: true, the freebie's price would become the lowest price used as the discount base, and the freebie's quantity would count toward the kit minimum — both causing the kit discount to be much lower than intended.

Solution

Before processing kit discounts, collect the product IDs of currently active freebie rules (validated by date range, customer, and coupon/UTM). These IDs are then excluded from two places:

  1. kitEligibleItems — the items array passed to getValidDiscountRules, which is used to determine the lowest price for discount_lowest_price rules.
  2. kitItems filter — the items used to compute total quantity and apply the discount, preventing the freebie from triggering or inflating kit counts.

Impact

No change in behavior when no freebie rules are active. When a freebie rule is active, only its specific product IDs are excluded from kit calculations; all other items remain unaffected.

Fixes #702

@vitorrgg vitorrgg requested a review from leomp12 February 25, 2026 21:29
Copy link
Member

@leomp12 leomp12 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@claude review, considere que os brindes nunca deveriam chegar aqui sem a flag, valide se a flag não está sendo checada em outros momentos (para aplicação do brinde)

Comment on lines -283 to -285
const itemsForKit = params.items.filter((item) => {
return !item.flags?.includes('freebie');
});
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Mas você tem alguma evidência de brinde chegando sem a flag? 🤔

@claude
Copy link

claude bot commented Feb 26, 2026

Claude finished @leomp12's task in 4m 12s —— View job


Code Review — Freebie Kit Exclusion

  • Gather context
  • Read the changed file and understand the freebie flag mechanism
  • Check if freebies are flagged before reaching kit discount logic
  • Validate where the flag is checked for freebie application
  • Post review feedback

Resposta à pergunta do @leomp12

Sobre a flag freebie:

Investigando o código base, os itens de brinde podem chegar em params.items sem nenhuma flag de brinde, dependendo de como o storefront os adicionou ao carrinho:

  • checkout-utils.ts:292-301: A flag 'discount-set-free' só é aplicada aos itens do pedido no momento do checkout — não ao carrinho durante o fluxo do apply_discount
  • use-cart-item.ts:47: O storefront verifica flags?.includes('freebie') para display, mas o storefront base não define essa flag ao adicionar brindes ao carrinho (não há código no storefront que processe freebie_product_ids e adicione ao carrinho com a flag)
  • pagarme-v5/api-utils.mjs:34 e galaxpay/update-subscription.ts:14: Ambos checam flags.includes('freebie') || flags.includes('discount-set-free') confirmando dois flags diferentes

Então sim, brindes podem chegar sem flag em params.items durante as chamadas de apply_discount no carrinho — o flag freebie parece ser uma convenção de storefronts customizados, não do base.


Problema na implementação do PR

A coleção de freebieProductIds (linhas 283–296) usa validações menos restritivas que a getFreebiesPreview():

PR (linha 283-296):

config.freebies_rules.forEach((rule) => {
  if (
    validateDateRange(rule)
    && validateCustomerId(rule, params)
    && Array.isArray(rule.product_ids)
    && matchFreebieRule(rule, params)
  ) { ... }
});

getFreebiesPreview() (linha 157-163):

config.freebies_rules.filter((rule) => {
  return validateDateRange(rule)
    && validateCustomerId(rule, params)
    && mapCampaignProducts({ product_ids: rule.check_product_ids }, params).valid  // ← FALTA
    && Array.isArray(rule.product_ids)
    && rule.product_ids.length  // ← FALTA
    && matchFreebieRule(rule, params);
});

Dois problemas:

  1. check_product_ids não é validado — Se uma regra de brinde requer produtos específicos no carrinho (check_product_ids) para ativar, o PR excluirá os IDs dos brindes do cálculo de kit mesmo quando a regra de brinde não está ativa (produtos gatilho ausentes do carrinho). Isso causaria uma exclusão falsa de itens do kit.

  2. min_subtotal não é verificado — O subtotal mínimo para ativar o brinde não é validado, então produtos de brinde podem ser excluídos do kit mesmo quando o carrinho não atingiu o valor mínimo para o brinde disparar. [Fix this →]

Solução sugerida: Alinhar as validações com getFreebiesPreview() incluindo as checagens ausentes, ou — se a convenção do storefront garante que brindes chegam com flags: ['freebie'] — simplificar o filtro em kitItems para usar !item.flags?.includes('freebie') && !item.flags?.includes('discount-set-free') diretamente.
|

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Freebie item affects product kit discount calculation

2 participants