Skip to content
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

feat(contact-center): emit AgentStateChange event #4030

Merged
merged 3 commits into from
Dec 20, 2024

Conversation

mkesavan13
Copy link
Contributor

@mkesavan13 mkesavan13 commented Dec 17, 2024

COMPLETES SPARK-584812

This pull request addresses

Emitting Event for AgentStateChange

by making the following changes

  • Updating cc.ts to listen to socket message and emit only the AgentStateChange event with the same name
  • Updating the sample app to receive this event and update the dropdown accordingly

Change Type

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to change)
  • Documentation update
  • Tooling change
  • Internal code refactor

The following scenarios were tested

  • Tested by logging in as supervisor and changing to Available State and Meeting State
  • Tested by logging in as supervisor and changing to Custom State created from the Admin portal
agent.state.emit.mov

I certified that

  • I have read and followed contributing guidelines

  • I discussed changes with code owners prior to submitting this pull request

  • I have not skipped any automated checks

  • All existing and new tests passed

  • I have updated the documentation accordingly


Make sure to have followed the contributing guidelines before submitting.

Summary by CodeRabbit

  • New Features

    • Enhanced agent state management and wrap-up code functionality.
    • Introduced a dropdown for selecting wrap-up codes.
    • Added event listeners for agent state changes and incoming messages.
  • Bug Fixes

    • Corrected comparison logic for setting auxiliary code IDs.
  • Tests

    • Added tests for new event handling and wrap-up code dropdown functionality.

@mkesavan13 mkesavan13 requested a review from a team as a code owner December 17, 2024 01:52
Copy link

coderabbitai bot commented Dec 17, 2024

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

This pull request introduces enhancements to the contact center application's agent state management and event handling. The changes focus on improving wrap-up code functionality in the app.js file and adding event listeners in the cc.ts file. The modifications include introducing a new dropdown for wrap-up codes, updating agent state change event handling, and implementing more robust event management for WebSocket communications.

Changes

File Change Summary
docs/samples/contact-center/app.js - Added wrapupCodes global variable
- Introduced wrapupCodesDropdownElm DOM element
- Created populateWrapupCodesDropdown() function
- Updated event listeners for agent state changes
packages/@webex/plugin-cc/src/cc.ts - Added CC_EVENTS import
- Enhanced WebSocket message event handling
- Implemented new event listener for agent state changes
packages/@webex/plugin-cc/test/unit/spec/cc.ts - Added setupEventListeners() method
- Enhanced test coverage for new event handling functionality

Sequence Diagram

sequenceDiagram
    participant Agent
    participant WebApp
    participant WebSocket
    participant ContactCenter

    Agent->>WebApp: Interact with UI
    WebApp->>ContactCenter: Register Agent
    ContactCenter->>WebSocket: Establish Connection
    WebSocket-->>ContactCenter: Agent State Change Event
    ContactCenter->>WebApp: Update UI Elements
    WebApp->>Agent: Display Updated Agent Status
Loading

Possibly related PRs

Suggested reviewers

  • sreenara
  • adhmenon

Poem

🐰 Hop, hop, through agent's state,
Wrap-up codes now populate!
WebSocket whispers, events unfurl,
Contact center's magic swirl!
Code rabbits dance with glee today! 🎉


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@mkesavan13 mkesavan13 added the validated If the pull request is validated for automation. label Dec 17, 2024
Copy link
Contributor

@Kesari3008 Kesari3008 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is it possible to add some screenshot or screenrecording for this to verify the testing done in the PR description?

packages/@webex/plugin-cc/src/cc.ts Outdated Show resolved Hide resolved
docs/samples/contact-center/app.js Outdated Show resolved Hide resolved
@mkesavan13
Copy link
Contributor Author

@coderabbitai review

Copy link

coderabbitai bot commented Dec 20, 2024

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

♻️ Duplicate comments (1)
packages/@webex/plugin-cc/src/cc.ts (1)

287-294: ⚠️ Potential issue

Add error handling and type safety checks

The WebSocket message handler needs improvements in error handling and type safety:

  1. Add try-catch for JSON.parse
  2. Add type checking for eventData
  3. Clean up the listener during station logout

Apply this diff to improve the implementation:

    this.services.webSocketManager.on('message', (event) => {
-     const eventData = JSON.parse(event);
-
-     if (eventData.type === CC_EVENTS.AGENT_STATE_CHANGE) {
-       // @ts-ignore
-       this.emit(CC_EVENTS.AGENT_STATE_CHANGE, eventData.data);
-     }
+     try {
+       const eventData = JSON.parse(event);
+       
+       if (eventData && typeof eventData === 'object' && 
+           eventData.type === CC_EVENTS.AGENT_STATE_CHANGE && 
+           eventData.data) {
+         this.emit(CC_EVENTS.AGENT_STATE_CHANGE, eventData.data);
+       }
+     } catch (error) {
+       LoggerProxy.error('Failed to parse WebSocket message', {
+         module: CC_FILE,
+         method: 'setupEventListeners',
+         error
+       });
+     }
    });

Additionally, store the message handler reference and remove the listener in stationLogout:

