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(web): Add boost chat panel for 'Vinnumálastofnun' #17071

Merged
merged 2 commits into from
Nov 28, 2024

Conversation

RunarVestmann
Copy link
Member

@RunarVestmann RunarVestmann commented Nov 28, 2024

Add boost chat panel for 'Vinnumálastofnun'

What

  • Boost AI chat panel added to Vinnumálastofnun organization page
  • Just in case we've got a "config flag" so we can remove the chat if needed

Screenshots / Gifs

Screenshot 2024-11-28 at 13 08 53

Checklist:

  • I have performed a self-review of my own code
  • I have made corresponding changes to the documentation
  • My changes generate no new warnings
  • I have added tests that prove my fix is effective or that my feature works
  • Formatting passes locally with my changes
  • I have rebased against main before asking for a review

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced a new chat panel for the "Vinnumálastofnun" organization, replacing the previous "Sýslumenn" configuration.
    • Enhanced the OrganizationWrapper component to conditionally render the new chat panel based on organization IDs.
  • Improvements

    • Improved error handling for JSON parsing in the chat panel logic.
    • Enhanced type safety for the domain parameter in the pageview tracking hook.

These updates enhance user experience by providing new chat functionalities and improving the reliability of existing features.

@RunarVestmann RunarVestmann added the automerge Merge this PR as soon as all checks pass label Nov 28, 2024
@RunarVestmann RunarVestmann requested review from a team as code owners November 28, 2024 13:09
Copy link
Contributor

coderabbitai bot commented Nov 28, 2024

Walkthrough

The pull request introduces changes to several components, primarily focusing on the chat functionality. The boostChatPanelEndpoints configuration is updated to remove the "Sýslumenn" organization and add the "Vinnumálastofnun" organization. Additionally, the OrganizationWrapper.tsx component is modified to conditionally render the BoostChatPanel based on organization IDs and introduces improved error handling for namespace parsing. Lastly, the usePlausiblePageview hook is adjusted to enhance type safety for the domain parameter, allowing it to accept null.

Changes

