learnshopify.dev/Workspace
code reading

Trace Sarah's discount Function, then answer.

// extensions/bulk-discount/src/cart_lines_discounts_generate_run.js
//
// Input query (cart_lines_discounts_generate_run.graphql):
//
//   query CartLinesDiscountsGenerateRunInput {
//     cart {
//       lines {
//         id
//         quantity
//         merchandise {
//           __typename
//           ... on ProductVariant {
//             product { hasAnyTag(tags: ["bulk-eligible"]) }
//           }
//         }
//       }
//     }
//   }

import { ProductDiscountSelectionStrategy } from "../generated/api";

export function cartLinesDiscountsGenerateRun(input) {
  const candidates = [];

  for (const line of input.cart.lines) {
    if (line.merchandise.__typename !== "ProductVariant") continue;
    if (!line.merchandise.product.hasAnyTag) continue;

    const freeUnits = Math.floor(line.quantity / 4);
    if (freeUnits === 0) continue;

    candidates.push({
      message: "Buy 3 bags, get 1 free",
      targets: [{ cartLine: { id: line.id, quantity: freeUnits } }],
      value: { percentage: { value: 100 } },
    });
  }

  if (candidates.length === 0) {
    return { operations: [] };
  }

  return {
    operations: [
      {
        productDiscountsAdd: {
          candidates,
          selectionStrategy: ProductDiscountSelectionStrategy.First,
        },
      },
    ],
  };
}
1. Where does the boolean `line.merchandise.product.hasAnyTag` come from?
2. A café puts 7 bags of a `bulk-eligible` coffee in one line. What does the function do?
3. How does 'free' happen in the result?
4. Marcus deletes the promo banner in the theme editor. What happens to the discount?
0 / 1 task solved