Skip to content

chore: some math#27

Merged
hmbanan666 merged 1 commit into
mainfrom
update
Jul 30, 2025
Merged

chore: some math#27
hmbanan666 merged 1 commit into
mainfrom
update

Conversation

@hmbanan666
Copy link
Copy Markdown
Collaborator

@hmbanan666 hmbanan666 commented Jul 30, 2025

Summary by CodeRabbit

  • New Features

    • Kitchen revenue charts now display two lines: one for total revenue and one for common total, with an enhanced tooltip showing additional metrics.
    • Kitchen revenue data now includes average check, common average check, and common total values for more detailed reporting.
  • Bug Fixes

    • Avoids unnecessary updates to weekly kitchen revenue when values have not changed.
  • Chores

    • Adjusted scheduled tasks and background updates to align with new data fields and improve efficiency.

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

coderabbitai Bot commented Jul 30, 2025

Walkthrough

This set of changes updates the kitchen revenue reporting system to support and process an additional metric, commonTotal, alongside existing revenue data. The changes extend data models, update frontend visualization to display two line series, modify backend parsing and persistence logic, and adjust scheduled tasks and repository queries to align with the new and revised data fields.

Changes

Cohort / File(s) Change Summary
KitchenRevenue chart component
apps/web-app/app/components/chart/KitchenRevenue.client.vue
Extended to support and display two line series (total and commonTotal). Updated prop types, internal data mapping, and tooltip.
Scheduled tasks configuration
apps/web-app/nuxt.config.ts
Removed the 'kitchen:average-update' task from the every-minute cron schedule. No changes to exported entities.
Kitchen revenue daily import API
apps/web-app/server/api/kitchen/revenue/iiko-daily.post.ts
Parses and persists new fields: averageCheck, commonAverageCheck, and commonTotal for each kitchen. Updates database calls accordingly.
Kitchen average update task
apps/web-app/server/tasks/kitchen/average-update.ts
Removes computation and update of individual averageCheck and commonTotal, retaining only commonAverageCheck update logic.
Kitchen revenue weekly update task
apps/web-app/server/tasks/kitchen/revenue-update.ts
Removes logger usage, rounds computed weekly revenue, and skips database update if value unchanged.
Kitchen repository query
packages/database/src/repository/kitchen.ts
Alters listRevenuesToUpdate to filter only on commonAverageCheck == 0, removing previous checks for averageCheck and commonTotal.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Frontend (KitchenRevenue.vue)
    participant Backend API
    participant Database

    User->>Frontend (KitchenRevenue.vue): Load kitchen revenue chart
    Frontend (KitchenRevenue.vue)->>Backend API: Fetch revenue data (including total, commonTotal)
    Backend API->>Database: Query revenue records
    Database-->>Backend API: Return records with total, checks, commonTotal, etc.
    Backend API-->>Frontend (KitchenRevenue.vue): Return data
    Frontend (KitchenRevenue.vue)->>Frontend (KitchenRevenue.vue): Render two line series (total, commonTotal)
    User->>Frontend (KitchenRevenue.vue): Hover chart
    Frontend (KitchenRevenue.vue)->>Frontend (KitchenRevenue.vue): Show tooltip with total, commonTotal, and averages
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~18 minutes

Possibly related PRs

  • feat: revenue graph #25: Introduced the initial KitchenRevenue chart component, which is directly extended and modified by this PR to support multiple line series and new data fields.

Poem

In the kitchen where numbers align,
Two lines now dance, both bold and fine.
Totals and commons, side by side,
With averages and checks, our data's pride.
The charts now tell a richer tale,
As rabbits cheer with twitching tail! 🐇📈

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch update

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

@sonarqubecloud
Copy link
Copy Markdown

@hmbanan666 hmbanan666 merged commit a716e92 into main Jul 30, 2025
7 of 8 checks passed
@hmbanan666 hmbanan666 deleted the update branch July 30, 2025 08:19
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 (3)
packages/database/src/repository/kitchen.ts (1)

68-70: Simplify the unnecessary or() wrapper.

The filtering logic change to focus only on commonAverageCheck looks correct, but the or() wrapper is now unnecessary since there's only one condition.

