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

Feature/128 implement hint page frontend #156

Merged
merged 5 commits into from
Aug 26, 2024

Conversation

thomastepi
Copy link
Contributor

  • implemented the create hint page (frontend)
  • implemented the hint page using mock data (frontend)

Copy link
Contributor

coderabbitai bot commented Aug 22, 2024

Walkthrough

The changes consist of the introduction of a new banner resource in the backend, including routes, a controller, a service, and a model. In the frontend, new components and modifications to existing ones enhance the user interface, particularly for hints and banners. Import paths have been adjusted, and new styling files have been added to accommodate new components, along with the introduction of test files for the CustomLink component.

Changes

Files Change Summary
backend/index.js, backend/src/routes/banner.routes.js Introduced a new route handler for the banner resource.
backend/src/controllers/banner.controller.js Added BannerController class with methods for managing banners (CRUD operations).
backend/src/models/Banner.js, backend/src/models/index.js Introduced Sequelize model for Banner, defining its structure and relationships.
backend/src/service/banner.service.js Created BannerService class encapsulating methods for banner management.
frontend/src/App.jsx, frontend/src/scenes/hints/CreateHintPage.jsx, frontend/src/scenes/hints/HintDefaultPage.jsx, frontend/src/scenes/hints/HintPage.jsx Added new routes and components for hint creation and display while modifying existing ones.
frontend/src/components/CustomLink/CustomLink.jsx, frontend/src/services/bannerServices.js, frontend/src/services/popupServices.js Introduced new CustomLink component and services for managing banners and popups.
frontend/src/components/templates/GuideTemplate/GuideTemplate.jsx, frontend/src/templates/HomePageTemplate/HomePageTemplate.jsx Updated import paths for components.
frontend/src/scenes/bannerPage/BannerPage.jsx, frontend/src/scenes/popup/CreatePopupPage.jsx Enhanced functionality by adding state variables and props.
frontend/src/tests/components/customLinkComponent/CustomLink.test.jsx Introduced unit tests for the new CustomLink component.
frontend/src/assets/theme.js, frontend/src/components/Checkbox/CheckboxStyles.css Added new styles and enhanced existing theme configurations.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Frontend
    participant Backend

    User->>Frontend: Request to create a banner
    Frontend->>Backend: POST /banner/add_banner
    Backend->>Backend: Validate and process banner data
    Backend->>Frontend: Return success or error response
    Frontend->>User: Display success or error message
Loading

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:

‼️ IMPORTANT
Auto-reply has been disabled for this repository in the CodeRabbit settings. The CodeRabbit bot will not respond to your replies unless it is explicitly tagged.

  • 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @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 as 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.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

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.

@thomastepi thomastepi changed the base branch from master to develop August 22, 2024 03:58
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.

Caution

Inline review comments failed to post

Actionable comments posted: 12

Outside diff range, codebase verification and nitpick comments (8)
frontend/src/services/popupServices.js (1)

7-9: Enhance error logging for better traceability.

