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

535 tour url services #538

Merged
merged 6 commits into from
Feb 13, 2025
Merged

535 tour url services #538

merged 6 commits into from
Feb 13, 2025

Conversation

DeboraSerra
Copy link
Contributor

Describe your changes

create get_tour_by_url route similar to popup

create getIncompleteToursByUrl in tour.service

create getCompleteTours in guidelog.service

call getCompleteTours in getGuidesByUrl and getIncompleteGuidesByUrl in guide.controller like we did for other guides

image

Issue number

#535

Please ensure all items are checked off before requesting a review:

  • I deployed the code locally.
  • I have performed a self-review of my code.
  • I have included the issue # in the PR.
  • I have labelled the PR correctly.
  • The issue I am working on is assigned to me.
  • I didn't use any hardcoded values (otherwise it will not scale, and will make it difficult to maintain consistency across the application).
  • I made sure font sizes, color choices etc are all referenced from the theme.
  • My PR is granular and targeted to one specific feature.
  • I took a screenshot or a video and attached to this PR if there is a UI change.

Copy link
Contributor

coderabbitai bot commented Feb 12, 2025

Walkthrough

This pull request introduces enhancements for tour-related functionality across multiple components. In the GuideController, the getGuidesByUrl and getIncompleteGuidesByUrl methods now include a tour property by invoking tourService and guidelogService. A new method, getTourByUrl, is added to the TourController to retrieve tours based on a URL. The routing layer is improved with a new URL validation middleware, and service layers are expanded with methods for fetching complete and filtered tour logs. Error handling and formatting practices remain consistent.

Changes

File(s) Change Summary
backend/src/controllers/guide.controller.js, backend/src/controllers/tour.controller.js In GuideController, updated getGuidesByUrl and getIncompleteGuidesByUrl to include a tour property by invoking tourService.getTourByUrl(url) and guidelogService.getCompleteToursLogs(userId) respectively. In TourController, added the new getTourByUrl method to retrieve tours based on a URL.
backend/src/service/guidelog.service.js, backend/src/service/tour.service.js In GuideLogService, added getCompleteToursLogs for retrieving complete tour logs. In TourService, introduced getTourByUrl(url) and getIncompleteTourByUrl(url, ids) with improved error handling and consistent formatting.
backend/src/routes/tour.routes.js, backend/src/utils/tour.helper.js Updated the tours route to include the new bodyUrlValidator middleware for validating the URL in incoming requests. Added and exported a new validator (bodyUrlValidator) in the tour helper module.
backend/src/models/index.js Updated the association definition for Tour and TourPopup models, changing the alias from "popups" to "steps".

Sequence Diagram(s)

sequenceDiagram
  participant C as Client
  participant R as Router
  participant V as Validator
  participant TC as TourController
  participant TS as TourService
  C->>R: GET /get_tour_by_url with { url }
  R->>V: Validate request body (url)
  V-->>R: Validation passed
  R->>TC: Call getTourByUrl(req, res)
  TC->>TS: getTourByUrl(url)
  TS-->>TC: Return tour data
  TC-->>R: Response with tour JSON
  R-->>C: Send tour data response
Loading
sequenceDiagram
  participant C as Client
  participant GC as GuideController
  participant TS as TourService
  participant GL as GuideLogService
  C->>GC: GET /guides?url=... (or incomplete guides)
  GC->>TS: getTourByUrl(url)
  TS-->>GC: Return tour data
  alt Incomplete Guides Request
    GC->>GL: getCompleteToursLogs(userId)
    GL-->>GC: Return complete tour logs
  end
  GC-->>C: Respond with { banner, popup, hint, helperLink, tour }
Loading

Possibly related PRs

Suggested reviewers

  • swoopertr
✨ 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:

‼️ 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 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: 5

🧹 Nitpick comments (5)
backend/src/utils/tour.helper.js (1)

40-42: Mom's spaghetti! DRY principle violation spotted!

The URL validation logic is duplicated between tourValidator and bodyUrlValidator. Consider extracting the common validation chain into a reusable constant:

+const urlValidationChain = body('url')
+  .isString()
+  .withMessage('url is required')
+  .custom(validateUrl)
+  .withMessage('Invalid value for url');

 const tourValidator = [
-  body('url').isString().withMessage('url is required').custom(validateUrl).withMessage('Invalid value for url'),
+  urlValidationChain,
   // ... other validations
 ];

 const bodyUrlValidator = [
-  body('url').isString().withMessage('url is required').custom(validateUrl).withMessage('Invalid value for url'),
+  urlValidationChain,
 ];
backend/src/controllers/guide.controller.js (1)

14-16: URL validation logic is duplicated! Mom's spaghetti!

Extract the common URL validation logic into a reusable function to avoid duplication:

+const validateUrlInput = (url) => {
+  if (!url || typeof url !== 'string') {
+    return { error: { errors: [{ msg: 'URL is missing or invalid' }] } };
+  }
+  return null;
+};

 async getGuidesByUrl(req, res) {
   try {
     const { url } = req.body;
-    if (!url || typeof url !== 'string') {
-      return res.status(400).json({ errors: [{ msg: 'URL is missing or invalid' }] });
+    const validationError = validateUrlInput(url);
+    if (validationError) {
+      return res.status(400).json(validationError.error);
     }
     // ... rest of the code

Also applies to: 34-36

backend/src/controllers/tour.controller.js (1)

45-54: Yo, we need some additional validation checks, eh?

The method looks solid overall, but we should add some validation to handle empty or malformed URLs, just like mom's spaghetti - you gotta cook it right.

Here's a suggested improvement:

  async getTourByUrl(req, res) {
    try {
      const { url } = req.body;
+     if (!url || typeof url !== 'string') {
+       return res.status(400).json({
+         errors: [{ msg: 'Valid URL is required, eh?' }],
+       });
+     }
      const tours = await TourService.getTourByUrl(url);
+     if (!tours || tours.length === 0) {
+       return res.status(404).json({
+         errors: [{ msg: 'No tours found for the specified URL' }],
+       });
+     }
      res.status(200).json(tours);
    } catch (err) {
      const { statusCode, payload } = internalServerError('GET_TOUR_BY_URL_ERROR', err.message);
      res.status(statusCode).json(payload);
    }
  }
backend/src/service/guidelog.service.js (2)

85-97: Opportunity to optimize the database query, eh?

The implementation looks clean like a fresh Canadian snow, but we could add an index to improve query performance when you're nervous with sweaty palms.

Add an index on the frequently queried columns:

CREATE INDEX idx_guidelog_user_complete_type ON guide_logs(userId, completed, guideType);

This will help when your knees are weak but the query needs to be strong.


9-18: Let's keep the transaction handling consistent across methods, eh?

The transaction handling in addGuideLog is solid, but we should consider adding similar transaction support to other write operations that might be added in the future.

Consider creating a helper method to standardize transaction handling:

async function withTransaction(callback) {
  const transaction = await db.sequelize.transaction();
  try {
    const result = await callback(transaction);
    await transaction.commit();
    return result;
  } catch (err) {
    await transaction.rollback();
    throw err;
  }
}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 3adf9a3 and 21f237a.

📒 Files selected for processing (6)
  • backend/src/controllers/guide.controller.js (1 hunks)
  • backend/src/controllers/tour.controller.js (1 hunks)
  • backend/src/routes/tour.routes.js (1 hunks)
  • backend/src/service/guidelog.service.js (5 hunks)
  • backend/src/service/tour.service.js (3 hunks)
  • backend/src/utils/tour.helper.js (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: build (22.x)

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 (1)
backend/src/models/index.js (1)

51-52: The new association naming is cleaner and more intuitive!

Changing from popups to steps better represents the relationship between Tour and TourPopup models. Each popup is really a step in the tour sequence.

Consider also adding an order field to TourPopup if not already present, to maintain the sequence of steps in a tour.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 9092a04 and 0c44e9d.

📒 Files selected for processing (2)
  • backend/src/models/index.js (1 hunks)
  • backend/src/service/tour.service.js (3 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: build (22.x)
🔇 Additional comments (4)
backend/src/service/tour.service.js (4)

2-2: Mom's spaghetti looks good! Import is properly placed!

The Sequelize Op import is correctly added and necessary for the new query operations.


24-41: Knees weak! Error handling needs strengthening!

The error handling could be improved:

  1. Replace console.log with proper logging service
  2. Include the actual error in the thrown Error message for better debugging

However, the implementation itself is solid with proper use of:

  • Active flag filtering
  • Related steps inclusion
  • Sequelize operators

43-57: Arms are heavy! Same error handling issues here!

Vomit on his sweater already! Consider pagination for large datasets!

The Op.notIn operation could be inefficient for large sets of IDs. Consider adding pagination or limiting the result set size.

 async getIncompleteTourByUrl(url, ids) {
   try {
     return await Tour.findAll({
       where: {
         url,
         id: {
           [Op.notIn]: ids,
         },
       },
+      limit: 100, // Add reasonable limit
+      offset: 0, // Add offset for pagination
     });
   } catch (err) {
     console.log(err);
     throw new Error('Error finding incomplete tours by url');
   }
 }

94-94: He's nervous, but the semicolon looks calm and ready!

The added semicolon maintains consistent code formatting.

@DeboraSerra DeboraSerra requested a review from erenfn February 13, 2025 01:15
@DeboraSerra DeboraSerra merged commit 4b2dd50 into develop Feb 13, 2025
2 checks passed
@DeboraSerra DeboraSerra linked an issue Feb 14, 2025 that may be closed by this pull request
4 tasks
This was referenced Feb 18, 2025
@erenfn erenfn deleted the 535-tour-url-services branch March 5, 2025 21:07
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.

Tour URL services
2 participants