Skip to content

feat: update revenues task#21

Merged
hmbanan666 merged 2 commits into
mainfrom
update-revenue-task
Jul 28, 2025
Merged

feat: update revenues task#21
hmbanan666 merged 2 commits into
mainfrom
update-revenue-task

Conversation

@hmbanan666
Copy link
Copy Markdown
Collaborator

@hmbanan666 hmbanan666 commented Jul 28, 2025

Summary by CodeRabbit

  • New Features

    • Introduced an hourly scheduled task to update weekly kitchen revenue automatically.
    • Added an API endpoint to retrieve revenue data for a specific kitchen within a selected time period.
  • Bug Fixes

    • Improved validation for required parameters in the new revenue API endpoint to ensure accurate responses.

@hmbanan666 hmbanan666 self-assigned this Jul 28, 2025
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Jul 28, 2025

Walkthrough

A new scheduled task for updating kitchen revenues weekly has been added to the Nuxt app. Supporting this, a new API endpoint retrieves kitchen revenues for a specified period, and a repository method enables querying revenues within a date range. The scheduled task logic and API handler are both newly implemented.

Changes

Cohort / File(s) Change Summary
Scheduled Task Configuration
apps/web-app/nuxt.config.ts
Added a new scheduled task (kitchen:revenue-update) to run hourly; existing tasks remain unchanged.
Kitchen Revenue API Endpoint
apps/web-app/server/api/kitchen/id/[kitchenId]/revenues-for-period.get.ts
Added a new API route handler to fetch kitchen revenue for a specified period, with parameter validation.
Kitchen Revenue Update Task
apps/web-app/server/tasks/kitchen/revenue-update.ts
Introduced a new scheduled task to aggregate and update weekly kitchen revenues.
Database Repository Extension
packages/database/src/repository/kitchen.ts
Added a static method to query kitchen revenues within a date range.

Sequence Diagram(s)

sequenceDiagram
    participant Scheduler
    participant RevenueUpdateTask
    participant KitchenRepo
    participant Database

    Scheduler->>RevenueUpdateTask: Trigger (hourly)
    RevenueUpdateTask->>KitchenRepo: getAllKitchens()
    KitchenRepo->>Database: SELECT * FROM kitchens
    loop For each kitchen
        RevenueUpdateTask->>KitchenRepo: listRevenuesByKitchenForPeriod(kitchenId, start, end)
        KitchenRepo->>Database: SELECT * FROM kitchenRevenues WHERE kitchenId AND date BETWEEN start AND end
        RevenueUpdateTask->>KitchenRepo: updateKitchenWeeklyRevenue(kitchenId, total)
    end
    RevenueUpdateTask-->>Scheduler: Task result (success/failure)
Loading
sequenceDiagram
    participant Client
    participant APIHandler
    participant KitchenRepo
    participant Database

    Client->>APIHandler: GET /kitchen/id/{kitchenId}/revenues-for-period?start=...&end=...
    APIHandler->>KitchenRepo: listRevenuesByKitchenForPeriod(kitchenId, start, end)
    KitchenRepo->>Database: SELECT * FROM kitchenRevenues WHERE kitchenId AND date BETWEEN start AND end
    KitchenRepo-->>APIHandler: Revenue data
    APIHandler-->>Client: Response (revenue data)
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~8 minutes

Poem

A bunny hopped by the kitchen’s door,
Saw new tasks and endpoints galore!
With revenues tallied, week by week,
And APIs ready for data you seek.
“Hurrah!” said the rabbit, “Let’s crunch and compute—
For kitchens and code, this update’s a hoot!” 🥕

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 4208413 and 0452fc3.

📒 Files selected for processing (2)
  • apps/web-app/server/api/kitchen/id/[kitchenId]/revenues-for-period.get.ts (1 hunks)
  • apps/web-app/server/tasks/kitchen/revenue-update.ts (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • apps/web-app/server/tasks/kitchen/revenue-update.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/web-app/server/api/kitchen/id/[kitchenId]/revenues-for-period.get.ts
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: build
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch update-revenue-task

🪧 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this 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.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

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

@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: 4

🧹 Nitpick comments (1)
apps/web-app/server/tasks/kitchen/revenue-update.ts (1)

23-33: Consider parallel processing for better performance.

Sequential processing of kitchens could become slow as the number of kitchens grows. Consider using Promise.all() or Promise.allSettled() for parallel processing.

Apply this diff to process kitchens in parallel:

- for (const kitchen of kitchens) {
-   const revenues = await repository.kitchen.listRevenuesByKitchenForPeriod(kitchen.id, thisMonday, thisSunday)
-   
-   const revenueForThisWeek = revenues.reduce((acc, curr) => acc + curr.total, 0)
-   
-   await repository.kitchen.update(kitchen.id, {
-     revenueForThisWeek,
-   })
-   
-   // logger.log(`Kitchen ${kitchen.id}: Revenue updated from ${kitchen.revenueForThisWeek} to ${revenueForThisWeek}`)
- }
+ await Promise.allSettled(
+   kitchens.map(async (kitchen) => {
+     try {
+       const revenues = await repository.kitchen.listRevenuesByKitchenForPeriod(kitchen.id, thisMonday, thisSunday)
+       
+       const revenueForThisWeek = revenues.reduce((acc, curr) => acc + curr.total, 0)
+       
+       await repository.kitchen.update(kitchen.id, {
+         revenueForThisWeek,
+       })
+       
+       // logger.log(`Kitchen ${kitchen.id}: Revenue updated from ${kitchen.revenueForThisWeek} to ${revenueForThisWeek}`)
+     } catch (error) {
+       logger.error(`Failed to update revenue for kitchen ${kitchen.id}:`, error)
+     }
+   })
+ )
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 9db2919 and 4208413.

📒 Files selected for processing (4)
  • apps/web-app/nuxt.config.ts (1 hunks)
  • apps/web-app/server/api/kitchen/id/[kitchenId]/revenues-for-period.get.ts (1 hunks)
  • apps/web-app/server/tasks/kitchen/revenue-update.ts (1 hunks)
  • packages/database/src/repository/kitchen.ts (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: build
🔇 Additional comments (2)
packages/database/src/repository/kitchen.ts (1)

45-55: LGTM! Clean implementation with proper parameterization.

The method correctly uses parameterized queries to prevent SQL injection and follows the existing patterns in the codebase. The inclusive date range (>= and <=) is appropriate for period-based queries.

apps/web-app/nuxt.config.ts (1)

41-41: Verify the hourly execution frequency requirement.

The cron expression correctly runs the task every hour at minute 0. However, consider if hourly execution is necessary for weekly revenue aggregation - daily updates might be more appropriate unless there's a specific business requirement for real-time updates.

Comment on lines +3 to +23
export default defineEventHandler(async (event) => {
const kitchenId = getRouterParam(event, 'kitchenId')
if (!kitchenId) {
throw createError({
statusCode: 400,
message: 'Id is required',
})
}

const query = getQuery(event)
const start = query.start ? new Date(query.start.toString()) : null
const end = query.end ? new Date(query.end.toString()) : null
if (!start || !end) {
throw createError({
statusCode: 400,
message: 'Start and end is required',
})
}

return repository.kitchen.listRevenuesByKitchenForPeriod(kitchenId, start, end)
})
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Consider adding authentication and input validation.

The endpoint lacks authentication checks and additional input validation. Consider adding:

  • Authentication/authorization to ensure only authorized users can access kitchen revenue data
  • Date range validation (e.g., end date should be after start date)
  • Rate limiting for API protection

Would you like me to help implement authentication middleware and additional validation for this endpoint?


🏁 Script executed:

#!/bin/bash
# Search for references to authentication mechanisms
rg "auth" -n || true

# Search for any custom middleware definitions
rg "middleware" -n || true

# List a few API route handlers to see common patterns
rg "defineEventHandler" -n | head -n 20

Length of output: 5233


Add authentication, date validation, and rate limiting to this endpoint

This handler currently allows unauthenticated access and only checks for the presence of start/end—it should also:

  • Enforce authentication
    – Use the existing getSession(event) (or equivalent from #auth-utils) at the top
    – Return 401 if the session is missing or invalid
  • Harden date inputs
    – Verify start and end are valid Dates (!isNaN(date.getTime()))
    – Ensure end is not before start
  • Apply rate limiting
    – Protect against abuse (e.g. via a Nuxt rate-limit module or custom middleware)

File to update:

  • apps/web-app/server/api/kitchen/id/[kitchenId]/revenues-for-period.get.ts

Let me know if you’d like assistance wiring up an ensureAuthenticated pre-handler and a small validation util here.

🤖 Prompt for AI Agents
In apps/web-app/server/api/kitchen/id/[kitchenId]/revenues-for-period.get.ts
around lines 3 to 23, add authentication by calling getSession(event) at the
start and throw a 401 error if the session is missing or invalid. Enhance date
validation by checking that start and end are valid Date objects using
!isNaN(date.getTime()) and ensure that end is not before start, throwing a 400
error if these validations fail. Finally, integrate rate limiting middleware or
use a Nuxt rate-limit module to protect this endpoint from abuse.

Comment thread apps/web-app/server/tasks/kitchen/revenue-update.ts
Comment on lines +34 to +36
} catch (error) {
errorResolver(error)
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Improve error handling specificity.

The generic errorResolver(error) might hide specific issues. Consider logging more detailed error information for better debugging.

Apply this diff to improve error handling:

- } catch (error) {
-   errorResolver(error)
- }
+ } catch (error) {
+   logger.error('Failed to update kitchen revenues:', error)
+   errorResolver(error)
+   throw error // Re-throw to indicate task failure
+ }
📝 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
} catch (error) {
errorResolver(error)
}
} catch (error) {
logger.error('Failed to update kitchen revenues:', error)
errorResolver(error)
throw error // Re-throw to indicate task failure
}
🤖 Prompt for AI Agents
In apps/web-app/server/tasks/kitchen/revenue-update.ts around lines 34 to 36,
the current error handling uses a generic call to errorResolver(error), which
may obscure specific error details. Modify the catch block to log detailed error
information such as error message, stack trace, or any relevant properties
before or within the errorResolver call to improve debugging clarity.

@sonarqubecloud
Copy link
Copy Markdown

@hmbanan666 hmbanan666 merged commit 8bbc39a into main Jul 28, 2025
8 checks passed
@hmbanan666 hmbanan666 deleted the update-revenue-task branch July 28, 2025 10:25
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.

1 participant