Apply this diff to simplify:

-      where: (revenues, { eq, or }) => or(
-        eq(revenues.commonAverageCheck, 0),
-      ),
+      where: (revenues, { eq }) => eq(revenues.commonAverageCheck, 0),
apps/web-app/app/components/chart/KitchenRevenue.client.vue (2)

101-101: Consider using different colors for better line distinction.

Both lines use the same color, which might make them difficult to distinguish. Consider using different colors for better visual clarity.

Apply this diff for better visual distinction:

-const color = (_: DataRecord, i: number) => ['var(--ui-secondary)', 'var(--ui-secondary)'][i]
+const color = (_: DataRecord, i: number) => ['var(--ui-secondary)', 'var(--ui-primary)'][i]

124-124: Consider clarifying the "Средняя" label in tooltip.

The tooltip shows commonTotal as "Средняя" (Average), which might be confusing since it represents the average total across all kitchens, not the average per transaction. Consider a clearer label like "Общая средняя" (Common Average).

Apply this diff for clarity:

-const template = (d: DataRecord) => `${formatDate(d.date)}, ${format(d.date, 'eeeeee', { locale: ru })}: ${d.checks} ${pluralizationRu(d.checks, ['чек', 'чека', 'чеков'])}<br> Выручка: ${formatNumber(d.total)}<br> Средняя: ${formatNumber(d.commonTotal)}`
+const template = (d: DataRecord) => `${formatDate(d.date)}, ${format(d.date, 'eeeeee', { locale: ru })}: ${d.checks} ${pluralizationRu(d.checks, ['чек', 'чека', 'чеков'])}<br> Выручка: ${formatNumber(d.total)}<br> Общая средняя: ${formatNumber(d.commonTotal)}`
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 5925f1c and 4682600.

📒 Files selected for processing (6)
  • apps/web-app/app/components/chart/KitchenRevenue.client.vue (4 hunks)
  • apps/web-app/nuxt.config.ts (1 hunks)
  • apps/web-app/server/api/kitchen/revenue/iiko-daily.post.ts (3 hunks)
  • apps/web-app/server/tasks/kitchen/average-update.ts (0 hunks)
  • apps/web-app/server/tasks/kitchen/revenue-update.ts (1 hunks)
  • packages/database/src/repository/kitchen.ts (1 hunks)
💤 Files with no reviewable changes (1)
  • apps/web-app/server/tasks/kitchen/average-update.ts
🧰 Additional context used
🧬 Code Graph Analysis (1)
apps/web-app/server/api/kitchen/revenue/iiko-daily.post.ts (1)
apps/web-app/server/tasks/kitchen/rating-update.ts (1)
  • run (10-35)
⏰ 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 (14)
apps/web-app/nuxt.config.ts (1)

40-40: LGTM! Task scheduling configuration updated appropriately.

The removal of 'kitchen:average-update' from the minutely scheduled tasks aligns with the broader changes to the kitchen revenue reporting system mentioned in the AI summary. This reduces unnecessary background processing frequency.

apps/web-app/server/tasks/kitchen/revenue-update.ts (2)

23-23: LGTM! Rounding revenue to integer makes sense.

The addition of Math.round() ensures weekly revenue is stored as an integer, which is appropriate for currency values and prevents precision issues.


24-26: LGTM! Good optimization to prevent unnecessary database writes.

This early exit when revenueForThisWeek === kitchen.revenueForThisWeek is an excellent optimization that reduces database load by skipping updates when the revenue value hasn't changed.

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

124-124: LGTM! Type extension correctly adds new revenue metrics.

The addition of averageCheck, commonAverageCheck, and commonTotal fields to the parsed kitchens type is well-structured and properly typed.


141-144: LGTM! Proper initialization of new revenue fields.

The initialization of new fields with calculated averageCheck and placeholder zeros for common values is correct, as the common values are calculated later.


151-154: LGTM! Correctly assigns common values to all kitchens.

The assignment of calculated common values to each kitchen object is appropriate since these represent aggregated metrics that should be consistent across all kitchens.


172-174: LGTM! Database creation includes all new revenue fields.

The inclusion of averageCheck, commonAverageCheck, and commonTotal in the revenue creation ensures complete data persistence.


180-182: LGTM! Database update mirrors creation with all new fields.

The update operation correctly includes all new revenue fields, maintaining consistency with the creation operation.

apps/web-app/app/components/chart/KitchenRevenue.client.vue (6)

59-59: LGTM! Type extension correctly adds commonTotal field.

The addition of commonTotal: number to the DataRecord type is consistent with existing field types.


65-65: LGTM! Props extension aligns with new data structure.

The addition of commonTotal to the values prop correctly reflects the enhanced data model from the backend.


89-89: LGTM! Data mapping follows consistent pattern.

The mapping of commonTotal with a fallback to 0 is consistent with the existing pattern used for other fields.


95-98: LGTM! Y accessor array enables dual line visualization.

Converting the y accessor to an array of functions correctly enables displaying both total and commonTotal as separate lines on the chart.


99-99: LGTM! Area fill correctly uses only primary total metric.

Using a separate yArea accessor for just the total values is a good design choice that prevents visual confusion while maintaining dual line functionality.


102-102: LGTM! Dash pattern provides good visual differentiation.

The lineDashArray correctly differentiates the second line with dashed styling while keeping the first line solid.

continue
}

const averageCheck = Math.round(total / checks)
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Add validation for division by zero.

The average check calculation could fail if checks is 0, leading to Infinity or NaN values.

Add validation to handle zero checks:

+    if (checks === 0) {
+      continue
+    }
+
     const averageCheck = Math.round(total / checks)
📝 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
const averageCheck = Math.round(total / checks)
if (checks === 0) {
continue
}
const averageCheck = Math.round(total / checks)
🤖 Prompt for AI Agents
In apps/web-app/server/api/kitchen/revenue/iiko-daily.post.ts at line 135, the
calculation of averageCheck divides total by checks without checking if checks
is zero, which can cause Infinity or NaN results. Add a validation before the
division to check if checks is zero; if so, set averageCheck to zero or an
appropriate default value to avoid invalid calculations.

Comment on lines +148 to +149
const commonAverageCheck = Math.round(parsedKitchens.reduce((acc, curr) => acc + curr.averageCheck, 0) / parsedKitchens.length)
const commonTotal = Math.round(parsedKitchens.reduce((acc, curr) => acc + curr.total, 0) / parsedKitchens.length)
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Add validation for empty kitchen arrays.

The common value calculations could fail with division by zero if parsedKitchens.length is 0.

Add validation to handle empty arrays:

+  if (parsedKitchens.length === 0) {
+    return { rowsUpdated: 0, errors: ['No valid kitchen data found'] }
+  }
+
   // Update common data
   const commonAverageCheck = Math.round(parsedKitchens.reduce((acc, curr) => acc + curr.averageCheck, 0) / parsedKitchens.length)
   const commonTotal = Math.round(parsedKitchens.reduce((acc, curr) => acc + curr.total, 0) / parsedKitchens.length)
📝 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
const commonAverageCheck = Math.round(parsedKitchens.reduce((acc, curr) => acc + curr.averageCheck, 0) / parsedKitchens.length)
const commonTotal = Math.round(parsedKitchens.reduce((acc, curr) => acc + curr.total, 0) / parsedKitchens.length)
if (parsedKitchens.length === 0) {
return { rowsUpdated: 0, errors: ['No valid kitchen data found'] }
}
// Update common data
const commonAverageCheck = Math.round(
parsedKitchens.reduce((acc, curr) => acc + curr.averageCheck, 0) / parsedKitchens.length
)
const commonTotal = Math.round(
parsedKitchens.reduce((acc, curr) => acc + curr.total, 0) / parsedKitchens.length
)
🤖 Prompt for AI Agents
In apps/web-app/server/api/kitchen/revenue/iiko-daily.post.ts around lines 148
to 149, the code calculates averages by dividing sums by parsedKitchens.length
without checking if the array is empty, which can cause division by zero errors.
Add a validation before these calculations to check if parsedKitchens.length is
greater than zero; if it is zero, set commonAverageCheck and commonTotal to a
safe default value like 0 to avoid runtime errors.

This was referenced Jul 30, 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