Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions apps/web-app/nuxt.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ export default defineNuxtConfig({
},
scheduledTasks: {
'* * * * *': ['task:auto-create'], // Every minute
'0 * * * *': ['kitchen:revenue-update'], // Every hour
'0 0 * * *': ['kitchen:rating-update'], // Every day
},
},
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { repository } from '@roll-stack/database'

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',
})
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.

return repository.kitchen.listRevenuesByKitchenForPeriod(kitchenId, start, end)
})
Comment on lines +3 to +23

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.

40 changes: 40 additions & 0 deletions apps/web-app/server/tasks/kitchen/revenue-update.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { repository } from '@roll-stack/database'
import { endOfWeek, startOfWeek } from 'date-fns'

const logger = useLogger('kitchen:revenue-update')

export default defineTask({
meta: {
name: 'kitchen:revenue-update',
description: 'Update weekly revenue of kitchens',
},
async run() {
try {
const kitchens = await repository.kitchen.list()

// From this monday to sunday (use UTC+0 time zone)
const now = new Date()

const thisMonday = startOfWeek(now, { weekStartsOn: 1 })
const thisSunday = endOfWeek(now, { weekStartsOn: 1 })

Comment thread
coderabbitai[bot] marked this conversation as resolved.
logger.log(thisMonday, thisSunday)

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}`)
}
} catch (error) {
errorResolver(error)
}
Comment on lines +35 to +37

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.


return { result: true }
},
})
12 changes: 12 additions & 0 deletions packages/database/src/repository/kitchen.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,18 @@ export class Kitchen {
})
}

static async listRevenuesByKitchenForPeriod(kitchenId: string, start: Date, end: Date) {
return useDatabase().query.kitchenRevenues.findMany({
where: (revenues, { eq, and }) => and(
eq(revenues.kitchenId, kitchenId),
sql`date(${revenues.date}) >= date(${start})`,
sql`date(${revenues.date}) <= date(${end})`,
),
orderBy: (revenues, { desc }) => desc(revenues.date),
limit: 1000,
})
}

static async create(data: KitchenDraft) {
const [kitchen] = await useDatabase().insert(kitchens).values(data).returning()
return kitchen
Expand Down