-
Notifications
You must be signed in to change notification settings - Fork 214
created ShopperAgent component and refactored useMiaw hook to just a … #2370
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
sf-mkosak
merged 5 commits into
SalesforceCommerceCloud:feature-shopper-agent-exp-v3.0
from
sf-mkosak:preChatContextFollowup
Apr 23, 2025
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
fdd0b38
created ShopperAgent component and refactored useMiaw hook to just a …
sf-mkosak 066c939
pr cleanup and messing around with mobile miaw bug
sf-mkosak 84d900a
added Uid
sf-mkosak 3b133dc
Changes based on PR feedback
sf-mkosak b2ba471
renamed DomainURL preChat variable
sf-mkosak File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
137 changes: 137 additions & 0 deletions
137
packages/template-retail-react-app/app/components/shopper-agent/index.jsx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,137 @@ | ||
| /* | ||
| * Copyright (c) 2024, salesforce.com, inc. | ||
| * All rights reserved. | ||
| * SPDX-License-Identifier: BSD-3-Clause | ||
| * For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause | ||
| */ | ||
|
|
||
| import {useEffect, useState} from 'react' | ||
| import useScript from '@salesforce/retail-react-app/app/hooks/use-script' | ||
| import {useUsid} from '@salesforce/commerce-sdk-react' | ||
|
|
||
| const onClient = typeof window !== 'undefined' | ||
|
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Not sure what the best practice is here. Admittedly this was copy and pasted from another spot. |
||
|
|
||
| // Function to initialize embedded messaging | ||
| const initEmbeddedMessaging = ( | ||
| orgId, | ||
| embeddedServiceDeploymentName, | ||
| embeddedServiceDeploymentUrl, | ||
| scrt2Url | ||
| ) => { | ||
| try { | ||
| if ( | ||
| onClient && | ||
| window.embeddedservice_bootstrap && | ||
| window.embeddedservice_bootstrap.settings | ||
| ) { | ||
| window.embeddedservice_bootstrap.settings.language = 'en_US' | ||
| window.embeddedservice_bootstrap.init( | ||
| orgId, | ||
| embeddedServiceDeploymentName, | ||
| embeddedServiceDeploymentUrl, | ||
| { | ||
| scrt2URL: scrt2Url | ||
| } | ||
| ) | ||
| } | ||
| } catch (err) { | ||
| console.error('Error initializing Embedded Messaging: ', err) | ||
| } | ||
| } | ||
|
|
||
| function useMiaw( | ||
| scriptLoadStatus, | ||
| orgId, | ||
| embeddedServiceDeploymentName, | ||
| embeddedServiceDeploymentUrl, | ||
| scrt2Url | ||
| ) { | ||
| const [isMiawInitialized, setIsMiawInitialized] = useState(false) | ||
|
|
||
| useEffect(() => { | ||
| if (scriptLoadStatus.loaded && !scriptLoadStatus.error) { | ||
| initEmbeddedMessaging( | ||
| orgId, | ||
| embeddedServiceDeploymentName, | ||
| embeddedServiceDeploymentUrl, | ||
| scrt2Url | ||
| ) | ||
| setIsMiawInitialized(true) | ||
| } | ||
| }, [scriptLoadStatus]) | ||
|
|
||
| return isMiawInitialized | ||
| } | ||
|
|
||
| /** | ||
| * ShopperAgent component that initializes and manages the embedded messaging service | ||
| * @param {Object} props - Component props | ||
| * @param {string} props.commerceAgent - JSON stringified commerce agent settings | ||
| * @param {string} props.domainUrl - The domain URL for the embedded messaging script | ||
| * @param {string} props.basketId - The basket ID for the embedded messaging script | ||
| * @param {string} props.locale - The locale for the embedded messaging script | ||
| * @param {function} props.onAgentConversationOpened - The callback function for when the conversation is opened | ||
| * @param {function} props.onAgentConversationClosed - The callback function for when the conversation is closed | ||
| * @returns {JSX.Element} The ShopperAgent component | ||
| */ | ||
| const ShopperAgent = ({ | ||
| commerceAgent, | ||
| domainUrl, | ||
| basketId, | ||
| locale, | ||
| onAgentConversationOpened, | ||
| onAgentConversationClosed | ||
| }) => { | ||
| const { enabled, embeddedServiceName, embeddedServiceEndpoint, scriptSourceUrl, scrt2Url, salesforceOrgId, siteId } = JSON.parse(commerceAgent) | ||
| if (!onClient || !enabled) { | ||
| return null | ||
| } | ||
|
|
||
| const {usid} = useUsid(); | ||
|
|
||
| useEffect(() => { | ||
| window.addEventListener('onEmbeddedMessagingReady', (e) => { | ||
| window.embeddedservice_bootstrap.prechatAPI.setHiddenPrechatFields({ | ||
| DomainURL: domainUrl, | ||
| SiteId: siteId, | ||
| BasketId: basketId, | ||
| Locale: locale, | ||
| OrganizationId: salesforceOrgId, | ||
| UsId: usid | ||
|
|
||
| }) | ||
| }) | ||
|
|
||
| window.addEventListener('onEmbeddedMessagingConversationClosed', (e) => { | ||
| console.error('Error initializing Embedded Messaging: ', e) | ||
| }) | ||
|
|
||
| window.addEventListener('onEmbeddedMessagingConversationOpened', (e) => { | ||
| console.log('Conversation opened', e) | ||
| }) | ||
|
|
||
| window.addEventListener('onEmbeddedMessagingConversationEnded', (e) => { | ||
| console.log('Conversation ended', e) | ||
| }) | ||
|
|
||
|
|
||
| }, [commerceAgent]) | ||
|
|
||
| // Load the embedded messaging script | ||
| const scriptLoadStatus = useScript(scriptSourceUrl) | ||
|
|
||
| // Initialize the embedded messaging service | ||
| useMiaw( | ||
| scriptLoadStatus, | ||
| salesforceOrgId, | ||
| embeddedServiceName, | ||
| embeddedServiceEndpoint, | ||
gurpreetsainisalesforce marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| scrt2Url | ||
| ) | ||
|
|
||
| // The component doesn't render anything visible | ||
| // It's just a wrapper for the embedded messaging service | ||
| return null | ||
| } | ||
|
|
||
| export default ShopperAgent | ||
165 changes: 165 additions & 0 deletions
165
packages/template-retail-react-app/app/components/shopper-agent/index.test.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,165 @@ | ||
| /* | ||
| * Copyright (c) 2024, salesforce.com, inc. | ||
| * All rights reserved. | ||
| * SPDX-License-Identifier: BSD-3-Clause | ||
| * For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause | ||
| */ | ||
|
|
||
| import React from 'react' | ||
| import {render, screen, act} from '@testing-library/react' | ||
| import ShopperAgent from '@salesforce/retail-react-app/app/components/shopper-agent/index' | ||
| import useScript from '@salesforce/retail-react-app/app/hooks/use-script' | ||
| // Mock the embeddedservice_bootstrap object | ||
| const mockEmbeddedService = { | ||
| init: jest.fn(), | ||
| settings: jest.fn(), | ||
| prechatAPI: { | ||
| setHiddenPrechatFields: jest.fn() | ||
| } | ||
| } | ||
|
|
||
| jest.mock('../../hooks/use-script', () => jest.fn().mockReturnValue({loaded: false, error: false})) | ||
| jest.mock('@salesforce/commerce-sdk-react', () => { | ||
| const originalModule = jest.requireActual('@salesforce/commerce-sdk-react') | ||
| return { | ||
| ...originalModule, | ||
| useUsid: () => ({ usid: 'test-usid' }) | ||
| } | ||
| }) | ||
|
|
||
| const commerceAgentSettings = { | ||
| enabled: "true", | ||
| embeddedServiceName: "MIAW_Guided_Shopper_production", | ||
| embeddedServiceEndpoint: "https://myorg.salesforce.com/ESWMIAWGuidedShopper", | ||
| scriptSourceUrl: "https://myorg.salesforce.com/ESWMIAWGuidedShopper/assets/js/bootstrap.min.js", | ||
| scrt2Url: "https://myorg.salesforce.com-scrt.com", | ||
| salesforceOrgId: "00DSB00000MJ7YH", | ||
| siteId: "RefArchGlobal", | ||
| } | ||
|
|
||
| const commerceAgentSettingsString = JSON.stringify(commerceAgentSettings); | ||
|
|
||
| describe('ShopperAgent Component', () => { | ||
| const defaultProps = { | ||
| commerceAgent: commerceAgentSettingsString, | ||
| domainUrl: 'https://myorg.salesforce.com', | ||
| basketId: undefined, // TODO: Add basketId | ||
| locale: 'en-US' | ||
| } | ||
|
|
||
| beforeEach(() => { | ||
| // Reset all mocks before each test | ||
| jest.clearAllMocks() | ||
|
|
||
| // Mock the window.embeddedservice_bootstrap object | ||
| global.window.embeddedservice_bootstrap = mockEmbeddedService | ||
|
|
||
| useScript.mockReturnValue({loaded: false, error: false}) | ||
|
|
||
| // Clear any existing scripts | ||
| const scripts = document.querySelectorAll('script[data-status]') | ||
| scripts.forEach((script) => script.remove()) | ||
| }) | ||
|
|
||
| afterEach(() => { | ||
| // Clean up the window.embeddedservice_bootstrap mock | ||
| delete global.window.embeddedservice_bootstrap | ||
| }) | ||
|
|
||
| test('should render nothing when enableMiaw is false', () => { | ||
| const props = {...defaultProps, enableMiaw: false} | ||
| const {container} = render(<ShopperAgent {...props} />) | ||
|
|
||
| expect(container.firstChild).toBeNull() | ||
| }) | ||
|
|
||
| test('should not render anything when commerceAgenticEsdScriptSourceUrl is not provided', () => { | ||
| const props = {...defaultProps, scriptUrl: null} | ||
| const {container} = render(<ShopperAgent {...props} />) | ||
| expect(container.firstChild).toBeNull() | ||
| }) | ||
|
|
||
| test('should not render anything when embeddedservice_bootstrap is not available', () => { | ||
| // Temporarily remove the mock for this test | ||
| const originalEmbeddedService = global.window.embeddedservice_bootstrap | ||
| delete global.window.embeddedservice_bootstrap | ||
| useScript.mockReturnValue({loaded: true, error: false}) | ||
|
|
||
| render(<ShopperAgent {...defaultProps} />) | ||
|
|
||
| expect(mockEmbeddedService.init).not.toHaveBeenCalled() | ||
|
|
||
| // Restore the mock | ||
| global.window.embeddedservice_bootstrap = originalEmbeddedService | ||
| }) | ||
|
|
||
| test('should initialize embedded service when all required props are provided', () => { | ||
| useScript.mockReturnValue({loaded: true, error: false}) | ||
| render(<ShopperAgent {...defaultProps} />) | ||
|
|
||
| // Verify embedded service initialization | ||
| expect(mockEmbeddedService.init).toHaveBeenCalledWith( | ||
| commerceAgentSettings.salesforceOrgId, | ||
| commerceAgentSettings.embeddedServiceName, | ||
| commerceAgentSettings.embeddedServiceEndpoint, | ||
| { | ||
| scrt2URL: commerceAgentSettings.scrt2Url | ||
| } | ||
| ) | ||
| }) | ||
|
|
||
| test('should handle initialization error from useMiaw hook', () => { | ||
| // Mock useMiaw to return an error | ||
| const errorMessage = 'Initialization failed' | ||
| useScript.mockReturnValue({loaded: true, error: true}) | ||
| mockEmbeddedService.init.mockImplementation(() => { | ||
| throw new Error(errorMessage) | ||
| }) | ||
|
|
||
| const {container} = render(<ShopperAgent {...defaultProps} />) | ||
|
|
||
| // Component should not render anything when there's an error | ||
| expect(container.firstChild).toBeNull() | ||
| }) | ||
|
|
||
| test('should not reinitialize embedded service when already initialized', () => { | ||
| // First render | ||
| const scriptLoadStatus = {loaded: true, error: false} | ||
| useScript.mockReturnValue(scriptLoadStatus) | ||
| const {rerender} = render(<ShopperAgent {...defaultProps} />) | ||
|
|
||
| expect(mockEmbeddedService.init).toHaveBeenCalled() | ||
|
|
||
| // Reset mock call counts | ||
| jest.clearAllMocks() | ||
|
|
||
| useScript.mockReturnValue(scriptLoadStatus) | ||
|
|
||
| // Re-render with same props | ||
| rerender(<ShopperAgent {...defaultProps} />) | ||
|
|
||
| // Should not call init or createComponent again | ||
| expect(mockEmbeddedService.init).not.toHaveBeenCalled() | ||
| }) | ||
|
|
||
| test('should call the preChatAPI with the correct parameters', async () => { | ||
| useScript.mockReturnValue({loaded: true, error: false}) | ||
| render(<ShopperAgent {...defaultProps} />) | ||
|
|
||
| await act(async () => { | ||
| window.dispatchEvent(new Event('onEmbeddedMessagingReady')); | ||
| }); | ||
|
|
||
| // Verify embedded service initialization | ||
| expect(mockEmbeddedService.prechatAPI.setHiddenPrechatFields).toHaveBeenCalledWith( | ||
| { | ||
| BasketId: undefined, | ||
| DomainURL: defaultProps.domainUrl, | ||
| Locale: defaultProps.locale, | ||
| OrganizationId: commerceAgentSettings.salesforceOrgId, | ||
| SiteId: commerceAgentSettings.siteId, | ||
| UsId: 'test-usid', | ||
| } | ||
| ) | ||
| }) | ||
| }) |
49 changes: 49 additions & 0 deletions
49
packages/template-retail-react-app/app/hooks/use-script.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,49 @@ | ||
| /* | ||
| * Copyright (c) 2024, salesforce.com, inc. | ||
| * All rights reserved. | ||
| * SPDX-License-Identifier: BSD-3-Clause | ||
| * For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause | ||
| */ | ||
|
|
||
| import {useEffect, useState} from 'react' | ||
|
|
||
| /** | ||
| * Custom hook to handle script loading | ||
| * @param {string} src - The source URL for the script | ||
| * @returns {Object} The script load status | ||
| */ | ||
| const useScript = (src) => { | ||
| const [scriptLoadStatus, setScriptLoadStatus] = useState({loaded: false, error: false}) | ||
| // Effect to load and initialize the script | ||
| useEffect(() => { | ||
| if (!src) { | ||
| return | ||
| } | ||
|
|
||
| // Check if script already exists | ||
| const scriptAlreadyOnPage = document.querySelector(`script[src="${src}"]`) | ||
|
|
||
| if (!scriptAlreadyOnPage) { | ||
| const script = document.createElement('script') | ||
| script.src = src | ||
| script.async = true | ||
| script.setAttribute('data-status', 'loading') | ||
| document.body.appendChild(script) | ||
|
|
||
| const onScriptLoad = (event) => { | ||
| const loadStatus = event.type === 'load' ? 'ready' : 'error' | ||
| setScriptLoadStatus({ | ||
| loaded: loadStatus === 'ready', | ||
| error: loadStatus === 'error' | ||
| }) | ||
| } | ||
|
|
||
| script.addEventListener('load', onScriptLoad) | ||
| script.addEventListener('error', onScriptLoad) | ||
| } | ||
| }, [src]) | ||
|
|
||
| return scriptLoadStatus | ||
| } | ||
|
|
||
| export default useScript |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I guess the linting doesn't like semi colons