+ private messageHandler = (event: string) => {
+   try {
+     const eventData = JSON.parse(event);
+     
+     if (eventData && typeof eventData === 'object' && 
+         eventData.type === CC_EVENTS.AGENT_STATE_CHANGE && 
+         eventData.data) {
+       this.emit(CC_EVENTS.AGENT_STATE_CHANGE, eventData.data);
+     }
+   } catch (error) {
+     LoggerProxy.error('Failed to parse WebSocket message', {
+       module: CC_FILE,
+       method: 'setupEventListeners',
+       error
+     });
+   }
+ };

  private setupEventListeners() {
    this.services.connectionService.on('connectionLost', this.handleConnectionLost.bind(this));
-   this.services.webSocketManager.on('message', (event) => {
-     // ... existing code
-   });
+   this.services.webSocketManager.on('message', this.messageHandler);
  }

  public async stationLogout(data: Logout): Promise<StationLogoutResponse> {
    try {
      const logoutResponse = this.services.agent.logout({
        data,
      });

      await logoutResponse;

+     this.services.webSocketManager.off('message', this.messageHandler);

      if (this.webCallingService) {
        this.webCallingService.deregisterWebCallingLine();
      }
🧹 Nitpick comments (1)
packages/@webex/plugin-cc/test/unit/spec/cc.ts (1)

840-879: Add negative test cases for error scenarios

The test suite looks good but could be enhanced with additional test cases:

Consider adding these test cases:

it('should handle JSON parse error gracefully', () => {
  webex.cc.setupEventListeners();
  const messageCallback = mockWebSocketManager.on.mock.calls[0][1];
  
  // Simulate receiving invalid JSON
  messageCallback('invalid json');
  
  expect(LoggerProxy.error).toHaveBeenCalledWith(
    'Failed to parse WebSocket message',
    expect.any(Object)
  );
  expect(cCEmitSpy).not.toHaveBeenCalled();
});

it('should not emit event for non-AGENT_STATE_CHANGE message type', () => {
  webex.cc.setupEventListeners();
  const messageCallback = mockWebSocketManager.on.mock.calls[0][1];
  
  const eventData = {
    type: 'OTHER_EVENT',
    data: { some: 'data' }
  };
  
  messageCallback(JSON.stringify(eventData));
  expect(cCEmitSpy).not.toHaveBeenCalled();
});

it('should cleanup message listener on stationLogout', async () => {
  webex.cc.setupEventListeners();
  const offSpy = jest.spyOn(mockWebSocketManager, 'off');
  
  await webex.cc.stationLogout({ logoutReason: 'test' });
  
  expect(offSpy).toHaveBeenCalledWith(
    'message',
    expect.any(Function)
  );
});
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6fa4910 and fd4e700.

📒 Files selected for processing (3)
  • docs/samples/contact-center/app.js (2 hunks)
  • packages/@webex/plugin-cc/src/cc.ts (2 hunks)
  • packages/@webex/plugin-cc/test/unit/spec/cc.ts (5 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
docs/samples/contact-center/app.js

[error] 282-282: The assignment should not be in an expression.

The use of assignments in expressions is confusing.
Expressions are often considered as side-effect free.

(lint/suspicious/noAssignInExpressions)


[error] 282-282: Unexpected constant condition.

(lint/correctness/noConstantCondition)

🔇 Additional comments (1)
docs/samples/contact-center/app.js (1)

323-323: LGTM!

The implementation correctly retrieves the selected text from the dropdown.

Comment on lines 281 to 285
webex.cc.on('AgentStateChange', (data) => {
if(data.type = 'AgentStateChangeSuccess') {
idleCodesDropdown.value = data.auxCodeId.trim() !== '' ? data.auxCodeId : 0;
}
});
Copy link

@coderabbitai coderabbitai bot Dec 20, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Fix the condition operator and add error handling

The event handler has several issues that need to be addressed:

Apply this diff to fix the implementation:

-   webex.cc.on('AgentStateChange', (data) => {
-     if(data.type = 'AgentStateChangeSuccess') {
-       idleCodesDropdown.value = data.auxCodeId.trim() !== '' ? data.auxCodeId : 0;
-     }
-   });
+   webex.cc.on('AgentStateChange', (data) => {
+     if (data && typeof data === 'object' && data.type === 'AgentStateChangeSuccess') {
+       const DEFAULT_CODE = '0'; // Default code when no aux code is present
+       idleCodesDropdown.value = data.auxCodeId?.trim() !== '' ? data.auxCodeId : DEFAULT_CODE;
+     }
+   });

Key fixes:

  1. Fixed assignment operator (=) to comparison operator (===)
  2. Added null checks for data object
  3. Added optional chaining for auxCodeId
  4. Replaced magic number with named constant
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
webex.cc.on('AgentStateChange', (data) => {
if(data.type = 'AgentStateChangeSuccess') {
idleCodesDropdown.value = data.auxCodeId.trim() !== '' ? data.auxCodeId : 0;
}
});
webex.cc.on('AgentStateChange', (data) => {
if (data && typeof data === 'object' && data.type === 'AgentStateChangeSuccess') {
const DEFAULT_CODE = '0'; // Default code when no aux code is present
idleCodesDropdown.value = data.auxCodeId?.trim() !== '' ? data.auxCodeId : DEFAULT_CODE;
}
});
🧰 Tools
🪛 Biome (1.9.4)

[error] 282-282: The assignment should not be in an expression.

The use of assignments in expressions is confusing.
Expressions are often considered as side-effect free.

(lint/suspicious/noAssignInExpressions)


[error] 282-282: Unexpected constant condition.

(lint/correctness/noConstantCondition)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@mkesavan13, thanks for confirming that you've addressed the changes! Let me know if there's anything else needed.


If you found this review helpful, would you consider giving us a shout-out on X?
Thank you for using CodeRabbit!

Copy link
Contributor

@Shreyas281299 Shreyas281299 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Changes look good, please address Priya comments

@mkesavan13 mkesavan13 enabled auto-merge (squash) December 20, 2024 07:20
@mkesavan13 mkesavan13 disabled auto-merge December 20, 2024 07:20
@mkesavan13 mkesavan13 merged commit 9880b88 into webex:wxcc Dec 20, 2024
12 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
validated If the pull request is validated for automation.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants