Skip to content

feat: upload revenue file#20

Merged
hmbanan666 merged 3 commits into
mainfrom
revenue-file
Jul 28, 2025
Merged

feat: upload revenue file#20
hmbanan666 merged 3 commits into
mainfrom
revenue-file

Conversation

@hmbanan666
Copy link
Copy Markdown
Collaborator

@hmbanan666 hmbanan666 commented Jul 28, 2025

Summary by CodeRabbit

  • New Features
    • Added the ability to upload kitchen revenue reports via a dedicated form and modal dialog.
    • Introduced dynamic display of kitchen revenue data on the finance page.
    • Added a button to upload revenue directly from the kitchen list, with real-time sorting and display of weekly revenue.
    • Implemented backend support for uploading and retrieving kitchen revenue data, including Excel file processing.
  • Improvements
    • Enhanced toast notifications with new localized messages and customizable descriptions.
  • Chores
    • Updated dependencies to support Excel file parsing.

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

coderabbitai Bot commented Jul 28, 2025

Walkthrough

This 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

Cohort / File(s) Change Summary
Vue Components: Revenue Upload UI
apps/web-app/app/components/form/UploadKitchenRevenue.vue, apps/web-app/app/components/modal/UploadKitchenRevenue.vue
Added new form and modal components for uploading kitchen revenue reports, including form validation, event handling, and modal overlay integration.
Kitchen Revenue UI Integration
apps/web-app/app/pages/kitchen/index.vue, apps/web-app/app/pages/kitchen/[id]/finance.vue
Integrated the upload modal into the kitchen list page; updated table columns and revenue display; added dynamic data fetching for kitchen finance page.
API Endpoints: Kitchen Revenue
apps/web-app/server/api/kitchen/id/[kitchenId]/revenue.get.ts, apps/web-app/server/api/kitchen/revenue/iiko-daily.post.ts
Introduced GET endpoint for fetching kitchen revenue data and POST endpoint for processing uploaded daily revenue Excel files.
Database: Schema and Repository
packages/database/src/tables.ts, packages/database/src/repository/kitchen.ts, packages/database/src/types.ts
Added kitchenRevenues table, revenue relations, and new repository methods for revenue CRUD; extended kitchens table with weekly revenue and alias fields.
File Validation Utilities
apps/web-app/shared/services/file.ts
Added file validation schema and type for upload file constraints (size/type) using arktype.
Toast Localization and Customization
apps/web-app/i18n/locales/ru-RU.json, packages/ui/app/composables/useActionToast.ts
Added Russian translation for new toast message and enabled optional custom description for success toasts.
Dependency and Workspace Updates
apps/web-app/package.json, pnpm-workspace.yaml
Added node-xlsx dependency for Excel file parsing in both package.json and workspace configuration.

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
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Poem

A rabbit hops with files anew,
Uploads and tables, columns too!
A modal pops, a toast appears,
Revenue numbers—bring the cheers!
With Excel sheets and bytes in tow,
The kitchens' fortunes start to grow.
🐇✨

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 45ffed8 and 57f556f.

📒 Files selected for processing (2)
  • apps/web-app/server/api/kitchen/revenue/iiko-daily.post.ts (1 hunks)
  • apps/web-app/shared/services/file.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • apps/web-app/shared/services/file.ts
  • apps/web-app/server/api/kitchen/revenue/iiko-daily.post.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 revenue-file

🪧 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: 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 iikoAlias is 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

📥 Commits

Reviewing files that changed from the base of the PR and between d0d678b and e2514ca.

⛔ Files ignored due to path filters (2)
  • apps/web-app/public/docs/examples/iiko-daily-revenue.jpg is excluded by !**/*.jpg
  • pnpm-lock.yaml is 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 audit or 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:

  1. Close only on 'success' and show errors inline, or
  2. 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 KitchenRevenue and KitchenRevenueDraft type 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 description parameter 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 revenueForThisWeek value 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 sql template 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 updatedAt timestamp using sqlnow()`` is consistent with the new updateRevenue method and follows good database practices.

packages/database/src/tables.ts (2)

412-413: LGTM! Appropriate schema additions to kitchens table.

The addition of revenueForThisWeek and iikoAlias fields follows the existing table patterns with proper data types and sensible defaults.


804-812: LGTM! Proper relation definitions.

The bidirectional relations between kitchens and kitchenRevenues are correctly defined with proper field mappings and references.

Comment on lines +28 to +35
<UFileUpload
v-model="state.file"
color="neutral"
highlight
label="Перетащите свой файл сюда"
description="XLSX"
class="min-h-28"
/>
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

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.

Suggested change
<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.

Comment on lines +106 to +109
} catch (error) {
console.error(error)
actionToast.error(toastId)
}
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

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

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.

Suggested change
<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.

Comment on lines +7 to +10
<script setup lang="ts">
const { params } = useRoute('kitchen-id')
const { data } = useFetch(`/api/kitchen/id/${params.id}/revenue`)
</script>
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

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.

Suggested change
<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.

Comment thread apps/web-app/server/api/kitchen/revenue/iiko-daily.post.ts
Comment thread apps/web-app/server/api/kitchen/revenue/iiko-daily.post.ts Outdated
Comment on lines +78 to +106
// 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}" не найдена.`)
}
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

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.

Comment thread apps/web-app/shared/services/file.ts Outdated
return useDatabase().query.kitchenRevenues.findFirst({
where: (revenues, { eq, and }) => and(
eq(revenues.kitchenId, kitchenId),
sql`date(${revenues.date}) = date(${date})`, // Same date
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

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 sql

Length 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.ts

Length 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) for kitchen_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.

Comment on lines +417 to +424
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),
})
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

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.

Suggested change
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.

@sonarqubecloud
Copy link
Copy Markdown

Quality Gate Failed Quality Gate failed

Failed conditions
3.2% Duplication on New Code (required ≤ 3%)

See analysis details on SonarQube Cloud

@hmbanan666 hmbanan666 merged commit 9db2919 into main Jul 28, 2025
7 of 8 checks passed
@hmbanan666 hmbanan666 deleted the revenue-file branch July 28, 2025 09:37
This was referenced Jul 28, 2025
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