SFRA Server-side Javascript - Source: app_storefront_base/cartridge/scripts/helpers/basketValidationHelpers.js menu

SFRA / Server-side JS / Source: app_storefront_base/cartridge/scripts/helpers/basketValidationHelpers.js

  1. 'use strict';
  2. var collections = require('*/cartridge/scripts/util/collections');
  3. var COHelpers = require('*/cartridge/scripts/checkout/checkoutHelpers');
  4. var ProductInventoryMgr = require('dw/catalog/ProductInventoryMgr');
  5. var StoreMgr = require('dw/catalog/StoreMgr');
  6. /**
  7. * validates that the product line items exist, are online, and have available inventory.
  8. * @param {dw.order.Basket} basket - The current user's basket
  9. * @returns {Object} an error object
  10. */
  11. function validateProducts(basket) {
  12. var result = {
  13. error: false,
  14. hasInventory: true
  15. };
  16. var productLineItems = basket.productLineItems;
  17. collections.forEach(productLineItems, function (item) {
  18. if (item.product === null || !item.product.online) {
  19. result.error = true;
  20. return;
  21. }
  22. if (Object.hasOwnProperty.call(item.custom, 'fromStoreId')
  23. && item.custom.fromStoreId) {
  24. var store = StoreMgr.getStore(item.custom.fromStoreId);
  25. var storeInventory = ProductInventoryMgr.getInventoryList(store.custom.inventoryListId);
  26. result.hasInventory = result.hasInventory
  27. && (storeInventory.getRecord(item.productID)
  28. && storeInventory.getRecord(item.productID).ATS.value >= item.quantityValue);
  29. } else {
  30. var availabilityLevels = item.product.availabilityModel
  31. .getAvailabilityLevels(item.quantityValue);
  32. result.hasInventory = result.hasInventory
  33. && (availabilityLevels.notAvailable.value === 0);
  34. }
  35. });
  36. return result;
  37. }
  38. /**
  39. * Validates coupons
  40. * @param {dw.order.Basket} basket - The current user's basket
  41. * @returns {Object} an error object
  42. */
  43. function validateCoupons(basket) {
  44. var invalidCouponLineItem = collections.find(basket.couponLineItems, function (couponLineItem) {
  45. return !couponLineItem.valid;
  46. });
  47. return {
  48. error: !!invalidCouponLineItem
  49. };
  50. }
  51. module.exports = {
  52. validateProducts: validateProducts,
  53. validateCoupons: validateCoupons,
  54. validateShipments: COHelpers.ensureValidShipments
  55. };