1.1.2 • Published 2 years ago

@ashish_agarwal/cs-ecommerce-abstraction v1.1.2

Weekly downloads
-
License
ISC
Repository
github
Last release
2 years ago

CS E-commerce Abstraction

Package Conception

This npm module has been created with a motive to provide abstraction to the apis used from various API layers in the CS ecommerce module. This module can be imported to projects as a package and the API's can be used to implement solutions on cs e-commerce module

Features

  • Easy to use API to support solution in Elastic and Pricing Service
  • Perform operations to SFDC and Elastic API directly

Package Usage

Installation

This package is only accessible through the NPM repository.

npm i @ashish_agarwal/cs-ecommerce-abstraction

IMP: create registry file (.npmrc) on root folder with the registry key from cs

Dependencies

All dependencies will be auto installed when the package is installed

API Specification

NPM Module Setup

Using API's

1.) First import the package and let's call it as CommerceAPIs wherever the API needs to be called.

// Importing the package as api
const CommerceAPIs = require("@ashish_agarwal/cs-ecommerce-abstraction");

2.) To perform operation on EAPI and SFDC, authentication details needs to be shared. For demostration purpose we are referring to store these credentials information in a dot_env (.env) file

clientId = //shared by cs security team for elastic api connectivity
ecomm_endpoint = // elastic endpoint shared by cs security team **DONT include https://**
sfdc_url = //your salesforce domain url connected to the elastic and pricing services
dispatcherHost = //dispatcher host url shared by cs security team **DONT include https://**
orgId = //salesforce org id
rsa_pvt_key = //rsa private key for the certificate shared between sfdc instance and heroku instance
catalogueId = //catalogue salesforce id published to the heroku **OPTIONAL** IF NOT provided, default catalogue id will be used by elastic apis to fetch data from ecommerce layer or catalogueId can be directly passed in as paramter to the apis.

3.) The module exports a class that abstracts all the required functions to be used as abstractions for making calls to elastic and pricing service restful apis. Each available APIs are described below

first of all create a new instance of the exported class to utilise its inbuild apis.

  /** create this object from client credentials **/
  const sfdcConfig = {
      SFDC_URL : process.env.sfdc_url
  };

  /** create this object from stored secured credentials for heroku**/
  const elasticConfig = {
      ClientId : process.env.clientId,
      PrivateKey : process.env.rsa_pvt_key,
      Endpoint : process.env.ecomm_endpoint
  };

  /** create this object from stored secured credentials for pricing service**/
  const pricingConfig = {
      dispatcherHost : process.env.dispatcherHost,
      SFDCOrgId : process.env.orgId
  };

  const commerceAPI = new CommerceAPIs(sfdcConfig, elasticConfig, pricingConfig);

NOTE: The default basepath is set to be /services/current which can be overwritten to /sevices/vesrionX.0 by below code

  commerceAPI.setAPIVersion('elastic', 'v1');

a.) List catalogues - The api returns a list of all available catalogues. The return type is an object which contains status and body from the api call to /services/${apiVersion}/catalogues where apiversion is 'current' by default unless overridde by calling commerceAPI.setAPIVersion(server, version) api.

  await commerceAPI.catalogues().get();

b.) get catalogue by Id - The api returns the details about the passed in catalogue Id. The return type is an object which contains status and body from the api call to /services/${apiVersion}/catalogue/{catalogueId}

  await commerceAPI.catalogue(${catalogueId}).get();

c.) get categories - The api returns the categories that belong to the specified catalogue or from the default catalogue if catalogueId is not passed in to the api. The return type is an object which contains status and body from the api call to /services/${apiVersion}/.../categories

  await commerceAPI.categories(${catalogueId}).get();

Use showAll parameter to include categories in the result inactive at the time of the query, as defined by their start and end dates. Use effectiveDate to return active categories on the specified date. showAll and effectiveDate are mutually exclusive, and cannot be combined in a single request.

  /*${catalogueId} is optional*/
  //using showAll and showEffectiveAtDate apis to set query params
  await commerceAPI.categories(${catalogueId}).showAll().get();
  await commerceAPI.categories(${catalogueId}).showEffectiveAtDate('2022-05-21').get();

  //passing parameters direct using addQueryParam api
  await commerceAPI.categories(${catalogueId}).addQueryParam('showAll',true).get();
  await commerceAPI.categories(${catalogueId}).addQueryParam('effectiveDate','2022-05-21').get();

d.) get facets - The api returns the facets that belong to the specified catalogue or from the default catalogue if catalogueId is not passed in to the api. The return type is an object which contains status and body from the api call to /services/${apiVersion}/.../facets

  await commerceAPI.facets(${catalogueId}).get();

The response returned is a paginated response, which means the facets can be filtered using navigation parameters limit (how many facets are returned per page), and pageNumber (the number of the page returned). The query parameters are combined with AND (&). By default, the API returns 500 facets per page. The maximum number returned is 1000 facets per page. Using the limit query parameter to get more facets per page than the set maximum will not have the intended effect. Instead, the set maximum will apply.

  /*${catalogueId} is optional*/
  //using limit and pageNumber apis to set query params
  await commerceAPI.facets(${catalogueId}).limit(20).get();
  await commerceAPI.facets(${catalogueId}).limit(80).pageNumber(2).get();

  //passing parameters direct using addQueryParam or addQueryParams api
  await commerceAPI.facets(${catalogueId}).addQueryParam(limit,20).get();
  await commerceAPI.facets(${catalogueId}).addQueryParams({limit:20, pageNumber:2}).get();

e.) get offers - The api returns the offers that belong to the specified category or all offers from a specified or default catalogue. The api accepts categorId and catalgueId as optional input parameters. The return type is an object which contains status and body from the api call to /services/${apiVersion}/.../offers

  await commerceAPI.offers(${categoryId}, ${catalogueId}).get();

The response returned is a paginated response, which means the offers can be filtered using navigation parameters limit (how many facets are returned per page), and pageNumber (the number of the page returned). By default, the API returns 10 offers per page. The maximum number returned is 20 offers per page. Using the limit query parameter to get more offers per page than the set maximum will not have the intended effect. Instead, the set maximum will apply. Additonal query parameters include sku, productSkus, productType, productSubType, offer_type, name, commercialProductTypes, commercialProductRoles, offerCode, and any other attribute that was marked as a facet during product configuration. For more details refer - API Specifications

Use showAll parameter to include products in the result inactive at the time of the query, as defined by their start and end dates. Use effectiveDate to return active products on the specified date. showAll and effectiveDate are mutually exclusive, and cannot be combined in a single request.

  /*${catalogueId} is optional*/
  //using limit and pageNumber apis to set query params
  await commerceAPI.offers(${catalogueId}).limit(20).get();
  await commerceAPI.offers(${catalogueId}).limit(80).pageNumber(2).get();

  //passing parameters direct using addQueryParam or addQueryParams api
  await commerceAPI.offers(${catalogueId}).addQueryParam(limit,20).get();
  await commerceAPI.offers(${catalogueId}).addQueryParams({Model:'IPhone', Color:'black', productSkus:'offer_full_1,offer_special_1'}).get();

f.) get offer, child products, offer specializations, child product group(s) and child products that belongs to a specified product group. These apis accepts offerId as a mandatory input parameter. The return type is an object which contains status and body from the api call to /services/${apiVersion}/offer/${offerId}/...

Use showAll parameter to include products in the result inactive at the time of the query, as defined by their start and end dates. Use effectiveDate to return active products on the specified date. showAll and effectiveDate are mutually exclusive, and cannot be combined in a single request.

Supported query parameters for each of these api variants are described at - API Specifications

  //get offer be catalgueItem Id
  await commerceAPI.offer(${offerId}).get();
  //Retrieves child products related to the specified catalogue item (offer, package or package item). A single level of child products is returned in the response.
  await commerceAPI.offer(${offerId}).childProducts().get();
  //Retrieves catalogue item's specialisations. Catalogue item is defined by the offerId parameter. Only master and variant products have specialisations.
  await commerceAPI.offer(${offerId}).specializations().get();
  //Retrieves all product groups available for the specified catalogue item. Since packages do not have product groups per se, this route is not supported for packages.
  await commerceAPI.offer(${offerId}).childProducts().groups().get();
  //Retrieves all product groups available for the specified catalogue item. Since packages do not have product groups per se, this route is not supported for packages.
  await commerceAPI.offer(${offerId}).childProducts().byGroup(${productGroupId}).get();


  //using query parameters along with these apis
  await commerceAPI.offer(${offerId}).showAll().get();
  await commerceAPI.offer(${offerId}).childProducts().showEffectiveAtDate('2022-05-21').get();

g.) Basket APIs: create and update a basket, get basket(s), get and update basket fields and custom prices, empty a basket, push basket to salesforce. The return type is an object which contains status and body from each of these api calls.

Supported query parameters for each of these api variants are described at - API Specifications

  /*create a basket -- If accountId is not passed it will create an anonymous basket not attached to any account. request body can contain optionally a catalogueId and customPrices array. {
                                                      "catalogueId": "a1558000000pTk5AAE",
                                                      "customPrices": [
                                                        ...
                                                      ]
                                                    }*/
  await commerceAPI.basket({accountId:${ecommAccountId}}, requestBody).post();

  //attaching an anonymous basket to an account
  await commerceAPI.basket({basketId: ${ecommerceBasketId}}).attachToAccount({accountId:${ecommAccountId}}).post();

  //Fetches all baskets filtered by certain parameters. This route must be called with at least one of these two query parameters: customerIdentifier (Customer identifier set on a basket via special custom field) and accountId. Any filtering attempted without either of the two parameters included will throw an error. The response returned is a paginated response, which means the baskets can be filtered using navigation apis limit() (how many baskets are returned per page) and pageNumber() (the number of the page returned). By default, API returns 5 baskets per page. The default maximum number of baskets returned per page is 10.
  await commerceAPI.baskets({customerIdentifier:${customerIdentifier}, accountId:${ecommAccountId}}).limit(10).pageNumber(3).get();

  //Get a basket by basketId. This route also provides information on basket content changes by using the showDelta parameter. The basket returned by such a call will have an additional delta array property. For more details on delta please refer [API Specifications](https://cres.cloudsense.com/elastic/commerce-apis.html#tag/Basket/paths/~1basket~1{basketId}/get). accountId is not a mandatoey parameter to fetch a basket.
  await commerceAPI.basket({basketId:${ecommbasketId}, accountId:${ecommAccountId}}).showDelta(true/false).get();

  //retrieve the whole set of custom basket fields put on the basket. They are all returned as key-value pairs inside a JSON object.
  await commerceAPI.basket({basketId:${ecommbasketId}, accountId:${ecommAccountId}}).fields().get();

  /*updates a set of custom fields on the basket. The set is sent in the payload as a JSON with one or several key-value pairs. The response contains the fields that were set and their new values. sample customFieldJson - {
                                                                                              "customerIdentifier": "m_marines@gmail.com",
                                                                                              "customer_type__c": "Private Individual",
                                                                                              "Opportunity__c": "26bf352d-5643-46b3-929d-5f29bbb52628"
                                                                                            }*/
  await commerceAPI.basket({basketId:${ecommbasketId}, accountId:${ecommAccountId}).fields(${customFieldsJson}).put();

  //Empty a basket- This api will delete all the offers added from a given basket
  await commerceAPI.basket({basketId:${ecommbasketId}, accountId:${ecommAccountId}}).clearBasket();

  //This api will push an EAPI basket into Salesforce.com. The route will not create an order but it will put the basket into the non-Closed Won status that will enable users to continue working on the basket in Salesforce.com. The payload can contain ecomReference and orderId (both optional). If it is not provided in the request, the system will generate them.
  await commerceAPI.basket({basketId:${ecommbasketId}, accountId:${ecommAccountId}}).pushBasket(payload);

  //update or delete customPrices from a given basket. Additional query parameter include-response-body	can be passed to this api using addQueryParam(key, value) api.When this param is passed as true, the response body is provided, otherwise 204 - No Content is returned.
  await commerceAPI.basket({basketId: req.query.basketId, accountId: req.query.accountId}).customPrices('[...]').put();
  await commerceAPI.basket({basketId: req.query.basketId, accountId: req.query.accountId}).customPrices().del();

h.) Basket Item APIs: create, update and delete a item in a given basket. The api accepts offerId mandatory input parameters. The return type is an object which contains status and body from each of these api calls.

More details on each of these api callouts are described at - API Specifications

  /*add a offer/item to a given basket defined by basketId in the parameter, accountId is optional. request body should contain the catalogueItemId or the catalogueItemSku and optionally the customPrices array. {
                                                                                    "catalogueItemId":  "0ebd4b07-aa63-4f16-88ad-ac4b2ab57cb5",
                                                                                    "customPrices": [...],
                                                                                    "quantity": 2
                                                                                  }*/
  await commerceAPI.basket({basketId:${ecommBasketId}, accountId:${ecommAccountId}}).addOffer(${requestbody});

  //Remove a basket item (either an offer or a package) from the basket. This will remove the basket item entirely. Pass the Basket item (offer or package) UUID (baasId) as input to identify the basket Item to be deleted.
  await  commerceAPI.basket({basketId:${ecommBasketId}, accountId:${ecommAccountId}}).deleteOffer(${baasOfferId});

  //All compatible replacement offers can be found by fetching all offers (from either the default or a specific catalogue) using the catalogueItemId (fetchCompatibleReplacements({transitingFrom:"b9ccc151-af10-482a-bdcd-d3f4249f9077"}) or offerSku with the offerCode, (example:fetchCompatibleReplacements({offerSku:"PC-111", offerCode:"gold"})
  await commerceAPI.fetchCompatibleReplacements({offerSku:${offerSku}, offerCode:${offerCode}, catalogueItemId:${catalogueItemId}}, categoryId, catalogueId);

  //An item in the basket can be replaced with another offer which share the same product definition or upgraded product definition. More details on it [API Specifications](https://cres.cloudsense.com/elastic/commerce-apis.html#tag/Offerbasket-item/paths/~1basket~1{basketId}~1offer~1{baasOfferId}/patch)
  await commerceAPI.basket({basketId:${ecommBasketId}, accountId:${ecommAccountId}}).replaceBasketItem({"basketItemId": "{{baasItemId}}", "catalogueItemId": "{{selectedOfferId}}", "offerSku": "{{selectedsku}}", "offerCode": "", "preview": false, "omitDefaultAddons": false});