Skip to content

feat: upload several files#22

Merged
hmbanan666 merged 3 commits into
mainfrom
chore-revenue
Jul 29, 2025
Merged

feat: upload several files#22
hmbanan666 merged 3 commits into
mainfrom
chore-revenue

Conversation

@hmbanan666
Copy link
Copy Markdown
Collaborator

@hmbanan666 hmbanan666 commented Jul 28, 2025

Summary by CodeRabbit

  • New Features
    • Support for uploading and processing multiple Excel files simultaneously.
    • Updated file upload form to allow selecting multiple files with improved success messages reflecting batch processing results.
  • Bug Fixes
    • Enhanced Excel parsing to dynamically detect relevant columns, improving reliability with varying file formats.
    • Added validation for required columns and file size/type restrictions, ensuring clearer error feedback.
  • Localization
    • Added new translation key for batch file processing success notifications.

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

coderabbitai Bot commented Jul 28, 2025

Walkthrough

The code refactors the kitchen revenue upload feature to support multiple Excel files instead of a single file. It introduces dynamic column identification from a dictionary row for kitchen name and revenue, processes each uploaded file to update or create revenue records, and consolidates results and errors. The frontend and validation schema were updated accordingly to handle multiple file uploads.

Changes

Cohort / File(s) Change Summary
Backend API and Parsing Logic
apps/web-app/server/api/kitchen/revenue/iiko-daily.post.ts
Refactored to support multiple uploaded Excel files; added dynamic column index detection from dictionary row; centralized error handling; processes each file and accumulates results.
Frontend Upload Component
apps/web-app/app/components/form/UploadKitchenRevenue.vue
Updated file upload UI and state to support multiple files; changed label to plural; modified form submission to send multiple files; updated success toast message with pluralization.
File Upload Validation Schema
apps/web-app/shared/services/file.ts
Changed upload schema from single file to array of files; updated TypeScript types to reflect multiple file uploads; exported constants for max file size and accepted types.
Localization
apps/web-app/i18n/locales/ru-RU.json
Added new translation key "toast.files-handled" for success toast message when multiple files are processed.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • feat: upload revenue file #20: Introduced the initial single-file upload API and Vue component for kitchen revenue reports, which this PR extends to support multiple files and refactors.

Poem

🐇✨
Through fields of files, the rabbit leaps,
From one to many, the harvest reaps.
Columns found by dictionary's guide,
Errors logged, no need to hide.
Uploads dance in plural cheer,
Kitchen sums now crystal clear!
Hop along, the data sings—
Multiple files, new joy it brings! 📊🐰

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 876b244 and 9b9e397.

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

🪧 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: 0

🧹 Nitpick comments (1)
apps/web-app/server/api/kitchen/revenue/iiko-daily.post.ts (1)

53-68: Remove redundant dictionary validation.

The dictionary validation is performed twice - once on line 54 and again on line 63. The second check is redundant since the dictionary has already been validated.

Apply this diff to remove the redundant check:

 const indexOfName = dictionary.indexOf('Группа')
 const indexOfTotal = dictionary.indexOf('Сумма со скидкой, р. Всего')
