feat: upload revenue file#20
Conversation
WalkthroughThis change set introduces a complete workflow for uploading, parsing, and displaying kitchen revenue data. It adds new Vue components for file upload and modal dialogs, server API endpoints for revenue data management, database schema and repository enhancements for revenue tracking, and supporting utilities for file validation and localization. Dependencies are updated to support Excel file parsing. Changes
Sequence Diagram(s)sequenceDiagram
participant User
participant WebApp (UI)
participant Modal
participant Form
participant API (Server)
participant DB
User->>WebApp (UI): Click "Добавить выручку"
WebApp (UI)->>Modal: Open Upload Modal
Modal->>Form: Render Upload Form
User->>Form: Select report type & upload XLSX file
Form->>API (Server): POST /api/kitchen/revenue/iiko-daily (with file)
API (Server)->>DB: Parse file, upsert revenues
DB-->>API (Server): Revenue update result
API (Server)-->>Form: Success/Failure response
Form-->>Modal: Emit "success" event
Modal->>WebApp (UI): Close modal, refresh data
WebApp (UI)->>API (Server): GET /api/kitchen/id/[id]/revenue
API (Server)->>WebApp (UI): Return updated revenue data
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 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 as they are similar to previous changes (2)
⏰ 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: 10
🧹 Nitpick comments (5)
apps/web-app/app/components/modal/UploadKitchenRevenue.vue (1)
2-2: Localize the modal title.The title "Загрузка отчета" is hardcoded in Russian. Consider using the i18n system for better maintainability and potential multi-language support.
Apply this diff to localize the title:
- <UModal title="Загрузка отчета"> + <UModal :title="$t('upload.revenue.title')">And add the corresponding key to the localization file:
"upload": { "revenue": { "title": "Загрузка отчета" } }apps/web-app/app/components/form/UploadKitchenRevenue.vue (1)
99-99: Improve error message handling.The error concatenation could result in confusing messages when no errors exist, and the logic could be simplified.
Apply this diff to improve error message formatting:
- const errors = data.result.errors.length ? `Ошибки: ${data.result.errors}` : '' + const errorMessage = data.result.errors.length > 0 ? `Ошибки: ${data.result.errors.join(', ')}` : ''And update the toast message:
actionToast.success( toastId, t('toast.file-loaded'), - `Было добавлено ${data.result.rowsUpdated} ${pluralizationRu(data.result.rowsUpdated, ['запись', 'записи', 'записей'])}. ${errors}`) + `Было добавлено ${data.result.rowsUpdated} ${pluralizationRu(data.result.rowsUpdated, ['запись', 'записи', 'записей'])}.${errorMessage ? ` ${errorMessage}` : ''}`)apps/web-app/server/api/kitchen/revenue/iiko-daily.post.ts (1)
17-23: Add memory usage protection for large files.The xlsx.parse() method loads the entire file into memory, which could cause issues with very large files.
Consider adding memory usage protection:
+ const maxRows = 10000 // Reasonable limit for kitchen data const workSheetsFromFile = xlsx.parse(file.data.buffer) if (!workSheetsFromFile[0]) { throw createError({ statusCode: 404, message: 'File not found', }) } + const data = workSheetsFromFile[0].data + if (data.length > maxRows) { + throw createError({ + statusCode: 413, + message: `File contains too many rows. Maximum allowed: ${maxRows}`, + }) + }packages/database/src/repository/kitchen.ts (1)
37-43: Consider making the limit configurable.The hardcoded limit of 1000 records might not be suitable for all use cases and could become a bottleneck for kitchens with extensive revenue history.
Consider making the limit configurable:
- static async listRevenuesByKitchen(kitchenId: string) { + static async listRevenuesByKitchen(kitchenId: string, limit = 1000) { return useDatabase().query.kitchenRevenues.findMany({ where: (revenues, { eq }) => eq(revenues.kitchenId, kitchenId), orderBy: (revenues, { desc }) => desc(revenues.date), - limit: 1000, + limit, }) }packages/database/src/tables.ts (1)
413-413: Consider adding unique constraint for iikoAlias.If
iikoAliasis used as a lookup key (as seen in the API endpoint), it should probably have a unique constraint to prevent duplicates.Consider adding uniqueness if iikoAlias serves as an identifier:
- iikoAlias: varchar('iiko_alias'), + iikoAlias: varchar('iiko_alias').unique(),Or if null values should be allowed but non-null values must be unique, this would need to be handled at the database level with a partial unique index.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
⛔ Files ignored due to path filters (2)
apps/web-app/public/docs/examples/iiko-daily-revenue.jpgis excluded by!**/*.jpgpnpm-lock.yamlis excluded by!**/pnpm-lock.yaml
📒 Files selected for processing (14)
apps/web-app/app/components/form/UploadKitchenRevenue.vue(1 hunks)apps/web-app/app/components/modal/UploadKitchenRevenue.vue(1 hunks)apps/web-app/app/pages/kitchen/[id]/finance.vue(1 hunks)apps/web-app/app/pages/kitchen/index.vue(5 hunks)apps/web-app/i18n/locales/ru-RU.json(1 hunks)apps/web-app/package.json(1 hunks)apps/web-app/server/api/kitchen/id/[kitchenId]/revenue.get.ts(1 hunks)apps/web-app/server/api/kitchen/revenue/iiko-daily.post.ts(1 hunks)apps/web-app/shared/services/file.ts(1 hunks)packages/database/src/repository/kitchen.ts(3 hunks)packages/database/src/tables.ts(2 hunks)packages/database/src/types.ts(1 hunks)packages/ui/app/composables/useActionToast.ts(1 hunks)pnpm-workspace.yaml(1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
apps/web-app/server/api/kitchen/id/[kitchenId]/revenue.get.ts (1)
packages/database/src/repository/client.ts (1)
listReviewsOfKitchen(30-34)
packages/database/src/repository/kitchen.ts (2)
packages/database/src/types.ts (2)
KitchenDraft(88-88)KitchenRevenueDraft(91-91)packages/database/src/tables.ts (2)
kitchens(398-415)kitchenRevenues(417-424)
🔇 Additional comments (19)
pnpm-workspace.yaml (1)
50-50: Dependency “node-xlsx@^0.24.0” Verified
- “node-xlsx” latest published version is 0.24.0 (no newer release as of July 2025).
- No public advisories or known security vulnerabilities affect v0.24.0.
- Continue to monitor via
npm auditor your preferred dependency-scanning tools for future advisories.apps/web-app/shared/services/file.ts (2)
3-3: File size limit is appropriate.The 20MB limit is reasonable for Excel files containing revenue data and provides protection against excessively large uploads.
9-16: Well-implemented validation schema.The arktype schema correctly validates file size and MIME types, with proper error message localization. The type inference and export structure follow TypeScript best practices.
apps/web-app/package.json (1)
28-28: LGTM!The dependency addition follows the project's pnpm workspace catalog pattern correctly and is placed in proper alphabetical order.
apps/web-app/i18n/locales/ru-RU.json (1)
340-340: LGTM!The Russian translation is accurate and follows the existing toast message naming convention. The placement is appropriate within the toast section.
apps/web-app/app/components/modal/UploadKitchenRevenue.vue (2)
4-7: Consider UX implications of closing modal on 'submitted' event.The modal closes on both 'submitted' and 'success' events. This means the modal closes immediately when the form is submitted, before knowing if the upload succeeded or failed. Consider if users should see upload progress or wait for confirmation.
Would it be better UX to:
- Close only on 'success' and show errors inline, or
- Keep current behavior where modal closes immediately on submission?
This depends on the FormUploadKitchenRevenue implementation and whether it shows loading states.
12-14: Clean composition API usage.The setup script correctly uses the useOverlay() composable with proper TypeScript typing. The implementation is concise and follows Vue 3 best practices.
packages/database/src/types.ts (1)
90-91: LGTM! Type definitions follow established patterns.The new
KitchenRevenueandKitchenRevenueDrafttype aliases are correctly implemented using Drizzle ORM's type inference utilities and maintain consistency with the existing codebase structure.apps/web-app/server/api/kitchen/id/[kitchenId]/revenue.get.ts (1)
1-13: LGTM! Clean API endpoint implementation.The endpoint correctly handles parameter extraction, validation, and error responses. The implementation follows established patterns and best practices for the codebase.
packages/ui/app/composables/useActionToast.ts (1)
22-25: LGTM! Backward-compatible enhancement for customizable success messages.The optional
descriptionparameter allows for more flexible toast notifications while maintaining backward compatibility through the sensible default fallback.apps/web-app/app/pages/kitchen/index.vue (5)
2-12: LGTM! Well-structured upload button implementation.The upload button follows the established UI patterns with proper styling, icon usage, and responsive classes. The click handler correctly references the modal instance.
109-111: LGTM! Revenue cell template properly displays formatted data.The template correctly displays the
revenueForThisWeekvalue with proper currency formatting.
236-249: LGTM! Sortable column implementation follows established patterns.The revenue column implementation matches the pattern used by other sortable columns in the table, with proper header rendering and sorting functionality.
153-153: LGTM! Proper component import.The modal component import follows the established pattern for component imports in this codebase.
275-276: LGTM! Correct modal setup using overlay system.The modal instance creation follows the established overlay pattern used throughout the application.
packages/database/src/repository/kitchen.ts (2)
19-26: LGTM! Proper SQL date comparison implementation.The date comparison using
sqltemplate literal is secure and follows the established pattern from the codebase. The query structure correctly handles date equality while avoiding SQL injection risks.
58-61: LGTM! Consistent automatic timestamp updates.The addition of automatic
updatedAttimestamp usingsqlnow()`` is consistent with the newupdateRevenuemethod and follows good database practices.packages/database/src/tables.ts (2)
412-413: LGTM! Appropriate schema additions to kitchens table.The addition of
revenueForThisWeekandiikoAliasfields follows the existing table patterns with proper data types and sensible defaults.
804-812: LGTM! Proper relation definitions.The bidirectional relations between
kitchensandkitchenRevenuesare correctly defined with proper field mappings and references.
| <UFileUpload | ||
| v-model="state.file" | ||
| color="neutral" | ||
| highlight | ||
| label="Перетащите свой файл сюда" | ||
| description="XLSX" | ||
| class="min-h-28" | ||
| /> |
There was a problem hiding this comment.
🛠️ Refactor suggestion
Add explicit MIME type validation for enhanced security.
The file upload component only validates file extensions through the schema, but should also validate MIME types to prevent malicious file uploads disguised with valid extensions.
Consider adding MIME type validation:
<UFileUpload
v-model="state.file"
+ accept=".xlsx,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
color="neutral"
highlight
label="Перетащите свой файл сюда"
description="XLSX"
class="min-h-28"
/>📝 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.
| <UFileUpload | |
| v-model="state.file" | |
| color="neutral" | |
| highlight | |
| label="Перетащите свой файл сюда" | |
| description="XLSX" | |
| class="min-h-28" | |
| /> | |
| <UFileUpload | |
| v-model="state.file" | |
| accept=".xlsx,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" | |
| color="neutral" | |
| highlight | |
| label="Перетащите свой файл сюда" | |
| description="XLSX" | |
| class="min-h-28" | |
| /> |
🤖 Prompt for AI Agents
In apps/web-app/app/components/form/UploadKitchenRevenue.vue around lines 28 to
35, the UFileUpload component currently only validates file extensions but lacks
MIME type validation, which is a security risk. Enhance the file validation by
adding explicit MIME type checks in the component or the form validation schema
to ensure only allowed MIME types (e.g., for XLSX files) are accepted. This can
be done by adding a MIME type validation rule or prop to the UFileUpload
component or by validating the file's MIME type in the form submission handler.
| } catch (error) { | ||
| console.error(error) | ||
| actionToast.error(toastId) | ||
| } |
There was a problem hiding this comment.
🛠️ Refactor suggestion
Enhance error handling and logging.
Console.error might not be appropriate for production, and users don't get specific error information.
Consider implementing proper error logging and user feedback:
} catch (error) {
- console.error(error)
+ const logger = useLogger('upload-kitchen-revenue')
+ logger.error('Failed to upload kitchen revenue file', error)
actionToast.error(toastId)
}Committable suggestion skipped: line range outside the PR's diff.
🤖 Prompt for AI Agents
In apps/web-app/app/components/form/UploadKitchenRevenue.vue around lines 106 to
109, replace the generic console.error call with a more robust error logging
mechanism suitable for production, such as sending the error details to a
centralized logging service. Additionally, improve user feedback by providing a
specific and informative error message through the actionToast.error method
instead of just passing toastId, so users understand what went wrong.
| <template> | ||
| <Content> | ||
| <div>В разработке</div> | ||
| <div>{{ data }}</div> |
There was a problem hiding this comment.
🛠️ Refactor suggestion
Consider improving data presentation and error handling.
Displaying raw data with {{ data }} will show JSON output, which isn't user-friendly. Consider formatting the revenue data appropriately for the UI.
- <div>{{ data }}</div>
+ <div v-if="pending">Loading...</div>
+ <div v-else-if="error">Error loading revenue data</div>
+ <div v-else-if="data">
+ <!-- Format revenue data appropriately -->
+ <pre>{{ JSON.stringify(data, null, 2) }}</pre>
+ </div>📝 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.
| <div>{{ data }}</div> | |
| <div v-if="pending">Loading...</div> | |
| <div v-else-if="error">Error loading revenue data</div> | |
| <div v-else-if="data"> | |
| <!-- Format revenue data appropriately --> | |
| <pre>{{ JSON.stringify(data, null, 2) }}</pre> | |
| </div> |
🤖 Prompt for AI Agents
In apps/web-app/app/pages/kitchen/[id]/finance.vue at line 3, the raw data is
displayed directly using {{ data }}, which results in unformatted JSON output
that is not user-friendly. Replace this with properly formatted presentation of
the revenue data, such as displaying key fields with labels and formatting
numbers as currency. Additionally, add error handling to display a user-friendly
message if the data is missing or invalid.
| <script setup lang="ts"> | ||
| const { params } = useRoute('kitchen-id') | ||
| const { data } = useFetch(`/api/kitchen/id/${params.id}/revenue`) | ||
| </script> |
There was a problem hiding this comment.
🛠️ Refactor suggestion
Add error handling to the data fetching.
The current implementation doesn't handle loading states or errors from the API call.
-const { data } = useFetch(`/api/kitchen/id/${params.id}/revenue`)
+const { data, pending, error } = useFetch(`/api/kitchen/id/${params.id}/revenue`)📝 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.
| <script setup lang="ts"> | |
| const { params } = useRoute('kitchen-id') | |
| const { data } = useFetch(`/api/kitchen/id/${params.id}/revenue`) | |
| </script> | |
| <script setup lang="ts"> | |
| const { params } = useRoute('kitchen-id') | |
| -const { data } = useFetch(`/api/kitchen/id/${params.id}/revenue`) | |
| +const { data, pending, error } = useFetch(`/api/kitchen/id/${params.id}/revenue`) | |
| </script> |
🤖 Prompt for AI Agents
In apps/web-app/app/pages/kitchen/[id]/finance.vue around lines 7 to 10, the
data fetching using useFetch lacks error handling and loading state management.
Update the code to destructure and handle loading and error states from
useFetch, such as adding variables for isLoading and error, and implement
conditional logic or UI feedback to manage these states appropriately during the
API call lifecycle.
| // Every kitchen: find in DB and add amount for this day | ||
| const kitchens = await repository.kitchen.list() | ||
| let rowsUpdated = 0 | ||
| const errors: string[] = [] | ||
|
|
||
| for (const kitchen of parsedKitchens) { | ||
| const found = kitchens.find((k) => k.iikoAlias === kitchen.name) | ||
| if (found) { | ||
| // Create or update | ||
| const revenue = await repository.kitchen.findRevenueByKitchenAndDate(found.id, date) | ||
| if (!revenue) { | ||
| await repository.kitchen.createRevenue({ | ||
| kitchenId: found.id, | ||
| date: dateOnly, | ||
| total: kitchen.total, | ||
| }) | ||
| } else { | ||
| await repository.kitchen.updateRevenue(revenue.id, { | ||
| total: kitchen.total, | ||
| }) | ||
| } | ||
|
|
||
| rowsUpdated++ | ||
| continue | ||
| } | ||
|
|
||
| logger.warn(`Kitchen "${kitchen.name}" from file not found`) | ||
| errors.push(`"${kitchen.name}" не найдена.`) | ||
| } |
There was a problem hiding this comment.
🛠️ Refactor suggestion
Wrap database operations in a transaction.
Multiple database operations could leave the system in an inconsistent state if one fails partway through processing.
Consider wrapping the database operations in a transaction:
// Every kitchen: find in DB and add amount for this day
const kitchens = await repository.kitchen.list()
let rowsUpdated = 0
const errors: string[] = []
+ const db = useDatabase()
+ await db.transaction(async (tx) => {
for (const kitchen of parsedKitchens) {
const found = kitchens.find((k) => k.iikoAlias === kitchen.name)
if (found) {
// Create or update
const revenue = await repository.kitchen.findRevenueByKitchenAndDate(found.id, date)
if (!revenue) {
await repository.kitchen.createRevenue({
kitchenId: found.id,
date: dateOnly,
total: kitchen.total,
})
} else {
await repository.kitchen.updateRevenue(revenue.id, {
total: kitchen.total,
})
}
rowsUpdated++
continue
}
logger.warn(`Kitchen "${kitchen.name}" from file not found`)
errors.push(`"${kitchen.name}" не найдена.`)
}
+ })Committable suggestion skipped: line range outside the PR's diff.
🤖 Prompt for AI Agents
In apps/web-app/server/api/kitchen/revenue/iiko-daily.post.ts around lines 78 to
106, the database operations for creating or updating kitchen revenue are not
wrapped in a transaction, risking partial updates if an error occurs. Refactor
the code to wrap the entire loop of database operations inside a single
transaction using the repository or database client's transaction API. This
ensures all updates succeed or fail atomically, maintaining data consistency.
| return useDatabase().query.kitchenRevenues.findFirst({ | ||
| where: (revenues, { eq, and }) => and( | ||
| eq(revenues.kitchenId, kitchenId), | ||
| sql`date(${revenues.date}) = date(${date})`, // Same date |
There was a problem hiding this comment.
💡 Verification agent
🧩 Analysis chain
Verify database indexing for date queries.
The date-based query in findRevenueByKitchenAndDate could benefit from a composite index for optimal performance.
Please verify that there's a database index on (kitchenId, date) for the kitchen_revenues table to optimize this query:
🏁 Script executed:
#!/bin/bash
# Check for existing indexes on kitchen_revenues table
rg -A 10 -B 5 "kitchen_revenues.*index|index.*kitchen_revenues" --type sqlLength of output: 225
🏁 Script executed:
#!/bin/bash
# Locate any migration directories
fd migrations -t d
# Find where `kitchen_revenues` is defined or referenced
rg -n "kitchen_revenues" -g "*.sql" -g "*.ts"
# Look for SQL index creation statements
rg -i "create\s\+index" -g "*.sql"
# Look for JS/TS migration helpers that add indexes (e.g., Knex, Sequelize)
rg -i "createIndex|addIndex" -g "*.ts"Length of output: 390
#!/bin/bash
# Display the kitchen_revenues table definition to check for indexes or primary key
sed -n '390,460p' packages/database/src/tables.ts#!/bin/bash
# Locate the tables.ts file
fd tables.ts -t f
# Show the definition of kitchenRevenues with surrounding lines
rg -n -A10 -B5 "export const kitchenRevenues" -g packages/database/src/tables.ts
# Search for any index definitions in that file
rg -n "index\s*\(" -g packages/database/src/tables.ts🏁 Script executed:
#!/bin/bash
# Show definition of kitchenRevenues with context
rg -n -A5 -B5 "export const kitchenRevenues" -g packages/database/src/tables.ts
# Dump the table block to inspect for index specifications
sed -n '410,470p' packages/database/src/tables.ts
# Search for any explicit index definitions in tables.ts
rg -n "index" -g packages/database/src/tables.tsLength of output: 4623
Action Required: Add composite index on kitchen_revenues (kitchen_id, date)
We inspected packages/database/src/tables.ts and found no existing index on the kitchen_revenues table. To ensure your findRevenueByKitchenAndDate query performs optimally, please:
-
Create a new migration that adds a composite index on
(kitchen_id, date)forkitchen_revenues. For example:CREATE INDEX idx_kitchen_revenues_kitchen_id_date ON kitchen_revenues (kitchen_id, date);
-
Place the migration in your project’s migrations directory (e.g.,
packages/database/migrations/) according to your setup. -
After adding the migration, verify that the index is created successfully and update any schema snapshots or metadata if your tooling requires it.
🤖 Prompt for AI Agents
In packages/database/src/repository/kitchen.ts at line 23, the query filtering
by kitchen_id and date lacks a supporting index on the kitchen_revenues table,
which can degrade performance. To fix this, create a new database migration file
in packages/database/migrations/ that adds a composite index on (kitchen_id,
date) for the kitchen_revenues table using the SQL statement: CREATE INDEX
idx_kitchen_revenues_kitchen_id_date ON kitchen_revenues (kitchen_id, date);
then run the migration to apply the index and update any schema snapshots or
metadata as required by your tooling.
| export const kitchenRevenues = pgTable('kitchen_revenues', { | ||
| id: cuid2('id').defaultRandom().primaryKey(), | ||
| createdAt: timestamp('created_at', { precision: 3, withTimezone: true, mode: 'string' }).notNull().defaultNow(), | ||
| updatedAt: timestamp('updated_at', { precision: 3, withTimezone: true, mode: 'string' }).notNull().defaultNow(), | ||
| date: date('date', { mode: 'string' }).notNull(), | ||
| total: numeric('total', { mode: 'number' }).notNull().default(0), | ||
| kitchenId: cuid2('kitchen_id').notNull().references(() => kitchens.id), | ||
| }) |
There was a problem hiding this comment.
🛠️ Refactor suggestion
Consider adding unique constraint for data integrity.
The schema allows multiple revenue records for the same kitchen and date, which could lead to data inconsistency issues.
Consider adding a unique constraint on the combination of kitchenId and date:
export const kitchenRevenues = pgTable('kitchen_revenues', {
id: cuid2('id').defaultRandom().primaryKey(),
createdAt: timestamp('created_at', { precision: 3, withTimezone: true, mode: 'string' }).notNull().defaultNow(),
updatedAt: timestamp('updated_at', { precision: 3, withTimezone: true, mode: 'string' }).notNull().defaultNow(),
date: date('date', { mode: 'string' }).notNull(),
total: numeric('total', { mode: 'number' }).notNull().default(0),
kitchenId: cuid2('kitchen_id').notNull().references(() => kitchens.id),
-})
+}, (table) => ({
+ uniqueKitchenDate: unique().on(table.kitchenId, table.date),
+}))📝 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.
| export const kitchenRevenues = pgTable('kitchen_revenues', { | |
| id: cuid2('id').defaultRandom().primaryKey(), | |
| createdAt: timestamp('created_at', { precision: 3, withTimezone: true, mode: 'string' }).notNull().defaultNow(), | |
| updatedAt: timestamp('updated_at', { precision: 3, withTimezone: true, mode: 'string' }).notNull().defaultNow(), | |
| date: date('date', { mode: 'string' }).notNull(), | |
| total: numeric('total', { mode: 'number' }).notNull().default(0), | |
| kitchenId: cuid2('kitchen_id').notNull().references(() => kitchens.id), | |
| }) | |
| export const kitchenRevenues = pgTable('kitchen_revenues', { | |
| id: cuid2('id').defaultRandom().primaryKey(), | |
| createdAt: timestamp('created_at', { precision: 3, withTimezone: true, mode: 'string' }).notNull().defaultNow(), | |
| updatedAt: timestamp('updated_at', { precision: 3, withTimezone: true, mode: 'string' }).notNull().defaultNow(), | |
| date: date('date', { mode: 'string' }).notNull(), | |
| total: numeric('total', { mode: 'number' }).notNull().default(0), | |
| kitchenId: cuid2('kitchen_id').notNull().references(() => kitchens.id), | |
| }, (table) => ({ | |
| uniqueKitchenDate: unique().on(table.kitchenId, table.date), | |
| })); |
🤖 Prompt for AI Agents
In packages/database/src/tables.ts around lines 417 to 424, the kitchenRevenues
table currently allows multiple entries for the same kitchenId and date, risking
data inconsistency. To fix this, add a unique constraint on the combination of
kitchenId and date columns to ensure only one revenue record per kitchen per
date is allowed.
|


Summary by CodeRabbit