Consider logging additional details such as error.message and error.stack to improve debugging and traceability.

  } catch (error) {
-   console.error('Add Popup error:', error.response);
+   console.error('Add Popup error:', error.message, error.stack);
frontend/src/services/bannerServices.js (1)

8-9: Enhance error logging for better traceability.

Consider logging additional details such as error.message and error.stack to improve debugging and traceability.

  } catch (error) {
-   console.error('Add Banner error:', error);
+   console.error('Add Banner error:', error.message, error.stack);
frontend/src/components/List/List.jsx (1)

24-25: Consider making items and onSelectItem optional.

Based on previous learnings, the items and onSelectItem props might not need to be required. Consider updating the PropTypes to reflect this flexibility.

 items: PropTypes.arrayOf(PropTypes.object),
-onSelectItem: PropTypes.func,
+onSelectItem: PropTypes.func,
frontend/src/components/TourComponents/ConfirmationPopup/ConfirmationPopup.jsx (2)

13-14: Enhance accessibility with aria-label.

Consider adding aria-label attributes to the buttons to improve accessibility for screen readers.

 <Button onClick={onCancel} aria-label="Cancel action">Cancel</Button>
 <Button onClick={onConfirm} color="primary" aria-label="Confirm action">Confirm</Button>

5-17: Consider adding transition effects for better UX.

Adding transition effects to the dialog can enhance the user experience by making the appearance and disappearance of the popup smoother.

backend/src/controllers/popupController.js (1)

12-12: Verify and update database schema and logic related to "close-popup".

The "close-popup" action is still referenced in the migration file backend/migrations/20240601230258-create-popup-table.js. Ensure that the database schema and any related logic are updated to reflect the removal of this action from validActions. This will prevent potential inconsistencies between the application logic and database constraints.

  • File to review: backend/migrations/20240601230258-create-popup-table.js
Analysis chain

Verify the impact of removing "close-popup".

The removal of the "close-popup" action from validActions might affect existing functionality. Ensure that any logic relying on this action is updated accordingly.

Run the following script to check for usages of "close-popup" in the codebase:

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the impact of removing "close-popup" action.

# Test: Search for occurrences of "close-popup" in the codebase.
rg --type js -A 5 $'"close-popup"'

Length of output: 548

backend/src/controllers/banner.controller.js (2)

53-64: Enhance error logging for better debugging.

Consider using a logging library instead of console.log for better error tracking and debugging.

- console.log(err);
+ logger.error(err);

98-149: Enhance error logging for better debugging.

Consider using a logging library instead of console.log for better error tracking and debugging.

- console.log(err);
+ logger.error(err);
Comments failed to post (12)
frontend/src/services/bannerServices.js

6-6: Avoid logging the entire response object.

Logging the entire response could expose sensitive information. Consider logging specific details instead.

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


frontend/src/components/TourComponents/InfoTooltip/InfoTooltip.jsx

6-19: Remove unused title prop.

The title prop is defined in the PropTypes but is not used in the component. Consider removing it if it's unnecessary.

Apply this diff to remove the unused prop:

 const InfoTooltip = ({ text, title }) => {
-  return (
+  return (
     <Tooltip title={text}>
       <IconButton>
         <InfoIcon />
       </IconButton>
     </Tooltip>
   );
 };

 InfoTooltip.propTypes = {
   text: PropTypes.string,
-  title: PropTypes.string,
 };
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.

const InfoTooltip = ({ text }) => {
  return (
    <Tooltip title={text}>
      <IconButton>
        <InfoIcon />
      </IconButton>
    </Tooltip>
  );
};

InfoTooltip.propTypes = {
  text: PropTypes.string,
};
backend/src/service/banner.service.js

5-8: Enhance error handling in getAllBanners.

Consider adding error handling to manage potential database errors when fetching banners. This will improve the robustness of the service.

try {
  return await Banner.findAll({
    include: [{ model: db.User, as: "creator" }],
  });
} catch (error) {
  // Handle error, e.g., log it and return a meaningful response
}

11-13: Add validation for createBanner.

Ensure that the data passed to createBanner is validated before attempting to create a new banner. This can prevent potential issues with invalid data.

// Validate data here

15-23: Improve error handling in deleteBanner.

Consider handling potential database errors when attempting to delete a banner. This will improve the service's reliability.

try {
  const rowsAffected = await Banner.destroy({ where: { id } });
  if (rowsAffected === 0) {
    return false;
  }
  return true;
} catch (error) {
  // Handle error, e.g., log it and return a meaningful response
}

25-35: Enhance error handling in updateBanner.

Consider adding error handling to manage potential database errors when updating a banner. This will improve the robustness of the service.

try {
  const [affectedRows, updatedBanners] = await Banner.update(data, {
    where: { id },
    returning: true,
  });
  if (affectedRows === 0) {
    return null;
  }
  return updatedBanners[0];
} catch (error) {
  // Handle error, e.g., log it and return a meaningful response
}
backend/src/models/Banner.js

1-51: Solid model definition!

The Banner model is well-structured with appropriate validations and associations. Consider adding timestamps for better tracking of record creation and updates.

Apply this diff to add timestamps:

 {
     tableName: "banners",
-    timestamps: false,
+    timestamps: true,
 },
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.

        {
            tableName: "banners",
            timestamps: true,
        },
frontend/src/components/List/ListItem/ListItem.jsx

1-46: Great component design!

The ListItem component is well-implemented with proper prop types and usage of Material-UI components. Consider adding default props for better robustness.

Apply this diff to add default props:

 ListItem.propTypes = {
     title: PropTypes.string,
     text: PropTypes.string,
     id: PropTypes.string,
     onClick: PropTypes.func,
     onDelete: PropTypes.func,
     onEdit: PropTypes.func,
 };
+
+ListItem.defaultProps = {
+    title: '',
+    text: '',
+    id: '',
+    onClick: () => {},
+    onDelete: () => {},
+    onEdit: () => {},
+};
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.

import React from 'react';
import PropTypes from 'prop-types';
import { IconButton, useTheme } from '@mui/material';
import DeleteIcon from '@mui/icons-material/Delete';
import SettingsIcon from '@mui/icons-material/Settings';
import CircleIcon from '@mui/icons-material/Circle';
import './ListItem.css';

const ListItem = ({ title, text, id, onClick, onDelete, onEdit }) => {
  const theme = useTheme();

  return (
    <div className="list-item" onClick={onClick}>
      <div className="list-item-info">
        <div className="list-item-header">
          <div className="list-item-icon-container">
            <CircleIcon className="list-item-icon" style={{ fill: theme.palette.primary.main }} />
            <div className="list-item-dot" style={{ backgroundColor: theme.palette.background.default }}></div>
          </div>
          <h4>{title}</h4>
        </div>
        {text && <p>{text}</p>}
        {id && <p className="item-id">ID: {id}</p>}
      </div>
      <div className="list-item-actions">
        <IconButton onClick={onEdit}>
          <SettingsIcon />
        </IconButton>
        <IconButton onClick={onDelete}>
          <DeleteIcon />
        </IconButton>
      </div>
    </div>
  );
};

ListItem.propTypes = {
  title: PropTypes.string,
  text: PropTypes.string,
  id: PropTypes.string,
  onClick: PropTypes.func,
  onDelete: PropTypes.func,
  onEdit: PropTypes.func,
};

ListItem.defaultProps = {
  title: '',
  text: '',
  id: '',
  onClick: () => {},
  onDelete: () => {},
  onEdit: () => {},
};

export default ListItem;
frontend/src/scenes/popup/CreatePopupPage.jsx

37-61: Consider using optional chaining for error handling.

Using optional chaining can simplify the error handling logic by safely accessing nested properties.

Apply this diff to improve error handling:

        } catch (error) {
-          if (error.response && error.response.data) {
+          if (error.response?.data) {
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.

    const onSave = async () => {
        const popupData = { 
            popupSize: popupSize.toLowerCase(),
            url: actionButtonUrl,
            actionButtonText: actionButtonText,
            headerBackgroundColor: headerBackgroundColor,
            headerColor: headerColor,
            textColor: textColor,
            buttonBackgroundColor: buttonBackgroundColor,
            buttonTextColor: buttonTextColor,
            closeButtonAction:buttonAction.toLowerCase()
        };
        console.log(popupData)
        try {
          const response = await addPopup(popupData);
          console.log('Add popup successful:', response);
          navigate('/popup');
        } catch (error) {
          if (error.response?.data) {
            console.error('An error occurred:', error.response.data.errors[0].msg);
          } else {
            console.log('An error occurred. Please check your network connection and try again.');
          }
        }
    }
Tools
Biome

[error] 55-55: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

backend/src/controllers/banner.controller.js

71-72: Use Number.isNaN for safer type checking.

Replace isNaN with Number.isNaN to avoid unsafe type coercion.

- if (isNaN(id) || id.trim() === "") {
+ if (Number.isNaN(Number(id)) || id.trim() === "") {
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.

      if (Number.isNaN(Number(id)) || id.trim() === "") {
        return res.status(400).json({ errors: [{ msg: "Invalid id" }] });
Tools
Biome

[error] 71-71: isNaN is unsafe. It attempts a type coercion. Use Number.isNaN instead.

See the MDN documentation for more details.
Unsafe fix: Use Number.isNaN instead.

(lint/suspicious/noGlobalIsNan)

frontend/src/scenes/bannerPage/BannerPage.jsx

24-42: Save function is well-structured.

The onSave function is well-structured, with appropriate error handling and navigation logic.

However, consider using optional chaining for safer error handling.

Apply this diff to address the static analysis hint:

- if (error.response && error.response.data) {
+ if (error.response?.data) {
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.

    const onSave = async () => {
        const bannerData = { 
            backgroundColor:backgroundColor,
            fontColor:fontColor,
            url:url,
            position: isTopPosition ? 'top' : 'bottom',
            closeButtonAction:buttonAction.toLowerCase()
        };
        try {
          const response = await addBanner(bannerData);
          console.log('Add banner successful:', response);
          navigate('/banner');
        } catch (error) {
          if (error.response?.data) {
            console.error('An error occurred:', error.response.data.errors[0].msg);
          } else {
            console.log('An error occurred. Please check your network connection and try again.');
          }
        }
Tools
Biome

[error] 37-37: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

frontend/src/scenes/tours/ProductTour.jsx

36-37: Implement the create item functionality.

The handleCreateItem function is currently empty and should be implemented to handle item creation.

Would you like assistance in implementing this functionality or opening a GitHub issue to track this task?

frontend/src/scenes/hints/HintPage.jsx Outdated Show resolved Hide resolved
frontend/src/scenes/hints/HintPage.jsx Outdated Show resolved Hide resolved
frontend/src/scenes/hints/HintPage.jsx Outdated Show resolved Hide resolved
frontend/src/scenes/hints/HintPage.jsx Outdated Show resolved Hide resolved
frontend/src/scenes/hints/HintPage.jsx Outdated Show resolved Hide resolved
@erenfn
Copy link
Collaborator

erenfn commented Aug 22, 2024

take a look at this PR:

#157

@thomastepi thomastepi merged commit e8a38db into develop Aug 26, 2024
1 check passed
@thomastepi thomastepi deleted the feature/128-implement-hint-page-frontend branch August 26, 2024 06:27
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.

2 participants