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(ZMS-3503): added logic to end emergency with checkbox #805

Merged
merged 5 commits into from
Feb 4, 2025

Conversation

msfb3
Copy link
Contributor

@msfb3 msfb3 commented Jan 30, 2025

Pull Request Checklist (Feature Branch to next):

  • Ich habe die neuesten Änderungen aus dem next Branch in meinen Feature-Branch gemergt.
  • Das Code-Review wurde abgeschlossen.
  • Fachliche Tests wurden durchgeführt und sind abgeschlossen.

Summary by CodeRabbit

Release Notes

  • New Features

    • Added emergency end functionality to the admin interface.
    • Introduced new emergency management controls with enhanced styling and data handling.
  • Bug Fixes

    • Improved error handling in form data processing method.
    • Enhanced robustness of key removal in entity management.
  • Chores

    • Updated JavaScript modules for emergency feature implementation.
    • Added welcome console log to admin interface.

Copy link
Contributor

coderabbitai bot commented Jan 30, 2025

Walkthrough

This pull request introduces a new JavaScript class EndEmergencyView to manage emergency end functionalities in a web application. The changes span multiple files, including a new JavaScript module for emergency handling, updates to the main index file, modifications to a Twig template, and a small improvement in error handling within an entity schema method. The primary focus is on enhancing the emergency management feature with improved data handling and interaction capabilities.

Changes

File Change Summary
zmsadmin/js/block/scope/emergencyend.js Added new EndEmergencyView class with methods for managing emergency end functionality, including endEmergency(), update(), and sendEmergencyCancel()
zmsadmin/js/index.js Imported EmergencyEnd and instantiated it for elements with .emergency-end class, added a welcome console log
zmsadmin/templates/block/scope/form.twig Added emergency-end class and data attributes to emergency-related HTML elements
zmsentities/src/Zmsentities/Schema/Entity.php Added conditional check before unsetting 'save' key in withCleanedUpFormData() method

Sequence Diagram

sequenceDiagram
    participant User
    participant EmergencyEndView
    participant Backend
    
    User->>EmergencyEndView: Click Emergency End Button
    EmergencyEndView->>EmergencyEndView: endEmergency()
    EmergencyEndView->>Backend: sendEmergencyCancel()
    Backend-->>EmergencyEndView: Request Response
    EmergencyEndView->>User: Update UI
Loading

Suggested reviewers

  • ThomasAFink
  • matthilo96

Poem

🚨 Emergency's end is near,
A rabbit's code brings cheer!
Click the button, watch it fly,
Cancellation request goes high
Technology saves the day, hooray! 🐰

Tip

🌐 Web search-backed reviews and chat
  • We have enabled web search-based reviews and chat for all users. This feature allows CodeRabbit to access the latest documentation and information on the web.
  • You can disable this feature by setting web_search: false in the knowledge_base settings.
  • Please share any feedback in the Discord discussion.

📜 Recent review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e642fb0 and 3aa65ca.