-if (!dictionary || indexOfName < 0 || indexOfTotal < 0) {
+if (indexOfName < 0 || indexOfTotal < 0) {
   throw createError({
     statusCode: 400,
     message: 'Invalid dictionary',
   })
 }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 8bbc39a and 9a0645a.

📒 Files selected for processing (1)
  • apps/web-app/server/api/kitchen/revenue/iiko-daily.post.ts (2 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 (1)
apps/web-app/server/api/kitchen/revenue/iiko-daily.post.ts (1)

101-102: LGTM! Excellent improvement to use dynamic column indices.

This change makes the code more resilient to changes in the Excel file structure by using dynamically determined column indices instead of hardcoded values. The implementation correctly uses the indices found from the dictionary row.

@hmbanan666 hmbanan666 changed the title chore: revenue upload updated feat: upload several files Jul 28, 2025
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: 2

🧹 Nitpick comments (1)
apps/web-app/server/api/kitchen/revenue/iiko-daily.post.ts (1)

12-16: Consider eliminating code duplication.

These constants duplicate the values from the shared file schema. Consider importing them from the shared service to maintain DRY principle.

+import { MAX_FILE_SIZE, ACCEPTED_FILE_TYPES } from '~~/shared/services/file'
-const MAX_FILE_SIZE = 20 * 1024 * 1024 // 20MB
-const ACCEPTED_FILE_TYPES = [
-  'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
-  'application/vnd.ms-excel',
-]

Note: You'll need to export these constants from the shared file service.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 9a0645a and 876b244.

📒 Files selected for processing (4)
  • apps/web-app/app/components/form/UploadKitchenRevenue.vue (4 hunks)
  • apps/web-app/i18n/locales/ru-RU.json (1 hunks)
  • 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 due to trivial changes (1)
  • apps/web-app/i18n/locales/ru-RU.json
⏰ 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 (6)
apps/web-app/shared/services/file.ts (1)

14-14: LGTM! Clean schema update for multiple file support.

The change from single file to array of files is correctly implemented, maintaining the same validation constraints for each file while enabling multiple uploads.

apps/web-app/app/components/form/UploadKitchenRevenue.vue (2)

77-77: LGTM! Correct state initialization for multiple files.

The state is properly initialized as an empty array to handle multiple files.


91-93: LGTM! Proper FormData handling for multiple files.

The iteration through files and appending each to FormData under the 'files' key is correctly implemented.

apps/web-app/server/api/kitchen/revenue/iiko-daily.post.ts (3)

31-35: LGTM! Good aggregation of results across multiple files.

The logic properly accumulates rows updated and errors from all processed files, providing a comprehensive result to the client.


83-89: LGTM! Improved flexibility with dynamic column detection.

Using the dictionary row to determine column indices is much better than hardcoded values, making the parser more resilient to changes in Excel file structure.


91-98: Verify Excel column names consistency

No references to the headers ‘Группа’ or ‘Сумма со скидкой, р. Всего’ were found in the repository (docs, test data or code). Please ensure that:

  • All incoming Excel files use these exact column names.
  • You surface a sample/template spreadsheet or document these headers (e.g. in docs/ or a test/data/ folder).
  • Consider adding a unit or integration test that validates the header row to catch any future changes.

Comment thread apps/web-app/app/components/form/UploadKitchenRevenue.vue Outdated
Comment on lines +149 to +172
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,
})
}

logger.warn(`Kitchen "${kitchen.name}" from file not found`)
errors.push(`"${kitchen.name}" не найдена.`)
rowsUpdated++
continue
}

logger.log(rowsUpdated, date, parsedKitchens)
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

Consider adding database transaction support for better error handling.

Each file's database operations are not wrapped in a transaction. If an error occurs partway through processing a file's data, some records might be updated while others aren't, leading to inconsistent state.

Consider wrapping the database operations for each file in a transaction:

  for (const kitchen of parsedKitchens) {
    const found = kitchens.find((k) => k.iikoAlias === kitchen.name)
    if (found) {
+     // Wrap in transaction if supported by your repository
+     await repository.transaction(async (tx) => {
        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
    }
📝 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
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,
})
}
logger.warn(`Kitchen "${kitchen.name}" from file not found`)
errors.push(`"${kitchen.name}" не найдена.`)
rowsUpdated++
continue
}
logger.log(rowsUpdated, date, parsedKitchens)
logger.warn(`Kitchen "${kitchen.name}" from file not found`)
errors.push(`"${kitchen.name}" не найдена.`)
}
for (const kitchen of parsedKitchens) {
const found = kitchens.find((k) => k.iikoAlias === kitchen.name)
if (found) {
// Wrap in transaction if supported by your repository
await repository.transaction(async (tx) => {
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}" не найдена.`)
}
🤖 Prompt for AI Agents
In apps/web-app/server/api/kitchen/revenue/iiko-daily.post.ts around lines 149
to 172, the database operations for each kitchen are not wrapped in a
transaction, risking partial updates and inconsistent state if an error occurs.
To fix this, wrap the entire loop or the processing of each file's data in a
database transaction using your repository or ORM's transaction API. Begin a
transaction before processing, commit it after all operations succeed, and roll
back if any error occurs to ensure atomicity and consistency.

@sonarqubecloud
Copy link
Copy Markdown

@hmbanan666 hmbanan666 merged commit 4b6b86c into main Jul 29, 2025
8 checks passed
@hmbanan666 hmbanan666 deleted the chore-revenue branch July 29, 2025 07:36
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