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

Added the ability to generate Eco News from the Manage Eco News Page #8083

Conversation

Maryna-511750
Copy link
Collaborator

@Maryna-511750 Maryna-511750 commented Jan 30, 2025

GreenCity PR

Issue Link 📋

#8050

Summary Of Changes 🔥

Added the ability to generate eco news from the Manage Eco News Page.
Fixed an issue with rating calculation when creating eco news.

Added

  • Implemented functionality for generating eco news on the Manage Eco News Page.

Changed

  • Modified js files and management_eco_news.html to support the new functionality.
  • Updated the rating calculation logic when creating eco news.

PR Checklist Forms

(to be filled out by PR submitter)

  • Code is up-to-date with the dev branch.
  • You've successfully built and run the tests locally.
  • There are new or updated unit tests validating the change.
  • JIRA/ Github Issue number & title in PR title (ISSUE-XXXX: Ticket title)
  • This template filled (above this section).
  • Sonar's report does not contain bugs, vulnerabilities, security issues, code smells ar duplication
  • NEED_REVIEW and READY_FOR_REVIEW labels are added.
  • All files reviewed before sending to reviewers

Summary by CodeRabbit

  • New Features

    • Added AI-powered Eco News generation functionality.
    • Introduced a new form in the Eco News modal to generate content using AI.
    • Implemented language-specific support for content generation.
  • Localization

    • Added Ukrainian and English translations for AI-generated news feature.
    • Updated interface messages for AI Eco News generation.
  • User Interface

    • Added a "Generate AI Eco News" button in the Eco News management modal.
    • Implemented dynamic form for entering AI news generation topics.
    • Added error handling messages for user interactions in the Eco News modal.

Copy link

coderabbitai bot commented Jan 30, 2025

Walkthrough

The pull request introduces an AI-generated Eco News feature for the GreenCity application. The changes span multiple files to implement a new functionality that allows users to generate news articles using AI. The implementation includes modifications to the controller, JavaScript interactions, HTML templates, and localization files to support a seamless user experience for generating AI-powered Eco News content.

Changes

File Change Summary
core/src/main/java/greencity/controller/AIController.java Modified language handling for news generation, adding a specific check for Ukrainian locale.
core/src/main/resources/messages.properties Added new localization keys for AI Eco News generation feature.
core/src/main/resources/messages_ua.properties Added Ukrainian translations for new localization keys.
core/src/main/resources/static/management/econews/buttonsAJAX.js Implemented client-side JavaScript for AI news generation, including AJAX request handling.
core/src/main/resources/templates/core/management_eco_news.html Added new UI elements for AI Eco News generation modal.
service/src/main/java/greencity/service/EcoNewsServiceImpl.java Simplified parameter passing in rating calculation methods.
core/src/test/java/greencity/controller/AIControllerTest.java Added a test for the AI news generation functionality for the Ukrainian locale.

Sequence Diagram

sequenceDiagram
    participant User
    participant Browser
    participant AIController
    participant AIService

    User->>Browser: Click "Generate AI Eco News"
    Browser->>AIController: Send generation request
    AIController->>AIService: Request news generation
    AIService-->>AIController: Return generated news
    AIController-->>Browser: Send generated content
    Browser->>User: Display generated news in form
Loading

Possibly related issues

  • Issue #8050: This PR directly implements the AI-Generated Eco News feature described in the issue, addressing all the specified acceptance criteria.

Possibly related PRs

Suggested reviewers

  • VasylyshynDmytro
  • holotsvan
  • Cr1stal423

Poem

🌿 Bits of wisdom, algorithmically spun,
AI whispers tales of Earth's green run.
With a click, news springs to life,
Eco stories cutting through digital strife.
Innovation blooms, one article at a time! 🌍


📜 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 dc9abf1 and d9df2de.