File Path Change Summary
apps/web/components/ChatPanel/BoostChatPanel/config.ts Removed configuration for "Sýslumenn" and added new configuration for "Vinnumálastofnun" in boostChatPanelEndpoints.
apps/web/components/Organization/Wrapper/OrganizationWrapper.tsx Added conditional rendering for BoostChatPanel, introduced a namespace variable with error handling, and updated logic for OrganizationChatPanel.
apps/web/hooks/usePlausiblePageview.ts Updated domain parameter type from string? to `string

Possibly related PRs

Suggested reviewers

  • mannipje

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 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.

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.

Copy link

codecov bot commented Nov 28, 2024

Codecov Report

Attention: Patch coverage is 0% with 13 lines in your changes missing coverage. Please review.

Project coverage is 35.69%. Comparing base (7d3961e) to head (8aed334).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
...nents/Organization/Wrapper/OrganizationWrapper.tsx 0.00% 12 Missing ⚠️
apps/web/hooks/usePlausiblePageview.ts 0.00% 1 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main   #17071      +/-   ##
==========================================
- Coverage   35.69%   35.69%   -0.01%     
==========================================
  Files        6938     6938              
  Lines      147110   147122      +12     
  Branches    41820    41824       +4     
==========================================
  Hits        52516    52516              
- Misses      94594    94606      +12     
Flag Coverage Δ
api 3.34% <ø> (ø)
api-domains-auth-admin 48.49% <ø> (ø)
api-domains-communications 39.59% <ø> (ø)
application-system-api 38.72% <ø> (-0.02%) ⬇️
application-template-api-modules 27.78% <ø> (+<0.01%) ⬆️
cms 0.40% <ø> (ø)
cms-translations 38.93% <ø> (ø)
content-search-toolkit 8.20% <ø> (ø)
judicial-system-api 20.36% <ø> (ø)
judicial-system-backend 55.73% <ø> (-0.01%) ⬇️
services-user-notification 46.77% <ø> (ø)
web 2.44% <0.00%> (-0.01%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

Files with missing lines Coverage Δ
.../web/components/ChatPanel/BoostChatPanel/config.ts 0.00% <ø> (ø)
apps/web/hooks/usePlausiblePageview.ts 0.00% <0.00%> (ø)
...nents/Organization/Wrapper/OrganizationWrapper.tsx 0.00% <0.00%> (ø)

Continue to review full report in Codecov by Sentry.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update 7d3961e...8aed334. Read the comment docs.

@datadog-island-is
Copy link

Datadog Report

Branch report: feature/web-boost-chat-panel
Commit report: f2090a7
Test service: web

✅ 0 Failed, 84 Passed, 0 Skipped, 26.92s Total Time
➡️ Test Sessions change in coverage: 1 no change

Copy link
Contributor

@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

🧹 Outside diff range and nitpick comments (5)
apps/web/components/ChatPanel/BoostChatPanel/config.ts (1)

9-10: Ensure consistent naming convention

The ID and conversationKey use the same value '313vinnumalastofnun'. While this works, consider using a more descriptive conversation key that reflects the purpose or context of the chat panel.

-    id: '313vinnumalastofnun',
-    conversationKey: '313vinnumalastofnun',
+    id: '313vinnumalastofnun',
+    conversationKey: 'vinnumalastofnun-chat',
apps/web/hooks/usePlausiblePageview.ts (2)

Line range hint 1-46: Consider refactoring the global state management.

The hook uses a global newestVisitedUrl variable which could cause issues with concurrent renders or multiple hook instances. Consider using React's state management primitives instead.

Here's a suggested refactor:

-let newestVisitedUrl = ''
 
 export const usePlausiblePageview = (domain?: string | null) => {
   const router = useRouter()
+  const newestVisitedUrlRef = useRef('')
 
   useEffect(() => {
     const onRouteChangeComplete = () => {
       if (
         publicRuntimeConfig.environment !== 'prod' ||
         !domain ||
-        newestVisitedUrl === window.location.href
+        newestVisitedUrlRef.current === window.location.href
       ) {
         return
       }
 
-      newestVisitedUrl = window.location.href
+      newestVisitedUrlRef.current = window.location.href
 
       // Rest of the code...
     }
 
     // Rest of the code...
 
     return () => {
       router.events.off('routeChangeComplete', onRouteChangeComplete)
-      newestVisitedUrl = ''
+      newestVisitedUrlRef.current = ''
     }
   }, [domain, router.events])
 }

Line range hint 24-34: Enhance error handling and configurability.

The Plausible API integration could be improved with:

  1. Error handling for failed requests
  2. Configuration for the API URL
  3. Retry logic for failed requests

Here's a suggested improvement:

+const PLAUSIBLE_API_URL = publicRuntimeConfig.plausibleApiUrl || 'https://plausible.io/api/event'
+const MAX_RETRIES = 3
+
+const trackPageview = async (domain: string, retryCount = 0) => {
+  try {
     fetch('https://plausible.io/api/event', {
       method: 'POST',
       headers: {
         'Content-Type': 'text/plain',
       },
       body: JSON.stringify({
         domain: domain,
         name: 'pageview',
         url: window.location.href,
         referrer: window.document.referrer || null,
       }),
     })
+  } catch (error) {
+    console.error('Failed to track pageview:', error)
+    if (retryCount < MAX_RETRIES) {
+      setTimeout(() => trackPageview(domain, retryCount + 1), 1000 * Math.pow(2, retryCount))
+    }
+  }
+}
apps/web/components/Organization/Wrapper/OrganizationWrapper.tsx (2)

1132-1141: Consider adding error logging for namespace parsing failures

While the error handling is robust, adding error logging would help debug potential JSON parsing issues in production.

  const namespace = useMemo(() => {
    try {
      return JSON.parse(
        organizationPage.organization?.namespace?.fields || '{}',
      )
    } catch (error) {
+     console.error('Failed to parse organization namespace:', error);
      return {}
    }
  }, [organizationPage.organization?.namespace?.fields])

962-974: Enhance type safety for Boost chat panel endpoint lookup

The current implementation is good, but we can improve type safety by using a type guard instead of type assertion.

  const organizationIdWithBoost = organizationIds.find((id) => {
    return id in boostChatPanelEndpoints
  })

  if (organizationIdWithBoost) {
+   const endpoint = boostChatPanelEndpoints[organizationIdWithBoost]
+   if (endpoint) {
      return (
        <BoostChatPanel
-         endpoint={
-           organizationIdWithBoost as keyof typeof boostChatPanelEndpoints
-         }
+         endpoint={organizationIdWithBoost}
        />
      )
+   }
  }
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 6a313ad and 3089bbe.

📒 Files selected for processing (3)
  • apps/web/components/ChatPanel/BoostChatPanel/config.ts (1 hunks)
  • apps/web/components/Organization/Wrapper/OrganizationWrapper.tsx (5 hunks)
  • apps/web/hooks/usePlausiblePageview.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (3)
apps/web/components/ChatPanel/BoostChatPanel/config.ts (1)

Pattern apps/**/*: "Confirm that the code adheres to the following:

  • NextJS best practices, including file structure, API routes, and static generation methods.
  • Efficient state management and server-side rendering techniques.
  • Optimal use of TypeScript for component and utility type safety."
apps/web/components/Organization/Wrapper/OrganizationWrapper.tsx (1)

Pattern apps/**/*: "Confirm that the code adheres to the following:

  • NextJS best practices, including file structure, API routes, and static generation methods.
  • Efficient state management and server-side rendering techniques.
  • Optimal use of TypeScript for component and utility type safety."
apps/web/hooks/usePlausiblePageview.ts (1)

Pattern apps/**/*: "Confirm that the code adheres to the following:

  • NextJS best practices, including file structure, API routes, and static generation methods.
  • Efficient state management and server-side rendering techniques.
  • Optimal use of TypeScript for component and utility type safety."
🔇 Additional comments (4)
apps/web/components/ChatPanel/BoostChatPanel/config.ts (2)

8-11: ⚠️ Potential issue

Verify the security of the chat panel endpoint

The chat panel URL is using HTTP instead of HTTPS. This could potentially expose user conversations to security risks.

Let's verify if other chat panel endpoints in the codebase use HTTPS:


7-8: Verify Contentful entry reference

The comment references a Contentful entry ID. Let's ensure this matches our configuration.

✅ Verification successful

Contentful entry ID is correctly referenced

The Contentful entry ID co6SSvHZjUpEICpTlJT1B is correctly used and matches between both files:

  • It's defined in InstitutionContentfulIds enum as VINNUMALASTOFNUN
  • It's properly referenced in the BoostChatPanel config for Vinnumálastofnun organization
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify if the Contentful entry ID is used consistently
rg "co6SSvHZjUpEICpTlJT1B" --type ts

Length of output: 359


Script:

#!/bin/bash
# Let's check the content of both files to understand the relationship
cat libs/application/types/src/lib/InstitutionContentfulIds.ts
echo "---"
cat apps/web/components/ChatPanel/BoostChatPanel/config.ts

Length of output: 1934

apps/web/hooks/usePlausiblePageview.ts (1)

9-9: LGTM! Verify type usage across the codebase.

The type change from string? to string | null? makes nullability more explicit, which is good TypeScript practice.

Let's verify the usage of this hook across the codebase:

✅ Verification successful

Type change is safe and correctly used across the codebase

All usages of usePlausiblePageview are handling the domain parameter correctly:

  • article?.organization?.[0]?.trackingDomain ?? undefined
  • organization?.trackingDomain
  • organization?.trackingDomain ?? undefined
  • DIGITAL_ICELAND_PLAUSIBLE_TRACKING_DOMAIN

The type change from string? to string | null? is backward compatible with existing code as all call sites either:

  • Use optional chaining with nullish coalescing to undefined
  • Pass a constant string
  • Pass undefined explicitly
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Find all usages of usePlausiblePageview to ensure they handle null correctly

# Search for hook usage
rg -A 2 "usePlausiblePageview" --type ts --type tsx

Length of output: 79


Script:

#!/bin/bash
# Search for hook usage with ripgrep, without file type restrictions
rg "usePlausiblePageview"

# Also search for potential imports of this hook
rg "from ['\"].*usePlausiblePageview['\"]"

Length of output: 1446

apps/web/components/Organization/Wrapper/OrganizationWrapper.tsx (1)

34-35: LGTM: Import statements are correctly placed

The new imports for BoostChatPanel components are properly organized within the existing import block.

@kodiakhq kodiakhq bot merged commit 10e9499 into main Nov 28, 2024
61 checks passed
@kodiakhq kodiakhq bot deleted the feature/web-boost-chat-panel branch November 28, 2024 16:56
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
automerge Merge this PR as soon as all checks pass
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants