GithubHelp home page GithubHelp logo

salesforcecommercecloud / pwa-kit Goto Github PK

View Code? Open in Web Editor NEW
266.0 24.0 120.0 196.16 MB

React-based JavaScript frontend framework to create a progressive web app (PWA) storefront for Salesforce B2C Commerce.

Home Page: https://developer.salesforce.com/docs/commerce/pwa-kit-managed-runtime/guide/pwa-kit-overview.html

License: BSD 3-Clause "New" or "Revised" License

JavaScript 82.74% HTML 0.18% TypeScript 16.01% Handlebars 1.07% CSS 0.01%
pwa react monorepo progressive-web-app ecommerce javascript storefront nodejs salesforce salesforce-developers

pwa-kit's People

Contributors

adamraya avatar agurumurthy96 avatar alexvuong avatar bendvc avatar bfeister avatar breadadams avatar bredmond-sf avatar cbrother-csu avatar cc-prodsec avatar clavery avatar danechitoaie avatar ecrobertengel avatar hajinsuha1 avatar jkeanesf avatar joeluong-sfcc avatar johnboxall avatar kenjush avatar kevinxh avatar kieran-sf avatar lizcross avatar olibrook avatar raiyaj avatar rsexton404 avatar sejal-salesforce avatar shethj avatar snyk-bot avatar vcua-mobify avatar vmarta avatar wjhsf avatar yunakim714 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pwa-kit's Issues

[RFC] Improved version

Hello guys. I have an internal request to build a POC using your solution for a PWA kit. So sorry for bringing this through the issue, but I haven't seen a place for RFCs.
So far, you have done an awesome job with the project, but as it seems lately the progress has been stagnating for a while and I think there probably are places where the quality can be a tad improved.

We have an ambitious team that is assigned to explore your solution and build an improved version of it (with better data fetching, typescript, and the list goes on) that can be used as a boilerplate for all the new customers we're going to build using it, so I thought why can't we join forces together? I want to make it clear that I'm speaking specifically for the FE part of the package, since the BE part is doing a great job so far.

I don't want any commitments or contributions from your side since we have nothing on the table yet, but would appreciate knowing if you would accept a PR if you eventually like the job done or at least know if there are some red-lines that you have so we comply by them.

Thank you very much for your time!

[FEATURE] OCAPI has a way to get the content of Page designer?

We want to use PWA kit to refactor the website; but we now have a problem, OCAPI does not provide an interface to get the content of Page designer.

We tried to use the PageMgr.serializePage(page.ID, null) method, but found an error

Can't compile script '[DEBUGGER EXPR: ]'

wainclude url="/on/demandware.store/Sites-xxx-xxx-Site/en/__SYSTEM__Page-Include?cid=homepage&params=%7b%22custom%22%3a%22%22%2c%22aspect_attributes%22%3anull%7d&ot=JSON"

image

The existing website uses the SFRA framework, and the home page of the website about us and the FAQ page are all created using Page designer, and customers have been using Page designer to manage and maintain pages. We can't abandon Page designer.

Is there any way to solve the compatibility problem between PWA kit and Page designer

[Retail App] Show applied promotion codes case sensitive

The Cart and the Checkout pages show the applied promotions code in uppercase, this code is case sensitive, we should show the code using the original format.

STRS
add orderLevel promocode
view cart and checkout pages

Expected Results
promotions show case sensitive promo code (orderLevel)

Actual Results
promotions show upper case promo codes (ORDERLEVEL)

@W-9491413@

Japanese text was overwritten by default text in code at pushing bundle

Is your feature request related to a problem? Please describe.
When I use Japanese text as default in package.json and try to push with command npm run push , whole ja-JP.json text was overwritten by default text in code.

Describe the solution you'd like
Removing formatjs extract when pushing. or merge existing json and text in code.

[BUG] black-friday-hackathon | Windows 10

Summary

The app displays a 404 error after the initial loading screen on Windows 10

Steps To Reproduce

  1. npx [email protected] --preset retail-react-app-demo
  2. npm i
  3. npm start

Expected result

The retail react app should load normally

Actual result

Error 404 page displayed after initial loader
error

System Information (as applicable)

Browser: Chrome 97.0.4692.99
Node version: 14.18.2
pwa-kit version: 2.0.0-dev
Desktop OS: Windows 10
Mobile Device Info:

Additional information

error2

[Retail App] Order summary prices on check out page misaligned on mobile

@W-9872562@

Steps to Reproduce

  • Go to https://pwa-kit.mobify-storefront.com/ on a mobile device.
  • Add an item to cart.
  • Go to Cart > Checkout page.
  • Scroll down to Order Summary.
  • Click the arrow to see the item in cart.
  • The price is misaligned.

image

Expected Results

The price should display properly aligned.

[BUG] - Error during login - Invalid channel_id

I have a very barebones copy of the PWA kit that a colleague cloned. I set it up on my local machine, and I am getting the following error when I try logging in.

image

In the code I noticed the channel_id is being passed the SiteId, and from a data perspective it looks correct.

Is there a known issue around this? Any documentation about the channel_id? I've searched through documentation and can't find anything about what the value should be, or any information about configuring it in SFCC.

Steps To Reproduce

Attempt to login.

Expected result

User is authenticated.

Actual result

Error seen above

System Information (as applicable)

Browser: Chrome 97.0.4692.99
Node version: 14.18.3
pwa-kit version: 1.2?
Desktop OS: Windows
Mobile Device Info:

Error upon deployment - Managed Runtime

Hi there,
I am deploying my PWA project on managed runtime, which is working fine locally but throwing error upon MR after deployment. I have also provided the Proxy Configs in Environment Settings.
Screenshot is attached for the reference. Any help would be appreciable. Thanks

Screenshot 2022-03-08 at 1 03 40 PM

[BUG] Reset Password is not working

Summary

When using "Reset Password" the app returns the error "Your access-token is invalid and could not be used to identify the API client.". This happens regardless if the email is known to the system or not.

screenshot 2022-01-28 um 11 10 16

Steps To Reproduce

Expected result

  • no error message

Actual result

  • error message "Your access-token is invalid and could not be used to identify the API client."

System Information (as applicable)

Browser: Chrome Version 97.0.4692.99
Node version:
pwa-kit version: 1.3
Desktop OS:
Mobile Device Info:

Happens on the official test system, on our test system and locally.

Additional information

I tried to trace down this to myself but was not successful.

It seems that the underlying call

https://{{short_code}}.api.commercecloud.salesforce.com/customer/shopper-customers/v1/organizations/{{organization_id}}/customers/password/actions/create-reset-token?siteId={{site_id}}

is executed with the SLAS token and this does not work. I can reproduce the same error in Postman.

The documentation actually says to use the AM based token (https://account.demandware.com/dwsso/oauth2/access_token). But this did also not work for me and returns

"Your access-token is valid, but you have no permissions to access the resource.".

The related OCAPI permission is set but there is no related AuthZ Scope that could be set.

[FEATURE] Add build process for CSR only for use in hybrid apps

Is your feature request related to a problem? Please describe.
PWA kit is currently designed to be used with SRR, which is good for website scenarios, but leads to some problems when you want to use it in hybrid app as with Cordova.

Describe the solution you'd like
A second way to build pwa kit so both client and server js get complied for CSR only use (with an index.html file that can be used as starting point for hybrid app). Main problem is the reliance on server side rendered data to be always present in the current setup. Best would be to have the basic implementation for CSR in SDK and based on this a working example in PWA. It should be possible to switch between SSR and CSR builds by configuration.
The solution should not be a complete hybrid app setup, including the example pwa into a wrapper like cordova could be a readme example.

Describe alternatives you've considered
Create native app version using ReactNative

Additional context
I created a prove of concept that PWA kit can be adjusted to render on client side only using an index.html file as starting point.
This POC uses PWA as base without adjusting the SDK, calls to SDK code sometimes need to overriden by custom code. Problems faced during implementation of the POC:

  • Reliance on server side rendered data > most data can be omitted if App Component loads data on the first access > _app needs adjustments to load data
  • window.Progressive needs to be present as well as default locale
  • Icons > need to have different webpack setup to include icons on clientside
  • Server needs to send index.html on all requests

[FEATURE] Make nodejs inspect configurable

Is your feature request related to a problem? Please describe.
Currently nodejs inspect can not be configured. It starts default with 127.0.0.1:9229. But if you run the frontend in a docker container, you can not reach it. The IP must be changed into 0.0.0.0 to make it works. This is currently not possible. Or if you have a second app already running which is using 9229, then we have no possibility to change the port for inspect.

Describe the solution you'd like
Please add to pwa-kit-dev start command two new parameters like inspectIP and inspectPort

Describe alternatives you've considered
Found no alternatives.

Sample

program
        .command('start')
        .description(`develop your app locally`)
        .addOption(
            new program.Option('--inspect', 'enable debugging with --inspect on the node process')
        )
        .addOption(new program.Option('--noHMR', 'disable the client-side hot module replacement'))
        .action(({inspect, noHMR}) => {
            execSync(
                `node${inspect ? ' --inspect=0.0.0.0:9229' : ''} ${p.join(process.cwd(), 'app', 'ssr.js')}`,
                {
                    env: {
                        ...process.env,
                        ...(noHMR ? {HMR: 'false'} : {})
                    }
                }
            )
        })

[BUG] Search suggestions only returns category type

Summary

When entering a query into the megamenu search the 'suggested' result options appear to only return category type suggestions though there are other options including 'brand' and 'product' type suggestions.

Note that when the query is actually executed the search results themselves DO appear to be accurate.

Steps To Reproduce

Retail React App: in search megamenu type 'cardigan'.

Expected result

'cardigan' should match at least one product name and so product names should be suggested in the megamenu dropdown

Actual result

No suggestions are returned as 'cardigan' does not match any categories

System Information (as applicable)

Browser: Not browser specific
Node version:
pwa-kit version: Latest retail react app
Desktop OS:
Mobile Device Info:

image

[BUG] findInProjectThenSDK doesn't resolve correct path

Summary

We refactored our project to a MonoRepo with npm workspaces. So pwa-kit-dev in root node_modules folder. If we try to build the project, we get a lot of errors with wrong module paths. So all aliases and and rules in webpack config are broken because these are using findInProjectThenSDK and the else case creates in the path a "node_modules/node_modules", so one node_modules is too much.

Steps To Reproduce

1.) Create a npm workspaces project
2.) Add as one package the pwa-kit-app
3.) npm install in root folder
4.) Try npm run build in pwa-kit-app package