📒 Files selected for processing (1)
  • zmsadmin/templates/block/scope/form.twig (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • zmsadmin/templates/block/scope/form.twig
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: call-unit-tests / zmsdb-test
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: call-unit-tests / zmsapi-test

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

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

🧹 Nitpick comments (3)
zmsadmin/js/index.js (1)

147-147: Remove debug console.log statement.

This appears to be a debug statement that should be removed before production deployment.

-console.log("Hello")
zmsadmin/js/block/scope/emergencyend.js (2)

12-13: Remove debug console.log statements.

These appear to be debug statements that should be removed before production deployment.

-        console.log("Emergency Options received:", options);
         this.includeUrl = options.includeurl
         this.returnTarget = options.returnTarget
         this.workstationName = ""+options.workstationname
         this.scope = options.scope
-        console.log("Emergency Scope received:", this.scope);

Also applies to: 17-18


48-58: Enhance error handling in loadData method.

The error handling in the AJAX call could be improved by:

  1. Adding specific error types/messages
  2. Implementing retry logic for transient failures
  3. Providing user feedback on errors
         return new Promise((resolve, reject) => {
             $.ajax(url, {
                 method: 'GET'
             }).done(data => {
                 const emergencyData = deepGet(tryJson(data), ['workstation', 'scope', 'status', 'emergency'])
                 resolve(emergencyData)
             }).fail(err => {
-                console.log('XHR error', url, err)
+                const error = new Error(`Failed to load emergency data: ${err.statusText}`);
+                error.originalError = err;
+                reject(error);
             })
         })
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 21a1b2f and 6c4f1ad.

📒 Files selected for processing (5)
  • zmsadmin/js/block/emergency/index.js (1 hunks)
  • zmsadmin/js/block/scope/emergencyend.js (1 hunks)
  • zmsadmin/js/index.js (3 hunks)
  • zmsadmin/templates/block/scope/form.twig (2 hunks)
  • zmsentities/src/Zmsentities/Schema/Entity.php (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • zmsadmin/js/block/emergency/index.js
🔇 Additional comments (5)
zmsadmin/js/index.js (2)

29-29: LGTM!

The import follows the established pattern in the file.


112-114: LGTM!

The initialization of EmergencyEnd follows the consistent pattern used for other view components.

zmsadmin/js/block/scope/emergencyend.js (1)

126-159: Improve accessibility in focus trap implementation.

The focus trap implementation could be enhanced:

  1. Add ARIA attributes for better screen reader support
  2. Handle cases where no focusable elements exist
  3. Consider using established libraries like focus-trap

Additionally, verify if the focus trap is being properly removed when the emergency overlay is closed.

✅ Verification successful

Focus trap is properly removed, but accessibility can be improved

The focus trap is correctly removed when the emergency overlay is closed, with proper cleanup in all exit paths. However, the original accessibility improvement suggestions remain valid:

  1. Add ARIA attributes for better screen reader support
  2. Handle cases where no focusable elements exist
  3. Consider using established libraries like focus-trap
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for focus trap removal calls
rg -A 5 "removeFocusTrap" .

Length of output: 5739

zmsentities/src/Zmsentities/Schema/Entity.php (1)

311-313: LGTM!

Good defensive programming practice to check if the key exists before unsetting it.

zmsadmin/templates/block/scope/form.twig (1)

630-635: LGTM!

The template changes properly integrate with the new EmergencyEnd JavaScript functionality:

  1. Added required data attributes for state management
  2. Added appropriate classes for event handling

Also applies to: 647-647

zmsadmin/js/block/scope/emergencyend.js Outdated Show resolved Hide resolved
Copy link
Member

@Fabinatix97 Fabinatix97 left a comment

Choose a reason for hiding this comment

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

Bitte nochmal meine Anmerkungen prüfen

zmsadmin/js/block/emergency/index.js Outdated Show resolved Hide resolved
zmsadmin/js/block/scope/emergencyend.js Outdated Show resolved Hide resolved
zmsadmin/js/index.js Outdated Show resolved Hide resolved
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

🧹 Nitpick comments (5)
zmsadmin/js/block/scope/emergencyend.js (5)

1-4: Remove or clarify commented-out import.
You have some commented-out code (// import { playSound } from '../../lib/audio'). It's a best practice to remove unused code to maintain clarity, or add a comment explaining its future purpose if you plan to use it.

-// import { playSound } from '../../lib/audio'
+// import { playSound } from '../../lib/audio'} // Future use for emergency alert audio 

6-7: Consider making the refresh interval configurable.
Having a hard-coded constant DEFAULT_REFRESH_INTERVAL = 15 might be limiting. Consider making it configurable through an environment variable or configuration object to adapt to different environments or user requirements without changing the code.


10-29: Avoid excessive console logging in production code.
While console.log calls help with debugging, they can clutter the console in production. Consider using a logging utility that can be toggled off or replaced with debug-level logging in non-production environments.

- console.log("Emergency Options received:", options);
- console.log("Emergency Scope received:", this.scope);
+ // console.debug("Emergency Options received:", options);
+ // console.debug("Emergency Scope received:", this.scope);

38-49: Use newer fetch or axios for AJAX calls.
While jQuery’s $.ajax is valid, modern web applications often use the native fetch API or a library like axios for readability and simpler promise handling. Replacing $.ajax with fetch or axios can improve maintainability.

- $.ajax(url, {
-    method: 'GET'
- }).done(data => {
-    ...
- }).fail(err => {
-    ...
- })
+ fetch(url)
+   .then(res => res.json())
+   .then(data => {
+       // handle data
+   })
+   .catch(err => {
+       // handle error
+   })

Also applies to: 58-67


104-108: Consider i18n for displayed strings.
Labels like "Tresen" and "Platz" are hard-coded in German. If the application needs a multilingual audience, consider introducing an i18n library or a language file for easy translations.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6c4f1ad and 2c41030.

📒 Files selected for processing (2)
  • zmsadmin/js/block/scope/emergencyend.js (1 hunks)
  • zmsadmin/js/index.js (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • zmsadmin/js/index.js
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: call-unit-tests / zmsdb-test
  • GitHub Check: call-unit-tests / zmsapi-test
🔇 Additional comments (2)
zmsadmin/js/block/scope/emergencyend.js (2)

79-82: Confirm parseInt usage and default fallback.
You use parseInt for activated and acceptedByWorkstation. Ensure these values are always convertible to a valid number in your data flow. Otherwise, consider providing a default fallback to avoid NaN.

✅ Verification successful

parseInt usage is safe, no fallback needed
The values for activated and acceptedByWorkstation are always valid numeric strings controlled by the system through schema validation and explicit assignments. The current implementation is correct and safe.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Verifying if the properties are always numeric
rg -A 4 'activated' | rg 'acceptedByWorkstation'

Length of output: 27954


23-24: Ensure correct selector for the end-emergency button.
Double-check that .emergency__button-end is indeed the correct DOM element, as no default text or visible label is provided. Use a more descriptive class name or a data attribute if multiple buttons might exist in the future.

✅ Verification successful

The .emergency__button-end selector is correctly implemented

  • Follows consistent BEM naming convention with other emergency buttons
  • Has clear visible text label "Notruf beenden"
  • Used consistently in templates and JavaScript components
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# search for class usage in the entire codebase to confirm correctness
fd -E node_modules -E dist -e js -e html -e twig | xargs rg '\.emergency__button-end'

Length of output: 318


Script:

#!/bin/bash
# Search for emergency-related button classes and HTML structure
echo "=== Emergency-related classes ==="
rg -i 'emergency.*button' --type html --type twig

echo -e "\n=== Emergency button in HTML/template structure ==="
rg -i '<[^>]*emergency' --type html --type twig

echo -e "\n=== Module initialization ==="
rg -A 5 'new.*Emergency' --type js

Length of output: 4544

zmsadmin/js/block/scope/emergencyend.js Outdated Show resolved Hide resolved
zmsadmin/js/block/scope/emergencyend.js Outdated Show resolved Hide resolved
zmsadmin/js/block/scope/emergencyend.js Outdated Show resolved Hide resolved
zmsadmin/js/block/scope/emergencyend.js Outdated Show resolved Hide resolved
zmsadmin/js/block/scope/emergencyend.js Outdated Show resolved Hide resolved
zmsadmin/js/block/scope/emergencyend.js Outdated Show resolved Hide resolved
zmsadmin/js/block/scope/emergencyend.js Outdated Show resolved Hide resolved
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: 2

🧹 Nitpick comments (2)
zmsadmin/js/block/scope/emergencyend.js (2)

5-13: Add input validation and improve code quality.

Several improvements can be made to the constructor:

  1. Add validation for required options
  2. Use String() instead of string concatenation
  3. Use arrow function for event binding to avoid explicit bind(this)
     constructor(element, options) {
+        if (!element || !options || !options.includeurl || !options.scope || !options.workstationname) {
+            throw new Error('Required options missing');
+        }
         this.includeUrl = options.includeurl
         this.scope = options.scope
-        this.workstationName = "" + options.workstationname
+        this.workstationName = String(options.workstationname)
         this.data = {}
         this.$ = $(element)

-        this.$.find('.emergency__button-end').on('click', this.endEmergency.bind(this))
+        this.$.find('.emergency__button-end').on('click', () => this.endEmergency())
     }

40-40: Remove trailing whitespace.

There's an extra whitespace at the end of the export statement.

-export default EndEmergencyView;  
+export default EndEmergencyView;
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2c41030 and e642fb0.

📒 Files selected for processing (1)
  • zmsadmin/js/block/scope/emergencyend.js (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: call-unit-tests / zmsdb-test
  • GitHub Check: call-unit-tests / zmsapi-test
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (1)
zmsadmin/js/block/scope/emergencyend.js (1)

1-3: LGTM!

The import statement and class declaration follow best practices.

zmsadmin/js/block/scope/emergencyend.js Show resolved Hide resolved
Comment on lines +15 to +18
endEmergency() {
this.update({ activated: "0", calledByWorkstation: "-1", acceptedByWorkstation: "-1" })
this.sendEmergencyCancel()
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add error handling and user feedback.

The endEmergency method should handle errors from sendEmergencyCancel and provide feedback to the user.

     endEmergency() {
         this.update({ activated: "0", calledByWorkstation: "-1", acceptedByWorkstation: "-1" })
-        this.sendEmergencyCancel()
+        this.sendEmergencyCancel()
+            .then(() => {
+                // Add success feedback (e.g., toast notification)
+            })
+            .catch(error => {
+                // Add error feedback
+                this.update({ activated: "1" }) // Revert state on error
+            })
     }

Committable suggestion skipped: line range outside the PR's diff.

@msfb3 msfb3 merged commit 7565e11 into next Feb 4, 2025
23 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants