feat: update revenues task#21
Conversation
WalkthroughA 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
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)
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)
Estimated code review effort🎯 2 (Simple) | ⏱️ ~8 minutes Poem
Note ⚡️ Unit Test Generation is now available in beta!Learn more here, or try it out under "Finishing Touches" below. 📜 Recent review detailsConfiguration used: CodeRabbit UI 📒 Files selected for processing (2)
✅ Files skipped from review due to trivial changes (1)
🚧 Files skipped from review as they are similar to previous changes (1)
⏰ 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)
✨ Finishing Touches
🧪 Generate unit tests
🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed 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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
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()orPromise.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
📒 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.
| 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) | ||
| }) |
There was a problem hiding this comment.
💡 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 20Length 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 existinggetSession(event)(or equivalent from#auth-utils) at the top
– Return 401 if the session is missing or invalid - Harden date inputs
– Verifystartandendare valid Dates (!isNaN(date.getTime()))
– Ensureendis not beforestart - 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.
| } catch (error) { | ||
| errorResolver(error) | ||
| } |
There was a problem hiding this comment.
🛠️ 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.
| } 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.
|



Summary by CodeRabbit
New Features
Bug Fixes