Expected result

Correct alias and rules paths.
Sample: /workspaces/my-project/node_modules/react

Actual result

Paths have node_modules as path segment 2 times currently, which is broken.
Sample: /workspaces/my-project/node_modules/node_modules/react

EDIT: And a last problem in webpack config.js of pwa-kit-dev. Line 333
fs.existsSync(resolve(projectDir, 'node_modules', 'pwa-kit-react-sdk')) &&

pwa-kit-react-sdk can not be found in root node_modules folder. I think if findInProjectThenSDK is fixed the resolve() should be replaced by findInProjectThenSDK()

[BUG] Support multivalue query parameters

URLs may contain multivalue query parameters. That is a parameter with the same name may appear multiple times in a query string: ?q=123&q=abc.

As an example, SCAPI's product search API allows you to use the refine parameter multiple times to set a number of refinements on a search.

Today, multiple values are discarded and only the last value is available on Express code.

This is because the version of aws-serverless-express we're using doesn't correct forward the Lambda event to the Express server: CodeGenieApp/serverless-express#214

This issue only impacts code running on Managed Runtime, it doesn't appear locally, because we don't use the lib locally.

[BUG] Phone number should display a numeric keyboard on Mobile devices @W-9871940@

Summary

On the Account Profile Page, editing the phone number should bring up a number keyboard on mobile devices.

Steps To Reproduce

  • Log in to an account on a mobile device
  • Navigate to /account/profile
  • Click edit your profile
  • Click on the phone number field
  • It displays the alphanumeric character keyboard.

Expected result

It should show the numeric keyboard on mobile devices.

@ W-9871940 @

[BUG] Breadcrumb links have not correct url on product detail

Summary

Breadcrumb links have not correct url on product detail. Locale is missing in the urls.

Steps To Reproduce

  • Checkout project in version 1.4.0-dev develop branch
  • npm ci
  • npm run start
  • Open https://localhost:3000 in your browser
  • Go to category womens
  • Click on a product to reach product detail
  • Click on link Womens in Breadcrumb
  • Error is rising with page not found

Expected result

Can click on a link in the PDP Bread Crumb and reaching the correct page with current selected locale.

Actual result

On clicking a link in the Breadcrumb on product detail a page not found error is showing up.

System Information (as applicable)

Browser: Microsoft Edge 97
Node version: Node 14
pwa-kit version: 1.4.0-dev develop branch
Desktop OS: macOS Montery
Mobile Device Info: -

Additional information

x

Proxy remove query strings

I deployed PWA Kit to Managed Runtime.
But I could not see product list on MR server because refine=cgid%3Dmens-clothing-suits query was removed when requesting to CC server.
Does anyone have any idea?

[On my local(working well)]

Request URL:
スクリーンショット 2021-09-30 17 23 03

Response x-proxy-request-url:
スクリーンショット 2021-09-30 17 23 16

[On MR server(not working well)]

Request URL:
スクリーンショット 2021-09-30 17 23 34

Response x-proxy-request-url:
スクリーンショット 2021-09-30 17 23 52

[BUG] 502 Bad Gateway when sending request to SCAPI

Summary

When application sends request, for example, to https://{envID}.mobify-storefront.com/mobify/proxy/api/customer/shopper-customers/v1/organizations/{orgID}/customers?siteId={siteID}, 502 Bad Gateway (HTML response) received instead of 400 (JSON response). This probably happens because the cookie size exceeds the limit (please notice the token cookie present).

Steps To Reproduce

(Hybrid solution that uses cookies, possibly relates to this feature - link)

Try to register the customer with an invalid email address

OR

cURL

curl 'https://pwa-kit.mobify-storefront.com/mobify/proxy/api/customer/shopper-customers/v1/organizations/f_ecom_zzrf_001/customers?siteId=RefArchGlobal' \ -H 'authority: pwa-kit.mobify-storefront.com' \ -H 'accept: */*' \ -H 'accept-language: en-US,en;q=0.9' \ -H 'authorization: Bearer {BEARER_TOKEN}' \ -H 'cache-control: no-cache' \ -H 'cookie: oid=f_ecom_zzrf_001; usid=1a75930c-5544-4c7b-ab4d-1baf9f8ab81f; cid=abkuc1lrIXkekRlrsYlaYYwXBG; __cq_dnt=1; dw_dnt=1; dwanonymous_b5d8a8e2b741ecb26e2f400a02c69ec5=abkuc1lrIXkekRlrsYlaYYwXBG; token=Bearer%20ey{BEARER_TOKEN}; cc-nx-g=uY5XxvkapEIBojobDMSV0HdquFy8Sbq0kbqXTpWMgnI; dwsid=-J97Xy1NEodXBHEaF8y558J3_mxhRL8TzufsmbsnUD9ltB4oVeLivZFWNULSK34S8RnXIak0mkJYbE25oWY8sg==' \ -H 'content-type: application/json' \ -H 'origin: https://pwa-kit.mobify-storefront.com' \ -H 'pragma: no-cache' \ -H 'sec-ch-ua: "Chromium";v="104", " Not A;Brand";v="99", "Google Chrome";v="104"' \ -H 'sec-ch-ua-mobile: ?0' \ -H 'sec-ch-ua-platform: "Windows"' \ -H 'sec-fetch-dest: empty' \ -H 'sec-fetch-mode: cors' \ -H 'sec-fetch-site: same-origin' \ -H 'user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36' \ --data-raw '{"customer":{"firstName":"sdfsdfsd","lastName":"sdfsdfsdf","email":"[email protected]","login":"[email protected]"},"password":"3rsdfsdfE#"}' \ --compressed