📒 Files selected for processing (2)
  • core/src/main/resources/static/management/econews/buttonsAJAX.js (1 hunks)
  • core/src/test/java/greencity/controller/AIControllerTest.java (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: build
🔇 Additional comments (2)
core/src/test/java/greencity/controller/AIControllerTest.java (1)

67-78: Well-structured test for Ukrainian locale support!

The test method effectively verifies the behavior of the /ai/generate/eco-news endpoint with Ukrainian locale. Good use of Mockito for verifying the service call with the correct language parameter.

core/src/main/resources/static/management/econews/buttonsAJAX.js (1)

349-353: LGTM: Clean implementation of form toggle.

The toggle implementation is simple and effective.

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

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.

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

@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 (6)
service/src/main/java/greencity/service/EcoNewsServiceImpl.java (2)

104-107: Consider extracting rating and achievement calculations into a separate method.

The combination of rating calculation, achievement calculation, and notification creation appears in multiple places. Consider extracting these operations into a reusable method to improve maintainability and ensure consistent behavior.

Example refactor:

+ private void processUserAchievementsAndRatings(UserVO userVO, EcoNews news) {
+     achievementCalculation.calculateAchievement(
+         userVO, 
+         AchievementCategoryType.CREATE_NEWS, 
+         AchievementAction.ASSIGN
+     );
+     ratingCalculation.ratingCalculation(
+         ratingPointsRepo.findByNameOrThrow("CREATE_NEWS"), 
+         userVO
+     );
+     userNotificationService.createNewNotification(
+         userVO, 
+         NotificationType.ECONEWS_CREATED, 
+         news.getId(),
+         news.getTitle()
+     );
+ }

This would simplify the calling code to:

- achievementCalculation.calculateAchievement(userVO, AchievementCategoryType.CREATE_NEWS, AchievementAction.ASSIGN);
- ratingCalculation.ratingCalculation(ratingPointsRepo.findByNameOrThrow("CREATE_NEWS"), userVO);
- userNotificationService.createNewNotification(userVO, NotificationType.ECONEWS_CREATED, toSave.getId(), toSave.getTitle());
+ processUserAchievementsAndRatings(userVO, toSave);

Line range hint 1-1000: Review transaction boundaries for rating calculations.

The service uses class-level @Transactional, but consider defining explicit transaction boundaries for atomic operations involving rating calculations, achievements, and notifications to ensure data consistency.

Consider:

  1. Using method-level @Transactional(propagation = Propagation.REQUIRED) for atomic operations
  2. Adding explicit error handling for rating calculation failures
  3. Defining rollback behavior for specific exceptions
core/src/main/java/greencity/controller/AIController.java (1)

63-64: Consider improving locale handling robustness.

While the special case for Ukrainian locale works, consider these improvements:

  1. Add null check for locale
  2. Consider using a locale mapping configuration instead of hardcoding "українська"
-                aiService.getNews(locale.toString().equals("ua") ? "українська" : locale.getDisplayLanguage(), query));
+                aiService.getNews(
+                    Optional.ofNullable(locale)
+                        .map(l -> l.toString().equals("ua") ? "українська" : l.getDisplayLanguage())
+                        .orElse("english"),
+                    query));
core/src/main/resources/static/management/econews/buttonsAJAX.js (2)

349-353: Consider using jQuery for consistency.

Since jQuery is already used throughout the file, consider using it for DOM manipulation here as well.

-        const form = document.getElementById('generateEcoNewsForm');
-        form.style.display = form.style.display === 'none' ? 'block' : 'none';
+        $('#generateEcoNewsForm').toggle();

355-387: Add loading state and input validation.

Consider these improvements for better user experience:

  1. Add loading state during content generation
  2. Validate query input before making the request
  3. Disable the generate button during the request
    $('#generateEcoNewsContent').on('click', function (event) {
        const query = $('#generateQueryInput').val().trim();
+       if (!query) {
+           $('#errorModalGenerateContent').text('Please enter a topic for generation');
+           return;
+       }
        const language = localStorage.getItem("language") || "en";
        const locale = language === "ua" ? "uk-UA" : "en-US";

+       const $generateBtn = $(this);
+       $generateBtn.prop('disabled', true);
+       $('#generateSpinner').show();

        $.ajax({
            // ... existing ajax config ...
            success: function (response) {
                // ... existing success handling ...
+               $generateBtn.prop('disabled', false);
+               $('#generateSpinner').hide();
            },
            error: function (xhr, status, error) {
                // ... existing error handling ...
+               $generateBtn.prop('disabled', false);
+               $('#generateSpinner').hide();
            }
        });
    });
