Skip to main content

Adding Product or Contract to Basket via SDK

We want to programmatically add a product or contract to the basket, how can we do that?

Use the addProductOrContractById service function that is available on basket module:

// Add a product
await window.hapi.basket.service.addProductOrContractById.run('product-123', true)

// Add a contract
await window.hapi.basket.service.addProductOrContractById.run('contract-abc', false)

Parameters

  • contractOrProductId (string) - the ID of the product or contract to add
  • isProduct (boolean) - true for a product, false for a contract

Error handling

The method throws an Error in the following cases, so wrap it in a try/catch:

try {
await window.hapi.basket.service.addProductOrContractById.run('product-123', true)
} catch (error) {
console.error('Failed to add to basket:', error)
}

Success Alerts: Upon successful addition of a product or contract, a success alert (AlertKey.productAddToBasket) will be displayed to the user.

Conflict scenarios

  • Duplicate items - if the item is already in the basket, the method logs a warning and does nothing
  • Contract group conflicts - a contractGroupConflictInfo modal is opened and the method throws a corresponding Error. Resolve by calling window.hapi.basket.service.removeContractsWithConflictingGroups.run() or window.hapi.basket.service.keepContractsWithConflictingGroups.run()
  • Outdated contracts - contracts with has_errors: true cannot be added and need to be recreated; the method throws a corresponding Error.
  • Bundle clashes - a confirmation modal (basketProductBundleParentClashConfirmation or basketProductBundleChildClashConfirmation) is shown when the item conflicts with existing bundles
  • CPA product clashes - a basketProductCPAClashConfirmation modal is shown when adding a CPA product to a non-empty basket or adding items when a CPA product is already present