Expected result

Response with 400 code & JSON containing "Invalid Email" message

Actual result

502 Bad Gateway HTML Response

System Information (as applicable)

Browser: Version 104.0.5112.102 (Official Build) (64-bit) (although doesn't matter actually)
Node version: v14.18.0
pwa-kit version: 2.0.0
Desktop OS: Windows
Mobile Device Info: -

Additional information

This may be important: if I try to register a customer with a valid email address (although all request data stays the same), the correct 200 response is returned and the customer becomes logged in.

[BUG]Filter link on search result is not working

Summary

The filter on search page is not working.

Steps To Reproduce

Expected result

  • The filter on the search result page should filter items correctly

Actual result

  • The item is not being filtered, but it is directed to a 404 page

System Information (as applicable)

Browser:
Node version:
pwa-kit version:
Desktop OS:
Mobile Device Info:

Additional information

image

image

Unable to connect PWA Kit Project with my Sandbox instance

I have a created project using command npx pwa-kit-create-app --outputDir <project-name> and then changed the values of clientId, organizationId, shortCode, siteId in app/commerce-api.config.js file according to my sandbox instance. But I am unable to run the project, I have checked Commerce API's on postman and Commerce API's are working fine. I am seeing this error when visit http://localhost:3000/:

Sorry, there is a problem with this page 😔
To continue, go back home.

Go Back Home
Error: Client Authentication failed
at //build/ssr.js:57072:15
at Generator.next ()
at asyncGeneratorStep (//build/ssr.js:64:24)
at _next (//build/ssr.js:86:9)
at processTicksAndRejections (internal/process/task_queues.js:95:5)

Can anyone help here? I am using "pwa-kit-react-sdk": "1.0.0".

[BUG] - Getting error on windows

With the reference of following screenshot, I am unable to generate the project with command (npx pwa-kit-create-app --outputDir ...) on windows. I am providing valid creds upon creating the project.
Anyone faced this issue?

image

[BUG] Product tile skeletons should represent the same size as the content for no search results

Summary

On the no search results found page, the size of the top sellers skeletons are not the same as the size of the content that is loaded after. The skeletons should match the size of the content being loaded in them

Steps To Reproduce

  • Search for "space" or something with no results
  • See loading skeletons in product scroller

Expected result

  • Skeletons should represent the size of the content that will be displayed

Actual result

  • Skeletons are much smaller than the size of the displayed content

Additional information

Screen Shot 2022-02-08 at 3 00 30 PM
Screen Shot 2022-02-08 at 3 00 39 PM

@ W-9818382 @

[Retail App] Shipping method description overflows the price section

@W-9871674@

Description

Shipping method description overflows the price section on check out page

Steps to Reproduce

  • Add an item to cart.
  • Go to cart and checkout.
  • Go over the checkout steps to Shipping & Gift Options.
  • Observe that the super saver description overflows under the price section.

Expected Behavior

The description should not overflow under the price section and should be cut into another line.

Actual Behavior

image

[QUESTION] Roadmap for ReactQuery and ServerContext features

Hello everybody,
we are looking every time over new PRs in the PWA Kit project to see the road of the project, especially TechStack wise.
So we saw the use of ReactQuery for commerce-sdk-react and the new ServerContext to replace getProps in future.

This is a really good decision and for a current running customer project, we refactored our PageDesigner integration and THIRD Party API integrations to use ReactQuery.

But currently the SSR part with Hydration is missing in the PWA-Kit implementation. I see in the PRs you are working on this. Will these features coming with the next release?

Thx.

Best regards René

[Retail App] Price filter radio button doesn't reset while switching pages

Summary

Once the selection has been made, the price filter radio button does not reset while switching to a different page. For example, if a user selects the filter as £0 - £19.99 in the Women's page, after switching to the Men's page, the price filter radio button shows the same selection, but the search results displayed show the default results.

Steps To Reproduce

  1. Visit https://pwa-kit.mobify-storefront.com/en-GB
  2. Click Women's category page
  3. Change the price filter to £0 - £19.99
  4. Switch to Men's category page

Expected result

The price filter radio button should clear after the page is switched

Actual result

The price filter radio button uses the previous page value

System Information (as applicable)

Browser: Chrome
Node version: 14
pwa-kit version: 1.2.0
Desktop OS: MacOS
Mobile Device Info: iPhone 12

Additional information

Untitled.mp4

[BUG] The PLP does not show the correct amount of skeletons when loading filter results

Summary

On the PLP, when a user selects a filter, only one product tile skeleton appears. The amount of skeletons that should appear should be equal to the amount of product tiles that can be visible on the screen

Steps To Reproduce

  • Go to PLP
  • Select a filter
  • See skeleton of only one production tile

Expected result

The product tiles are all replaced with skeletons while the filter is processing.

Actual result

Only the first product tile is replaced with a skeleton. All other product tiles vanish and do not show a skeleton.

Additional information

Screen Shot 2022-02-08 at 3 24 27 PM

Screen Shot 2022-02-08 at 3 24 34 PM

@ W-9818340 @

RFC: `commerce-sdk-react` - SCAPI React.js hook library

Please feel free to leave comments / feedback in this issue! Thank you!

Summary

Here, we are proposing to introduce a new package in the pwa-kit monorepo - commerce-sdk-react. This library contains a collection of easy-to-use React.js hooks that integrates Salesforce Commerce Cloud B2C Commerce API (known as SCAPI) in a PWA Kit project.

Background

Today, the retail react app template is the starting point for PWA Kit project. The SCAPI integration source code lives inside the template. When a PWA Kit project kicks off, the first thing developers do is to generate a new project, via npx pwa-kit-create-app.

Problem

Once a project is generated, there is no way for a project to receive bug fixes / new updates.

Proposal

We want to extract re-usable code as much as possible from the template and move them into dedicated libraries and distribute and maintain the library via npm.

The new library commerce-sdk-react aims to provide a SCAPI integration library in the form of React components and hooks. The library leverages the commerce-sdk-isomorphic package internally.

Features

  • declarative promise resolution and data fetching
  • SSR (yes, hooks that run on the server side!, see #664)
  • Built-in cache and request deduplication
  • Authentication & Token management
  • TypeScript
  • and more...

Public Interface

1. The <CommerceApiProvider /> Component

This is a react component that wraps your entire application. It is used to configure the library as well as providing access to the API clients and hooks throughout the entire react application. Typically in a PWA kit project, you will import the component in the AppConfig special component.

The component takes the following props:

  • proxy (the path for your SCAPI proxy)
  • organizationId
  • clientId
  • siteId
  • shortCode
  • locale
  • currency

Example: /app/components/_app-config/index.jsx

import React from 'react'
import {CommerceAPIProvider} from 'commerce-sdk-react'

const AppConfig = ({children}) => {
    return (
        <CommerceAPIProvider
            proxy={`/mobify/proxy/api`}
            organizationId="f_ecom_xxxx_xxx"
            clientId="xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
            siteId="xxxx"
            shortCode="xxxx"
            locale="en-US"
            currency="USD"
        >
            {children}
        </CommerceAPIProvider>
    )
}

export default AppConfig

2. The useCommerceApi hook

This is a low level hook that gives developer access to the Commerce API clients. The return value is an object whose properties are initialized API clients, instantiated from individual commerce-sdk-isomorphic library classes.

Example: use the hook to get access to the api clients

import React, {useEffect} from 'react'
import {useCommerceApi} from 'commerce-sdk-react'

const MyComponent = () => {
    const [data, setData] = useState({})
   const api = useCommerceApi()
   
   useEffect(() => {
     const res = api.shopperProducts.getProduct()
     if (res) {
        setData(res)
     }
   }, [])
   
   return ...
}

Note: you probably won't be using this low level hook directly most of the time. It is an escape hatch for when the other API specific hooks cannot meet your needs.

3. The Query Hooks

Query Hook is a concept, it describes a type of hooks that are used to fetch data. Typically these hooks make HTTP GET requests. e.g. fetch a single product.

The query hooks data will be cached locally and if you have multiple same query hooks that in used inside different react component, the requests will be de-duplicated.

Query hooks follow a similar signature that looks like:

Example:

import React, {useEffect} from 'react'
import {useProduct} from 'commerce-sdk-react/ShopperProducts'

const MyComponent = () => {
    const {data, isLoading, error} = useProduct({parameters: {id: '37478392M'}})
    if (isLoading) return "Loading..."
    if (error) return `Something went wrong: ${error.message}`
   return <div>{data.name}</div>
}

Query Hook examples:

  • ShopperProduct API: useProducts, useProduct, useCategories, useCategory
  • ShopperCustomer API: useCustomer, useCustomerAddress, useCustomerBaskets, useCustomerOrders, useCustomerPaymentInstrument, etc
  • ShopperSearch API: useProductSearch, useSearchSuggestions
  • etc...

4. The Action Hooks

Action Hook is a concept, it describes a type of hooks that are used to mutate data. Typically these hooks make HTTP POST/PUT/DELETE requests. e.g. add an item to the basket. These hooks are usually invoked by user interactivity such as clicking a button. Action hooks follow a similar signature that looks like:

In addition to the return values such as data, isLoading, it returns an execute function, invoking this function will use the underlying isomorphic api client to send the request.

Unlike the query hooks, the action hook results are not cached globally. The results are local state. Calling the action hooks N times will send N network requests.

Example:

import React, {useEffect} from 'react'
import {useShopperBasketsAction} from 'commerce-sdk-react/ShopperBaskets'

const MyComponent = () => {
    const createBasket = useShopperBasketsAction('createBasket')
    if (createBasket.isLoading) return "Loading..."
    if (createBasket.error) return `Something went wrong: ${error.message}`
   return <button onClick={() => createBasket.execute({parameters: {items: [...]}})}>{data.name}</button>
}

Action Hook examples:

  • ShopperBasket API: useShopperBasketsAction
  • etc...

list of actions:

export enum ShopperBasketActions {
    addItemToBasket = 'addItemToBasket',
    removeItemFromBasket = 'removeItemFromBasket',
    updateItemInBasket = 'updateItemInBasket',
    createBasket = 'createBasket',
    mergeBasket = 'mergeBasket',
    updateBasket = 'updateBasket',
    updateBillingAddressForBasket = 'updateBillingAddressForBasket',
    addCouponToBasket = 'addCouponToBasket',
    removeCouponFromBasket = 'removeCouponFromBasket',
    updateCustomerForBasket = 'updateCustomerForBasket',
    addPaymentInstrumentToBasket = 'addPaymentInstrumentToBasket',
    removePaymentInstrumentFromBasket = 'removePaymentInstrumentFromBasket',
    updatePaymentInstrumentInBasket = 'updatePaymentInstrumentInBasket',
    updateShippingAddressForShipment = 'updateShippingAddressForShipment',
    updateShippingMethodForShipment = 'updateShippingMethodForShipment',
    deleteBasket = 'deleteBasket',
    transferBasket = 'transferBasket',
    addGiftCertificateItemToBasket = 'addGiftCertificateItemToBasket',
    removeGiftCertificateItemFromBasket = 'removeGiftCertificateItemFromBasket',
    updateGiftCertificateItemInBasket = 'updateGiftCertificateItemInBasket',
    addTaxesForBasketItem = 'addTaxesForBasketItem',
    addPriceBooksToBasket = 'addPriceBooksToBasket',
    createShipmentForBasket = 'createShipmentForBasket',
    removeShipmentFromBasket = 'removeShipmentFromBasket',
    updateShipmentForBasket = 'updateShipmentForBasket',
    addTaxesForBasket = 'addTaxesForBasket'
}

4. The SLAS Helper Hooks

We also included a few special action hooks for SLAS. These helpers implements the common authentication flows: loginGuest, loginRegisteredB2CUser, logout. Note that each helper could send multiple requests in order to get access token from the Shopper Login API.

These helpers manages the access token and refresh tokens internally, and persist the tokens in cookies/localstorage.

Example:

import React, {useEffect} from 'react'
import {useShopperLoginHelpers} from 'commerce-sdk-react/ShopperLogin'

const LoginForm = () => {
    const login = useShopperLoginHelpers('login')

   return <form>
    <input type="text" name="username">
    <input type="password" name="psw">
    <button type="button" onClick={() => login.execute({credentials:{username, password}})}>Login</button>
</form>
}

Authentication / Token Management

It is our goal to hide the token management complexity from the developers and fully manage the tokens within the library.

First, when the provider component is mounted, the library will initialize the session by re-using existing token / grabing access token from SLAS API following the Public Client Shopper Login OAuth flows. The library stores the tokens in the browser (cookie/localstorage).

While the library tries to initialize the session, the other API hooks will be blocked until the SLAS calls are resolved and there is a valid JWT.

[BUG] The 'x-api-key' header is cut off by the proxy

Summary

NOTE: This may not necessarily be a bug, but it can cause issues when integrating with some client libraries.

The current configuration of the built-in proxy explicitly filters out a set of specific headers. "x-api-key" is among those headers.
image

At the same time, there are client libraries/SDKs which use the same header to pass an authorization key to their backend. This happens especially when those services use AWS API Gateway where this naming convention is originally coming from.
Because the header is cut off via the proxy it causes issues for those types of integration(s).

Based on that it needs to be validated if there is a particular reason for having that header cut off

Steps To Reproduce

Expected result

1. The official documentation needs to be updated to indicate the specifics of some of the headers being cut off. All headers being cut off need to be explicitly listed..
2. Potentially allow the "x-api-key" header to be proxied as there might be a lot of SDKs using the same name due to its adoption as a convention and fixing it on the SDK/API level of a particular service is not always feasible.

Actual result

1. The current version of the documentation does not indicate that specifics: https://developer.salesforce.com/docs/commerce/pwa-kit-managed-runtime/guide/proxying-requests.html.
_2. "x-api-key" header is not proxied

System Information (as applicable)

n/a

Additional information

n/a

[BUG] Login empties the cart

Summary

⛔ login empties the cart

Steps To Reproduce

  • starting point: not logged in
  • add a product to the cart
  • login during checkout or via header link

→ see that the cart becomes removed → is empty now even if the guest had already products in cart

Expected result

after login cart remains as is

Actual result

cart becomes empty

System Information (as applicable)

Reproducible on https://pwa-kit.mobify-storefront.com/

Browser:
Node version:
pwa-kit version: 1.4
Desktop OS:
Mobile Device Info:

Additional information

As far as I remember this was working at least with version 1.1

[BUG] Forgot Password! not implemented in checkout

Summary

Forgot Password! not implemented in checkout

Steps To Reproduce

  • Add an item to cart.
  • Go to cart and checkout.
  • Switch to Already have an account? Login
  • Click Forgot Password? => nothing happens

Expected result

Forgot Password dialog should open same as for my account

screenshot 2021-12-13 um 14 55 50

Actual result

screenshot 2021-12-13 um 14 34 03

[BUG] Hybrid session not restored after logging in via PWA once dwsid exists

Summary

Removing the session bridge in PR #684 breaks phased rollout approach when switching between PWA and SFRA as a guest and registered customer.

Steps To Reproduce

  1. start out on pwa, add products to guest cart
  2. cart page redirects to SFRA cart page, session is successfully restored from PWA refresh token
  3. on SFRA login page, click "login" -> returns to PWA for login
  4. login via PWA
  5. return to SFRA cart page. notice that the previous guest dwsid is still set and onSession is never triggered on SFRA, resulting in a cleared guest cart. Customer is not logged in via SFRA.

Expected result

Returning to SFRA after logging in via PWA should maintain session state and cart

Additional information

Adding back the code removed in PR #684 fixes this issue.

Current State:
Notice that returning to SFRA the second time never calls onSession so the dwsid is never set from the logged in refresh token. The old dwsid from the initial session is used, resulting in an empty cart. There's no way to login via SFRA.

current-state-720.mov

Updated State

added-session-bridge-back-720.mov

[FEATURE] Support routing outgoing traffic through an HTTP(S) Proxy

In high control IT environments, outgoing traffic may required to route through a central corporate proxy:

Browser -> DevServer -> Corp Proxy -> Internet.

Currently using PWA Kit development server in such an environment is possible, but not straight forward:

https://github.com/SalesforceCommerceCloud/pwa-kit/compare/example-using-proxy

Ideally, we'd have a setting similar to npm's https-proxy setting that would route all requests through the proxy.


For folks looking for a workaround in the interim, in broad stokes you must:

  1. Install the better-https-proxy-agent and http-proxy-middleware packages
  2. Define express routes for “custom proxies” as shown in the above example for SCAPI and OCAPI
  3. Update your proxy settings. My example uses MITMProxy, but it should work w/ any HTTPS proxy.
  4. Alter the PWA code to use the custom proxies
  5. Celebrate! 🥳

[BUG] When a registered shopper logs in the items in the guest cart should move to the registered cart

Summary

When a registered shopper logs in the items in the guest cart should move to the registered cart

Steps To Reproduce

  1. As a guest shopper, add items to the cart
  2. Sign in as a registered user
  3. Go to cart and see items are gone

Expected result

As a guest shopper that has items in their cart if they log in the items are then associated with their account
If the shopper logs out the cart is empty.

Additional information

We could follow the default behaviour of SFRA on whether the existing registered user cart is merged or overwritten
OCAPI has the basket reference API that might work for this merge.
Commerce API guest cart merge is being implemented now (if OCAPI doesn't work).

@ W-9393931 @

[BUG] PLP Selecting multiple refinements from different filter categories are not combined

Summary

Selected refinements from different filter categories are not combined in the PLP filtering. Only selected refinements from the same filter category are being combined.

Steps To Reproduce

  1. Go to https://pwa-kit.mobify-storefront.com/global/en-GB/category/mens
  2. Click the filter Color “Black”
  3. Click the filter Price "20 - 49.99"

Expected result

Both "Black" and "20 - 49.99" refinements are selected, with a small set of products showing.

Actual result

Only "20 - 49.99" refinement is selected, not "Black".

[FEATURE] Enable Dependabot and Code scanning on the repo setting

Is your feature request related to a problem? Please describe.
To get the auto security fix recommendation and best practices in the code development

Describe the solution you'd like
Settings --> Code security and analysis

Describe alternatives you've considered

  • running code scanning on VS Code level. Developer responsibility
    Additional context
    Add any other context or screenshots about the feature request here.

[FEATURE] Proxy configs for multiple environments

Is your feature request related to a problem? Please describe.
Currently the proxy config for local development is in package.json, but if we want switch between on-demand sandboxes, then package.json must be changed. Sometimes after working the devs forgot to change the package.json.

Describe the solution you'd like
proxy or complete mobify config in package.json should be moved in separate config file.
Ideally we can make multiple environment configs.

Describe alternatives you've considered

Additional context

[BUG] Templated web app manifest is missing name,short_name

Summary

When templating a new pwa-kit project via npx pwa-kit-create-app the generated web app manifest is missing the name and short_name properties. Per spec the name property is at least required (https://developer.mozilla.org/en-US/docs/Web/Manifest/name).

This seems to occur with either preset.

The side effects of this is failing google lighthouse checks for PWA as it requires a valid manifest.
Likely other side effects are non-installable in home screen, etc

Steps To Reproduce

  1. Create new project npx pwa-kit-create-app
  2. View generated manifest file app/static/manifest.json

Expected result

manifest.json should have a name (and possible short_name)

Actual result

Missing those fields

System Information (as applicable)

Browser:
Node version: v14.17.5
pwa-kit version: Latest (via NPX)
Desktop OS: MacOS
Mobile Device Info:

Additional information

Seems like this maybe was a regression due to the configuration/multi-site refactoring. Given the changes here https://github.com/SalesforceCommerceCloud/pwa-kit/blame/f6de3aacea0298bb5358ea83a063e9343407f901/packages/pwa-kit-create-app/scripts/create-mobify-app.js#L165-L166 and https://github.com/SalesforceCommerceCloud/pwa-kit/blame/f6de3aacea0298bb5358ea83a063e9343407f901/packages/pwa-kit-create-app/scripts/create-mobify-app.js#L335-L348 perhaps siteId is a better option?

PDP Add to cart button should always be active unless out of stock

As a shopper, I need the "Add to Cart" button to be always active so that I'm not guessing what I have to do to add a product to cart.

Acceptance Criteria:
"Add to Cart button" is always active (unless the item is out of stock)
When the "Add to Cart" button is clicked but the product variants haven't been selected, show error state "Please select all your options above". See designs.

Implementation details:
Error message "Please select all your options above" is in the same place as "Out of Stock" error

This is a similar interaction with the forms during checkout
Working example on NTO demo: https://nto-pwakit-production.mobify-storefront.com/undefined/product/2010033?color=BE2

@W-9323464@

[FEATURE] MultiSite Context should include locale object instead of id

Is your feature request related to a problem? Please describe.
With version 2.2.0 we have now the MultiSite context, which includes the current site object, locale id and a buildUrl method.
This concept is much better then before and makes it easier to create full URLs, but i get with it only URLs with the locale id and not with locale alias if this is configured. The method has the localeRef parameter to have the possibility to set a custom locale path, but this means for every usage of buildUrl we must get the alias from the config and set it over the parameter.

Describe the solution you'd like
Instead only saving the locale id into the MultiSite context, save the complete locale object in the context, then change in the useMultiSite hook the following line: localeRef ? localeRef : locale?.alias || locale?.id
I don't see a reason, why this is not implemented, because old buildPathWithUrlConfig method was checking for configured alias and this method was removed.

Describe alternatives you've considered
Alternative is to use the localeRef parameter, which is not so useful in the complete project. We refactored the context, hook and tests to save the locale object in the MultiSite context to make the buildUrl more usable.

[BUG] Uncaught exception when adding a number of items to cart larger than the available stock

Summary

The useBasket hook throw an exception when a shopper tries to add more products to their cart than is available in stock.

useBasket.js:51 Uncaught (in promise) Error: [object Object] at useBasket.js:51

This is because we're not handling the API response with the exception type ProductItemNotAvailableException:

{"_v":"21.3","fault":{"arguments":{"productId":"701642842637M","quantity":110.0},"type":"ProductItemNotAvailableException","message":"The product '701642842637M' isn't available for quantity '110'."}}

Steps To Reproduce

  • Navigate to the PDP of any product.
  • Set quantity to 99 and repeatedly click the Add to cart button until the exception is thrown.

Expected result

The user is shown a useful error saying that the item is not available at the requested quantity.

Actual result

A Something went wrong Try again! popup appears. A 400 error appears in the devtools console.

@ W-9231893 @

[BUG] Images not rendering on the PLP or PDP when hosted on AWS

Summary

It appears that when products setup in the catalog in Business Manager have images hosted externally (i.e., AWS) they are not rendering in the retail react app. The image seems to list the src correctly, but it is not rendering. When I copy and paste the src into browser window the image renders correctly.

Steps To Reproduce

Install the retail react app... for the site, choose "alpine" (assuming you have this installed in your ODS.. would probably work with "nto" as well, but I haven't tested this. Navigate to any category or PDP and see images not rendering. Nothing else was changed - everything else works. I'm able to select a product and checkout successfully.

Expected result

image should be rendered

Actual result

image not rendered - just the 'alt text' is shown

System Information (as applicable)

Browser: Chrome
Node version:14
pwa-kit version: develop branch. v1.5
Desktop OS: Catalina v10.15.7
Mobile Device Info: na

Additional information

Screen Shot 2022-02-24 at 8 44 52 PM

<img alt="Alpine Energy Pre Eco Pod, Chai" class="chakra-image css-0" src="https://s3.amazonaws.com/northerntrailoutfitters.com/nto-alpine-nutrition/default/images/hi-res/alpine_energy_product_ecopod-chai.jpg" sizes="(min-width: 80em) 25vw, (min-width: 62em) 20vw, (min-width: 48em) 20vw, (min-width: 30em) 50vw, 50vw" srcset="https://s3.amazonaws.com/northerntrailoutfitters.com/nto-alpine-nutrition/default/images/hi-res/alpine_energy_product_ecopod-chai.jpg?sw=198&amp;q=60 198w, https://s3.amazonaws.com/northerntrailoutfitters.com/nto-alpine-nutrition/default/images/hi-res/alpine_energy_product_ecopod-chai.jpg?sw=396&amp;q=60 396w, https://s3.amazonaws.com/northerntrailoutfitters.com/nto-alpine-nutrition/default/images/hi-res/alpine_energy_product_ecopod-chai.jpg?sw=240&amp;q=60 240w, https://s3.amazonaws.com/northerntrailoutfitters.com/nto-alpine-nutrition/default/images/hi-res/alpine_energy_product_ecopod-chai.jpg?sw=480&amp;q=60 480w, https://s3.amazonaws.com/northerntrailoutfitters.com/nto-alpine-nutrition/default/images/hi-res/alpine_energy_product_ecopod-chai.jpg?sw=256&amp;q=60 256w, https://s3.amazonaws.com/northerntrailoutfitters.com/nto-alpine-nutrition/default/images/hi-res/alpine_energy_product_ecopod-chai.jpg?sw=512&amp;q=60 512w, https://s3.amazonaws.com/northerntrailoutfitters.com/nto-alpine-nutrition/default/images/hi-res/alpine_energy_product_ecopod-chai.jpg?sw=384&amp;q=60 384w, https://s3.amazonaws.com/northerntrailoutfitters.com/nto-alpine-nutrition/default/images/hi-res/alpine_energy_product_ecopod-chai.jpg?sw=768&amp;q=60 768w">

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.