core/src/main/resources/templates/core/management_eco_news.html (1)

535-542: Enhance accessibility and user experience.

Consider the following improvements:

  1. Add ARIA attributes for better screen reader support
  2. Add loading state handling for the generate button

Apply these changes:

-                                        <input type="text" id="generateQueryInput" class="form-control">
+                                        <input type="text" id="generateQueryInput" class="form-control" 
+                                               aria-label="AI generation topic input">
-                                        <span th:id="errorModalGenerateContent" id="errorModalGenerateContent" class="errorSpan"></span>
+                                        <span th:id="errorModalGenerateContent" id="errorModalGenerateContent" 
+                                              class="errorSpan" role="alert" aria-live="polite"></span>
-                                    <button type="button" class="btn btn-secondary" id="generateEcoNewsContent">
+                                    <button type="button" class="btn btn-secondary" id="generateEcoNewsContent"
+                                            data-loading-text="Generating...">
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between aeebe5a and 80c1be3.

📒 Files selected for processing (6)
  • core/src/main/java/greencity/controller/AIController.java (1 hunks)
  • core/src/main/resources/messages.properties (2 hunks)
  • core/src/main/resources/messages_ua.properties (2 hunks)
  • core/src/main/resources/static/management/econews/buttonsAJAX.js (1 hunks)
  • core/src/main/resources/templates/core/management_eco_news.html (1 hunks)
  • service/src/main/java/greencity/service/EcoNewsServiceImpl.java (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: build
🔇 Additional comments (5)
service/src/main/java/greencity/service/EcoNewsServiceImpl.java (1)

105-105: Great optimization in rating calculation!

The direct use of userVO instead of mapping from toSave simplifies the code and improves performance by eliminating unnecessary object mapping.

core/src/main/resources/messages.properties (1)

181-181: LGTM! Clear and consistent messages.

The new localization entries follow the existing naming pattern and provide clear user instructions.

Also applies to: 210-211

core/src/main/resources/messages_ua.properties (1)

166-166: LGTM! Proper Ukrainian translations.

The Ukrainian translations are properly encoded and maintain consistency with the English messages.

Also applies to: 199-200

core/src/main/resources/templates/core/management_eco_news.html (2)

532-534: Well-structured toggle button implementation!

The button follows the application's styling conventions and properly implements internationalization.


532-543: Clean integration with existing modal structure!

The AI generation form is well-integrated into the existing modal, maintaining consistency with the application's design patterns and user experience.

Comment on lines 367 to 368
console.log(response);
const titleMatch = response.match(/\*\*Title:\s*(.+?)\s*\*\*/) || response.match(/\*\*\s*(.+?)\s*\*\*/);
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Remove console.log of potentially sensitive data.

The response from the AI service might contain sensitive information. Remove the console.log or replace it with appropriate logging.

-                console.log(response);
📝 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
console.log(response);
const titleMatch = response.match(/\*\*Title:\s*(.+?)\s*\*\*/) || response.match(/\*\*\s*(.+?)\s*\*\*/);
const titleMatch = response.match(/\*\*Title:\s*(.+?)\s*\*\*/) || response.match(/\*\*\s*(.+?)\s*\*\*/);

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

🧹 Nitpick comments (1)
core/src/main/resources/static/management/econews/buttonsAJAX.js (1)

349-353: Consider using jQuery for consistent DOM manipulation.

Since the codebase predominantly uses jQuery, let's maintain consistency:

 $('#toggleGenerateEcoNewsForm').on('click', function (event) {
-    const form = document.getElementById('generateEcoNewsForm');
-    form.style.display = form.style.display === 'none' ? 'block' : 'none';
+    $('#generateEcoNewsForm').toggle();
 });
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 80c1be3 and dc9abf1.

📒 Files selected for processing (1)
  • core/src/main/resources/static/management/econews/buttonsAJAX.js (1 hunks)

Comment on lines 355 to 386
$('#generateEcoNewsContent').on('click', function (event) {
const query = $('#generateQueryInput').val().trim();
const language = localStorage.getItem("language") || "en";
const locale = language === "ua" ? "uk-UA" : "en-US";

$.ajax({
url: '/ai/generate/eco-news',
type: 'GET',
data: { query: query },
headers: { 'Accept-Language': locale },
contentType: 'application/json',
success: function (response) {
const titleMatch = response.match(/\*\*Title:\s*(.+?)\s*\*\*/) || response.match(/\*\*\s*(.+?)\s*\*\*/);

if (titleMatch) {
const title = titleMatch[1];
$('#inputTitle').val(title);

const updatedContent = response.replace(titleMatch[0], '').trim();

tinymce.get('ecoNewsContent').setContent(updatedContent);
} else {
tinymce.get('ecoNewsContent').setContent(response);
}
},
error: function (xhr, status, error) {
console.error('Error generating Eco News content:', status, error);
document.getElementById("errorModalGenerateContent").innerText =
'Failed to generate Eco News content. Please try again.';
}
});
});
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add input validation and improve user experience.

The implementation needs several improvements for robustness and user experience:

  1. Validate input before making the API call
  2. Show loading state during API call
  3. Remove console.error in production
  4. Add debounce to prevent rapid-fire API calls
 $('#generateEcoNewsContent').on('click', function (event) {
     const query = $('#generateQueryInput').val().trim();
+    if (!query) {
+        document.getElementById("errorModalGenerateContent").innerText = 
+            'Please enter a topic for content generation.';
+        return;
+    }
+
+    const $button = $(this);
+    $button.prop('disabled', true);
+    document.getElementById("errorModalGenerateContent").innerText = 'Generating content...';
+
     const language = localStorage.getItem("language") || "en";
     const locale = language === "ua" ? "uk-UA" : "en-US";

     $.ajax({
         url: '/ai/generate/eco-news',
         type: 'GET',
         data: { query: query },
         headers: { 'Accept-Language': locale },
         contentType: 'application/json',
         success: function (response) {
             const titleMatch = response.match(/\*\*Title:\s*(.+?)\s*\*\*/) || response.match(/\*\*\s*(.+?)\s*\*\*/);

             if (titleMatch) {
                 const title = titleMatch[1];
                 $('#inputTitle').val(title);

                 const updatedContent = response.replace(titleMatch[0], '').trim();

                 tinymce.get('ecoNewsContent').setContent(updatedContent);
             } else {
                 tinymce.get('ecoNewsContent').setContent(response);
             }
+            document.getElementById("errorModalGenerateContent").innerText = '';
         },
         error: function (xhr, status, error) {
-            console.error('Error generating Eco News content:', status, error);
+            // Log to server-side error tracking
             document.getElementById("errorModalGenerateContent").innerText =
                 'Failed to generate Eco News content. Please try again.';
         },
+        complete: function() {
+            $button.prop('disabled', false);
+        }
     });
 });

Also, consider adding debounce to prevent rapid-fire API calls:

const debouncedGenerate = _.debounce(function(event) {
    // Move the entire click handler logic here
}, 1000);

$('#generateEcoNewsContent').on('click', debouncedGenerate);

@Maryna-511750 Maryna-511750 merged commit d96c4a7 into dev Jan 30, 2025
4 checks passed
@Maryna-511750 Maryna-511750 deleted the feature/8050/Add-AI-Generated-Eco-News-Feature-to-Manage-Eco-News-Page branch January 30, 2025 09:28
@Maryna-511750 Maryna-511750 linked an issue Jan 30, 2025 that may be closed by this pull request
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.

Add AI-Generated Eco News Feature to Manage Eco News Page
4 participants