Skip to content

feat: network metrics page#41

Merged
hmbanan666 merged 2 commits into
mainfrom
network-page
Aug 1, 2025
Merged

feat: network metrics page#41
hmbanan666 merged 2 commits into
mainfrom
network-page

Conversation

@hmbanan666

@hmbanan666 hmbanan666 commented Aug 1, 2025

Copy link
Copy Markdown
Collaborator

Summary by CodeRabbit

  • New Features
    • Added a new navigation link labeled "Показатели сети" for accessing network metrics.
    • Introduced a dedicated page displaying network metrics, including interactive charts for revenue and average check amounts over customizable date ranges.
    • Users can view visualized trends and statistics for network revenue and check data, with localized formatting and tooltips.

@hmbanan666 hmbanan666 self-assigned this Aug 1, 2025
@coderabbitai

coderabbitai Bot commented Aug 1, 2025

Copy link
Copy Markdown

Walkthrough

A new "Network Metrics" feature was introduced to the web application. This includes a navigation link to a new /network route, a dedicated page that displays network metrics, and two client-side chart components for visualizing network revenue and check data over selectable date ranges. Data is fetched from an API endpoint and displayed with localized formatting.

Changes

Cohort / File(s) Change Summary
Navigation Update
apps/web-app/app/components/Navigation.vue
Added a new navigation link labeled "Показатели сети" pointing to /network, with an icon and active state logic.
Network Metrics Page
apps/web-app/app/pages/network/index.vue
Introduced a new page at /network that displays a date range picker and two charts for network revenue and checks. Fetches data from /api/network/metrics and manages period and range state.
Network Revenue Chart Component
apps/web-app/app/components/chart/NetworkRevenue.client.vue
Added a new client-side Vue component to render a card and chart visualizing network revenue statistics over a selectable period and range, with Russian localization and custom tooltips.
Network Checks Chart Component
apps/web-app/app/components/chart/NetworkChecks.client.vue
Added a new client-side Vue component to render a card and chart visualizing average check amounts and counts over a selectable period and range, with Russian localization and custom tooltips.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Navigation
    participant NetworkPage
    participant API
    participant RevenueChart
    participant ChecksChart

    User->>Navigation: Click "Показатели сети"
    Navigation->>NetworkPage: Route to /network
    NetworkPage->>API: Fetch /api/network/metrics (with period, range)
    API-->>NetworkPage: Return metrics data
    NetworkPage->>RevenueChart: Pass period, range, values
    NetworkPage->>ChecksChart: Pass period, range, values
    RevenueChart-->>User: Render revenue chart
    ChecksChart-->>User: Render checks chart
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

A hop and a skip to the network’s new view,
With charts full of numbers and rubles in blue.
A link in the nav, a page shining bright—
Metrics and checks now dance in the light.
The rabbits rejoice, their data in sight!
🐇📊✨


📜 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 7c68c86 and 3fca5ff.

📒 Files selected for processing (1)
  • apps/web-app/app/components/chart/NetworkChecks.client.vue (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/web-app/app/components/chart/NetworkChecks.client.vue
⏰ 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 unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch network-page

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🔭 Outside diff range comments (1)
apps/web-app/app/components/chart/NetworkChecks.client.vue (1)

1-140: Consider extracting shared chart logic into a composable.

Both NetworkRevenue and NetworkChecks components share significant amounts of code (data processing, date formatting, chart configuration). This creates maintenance overhead.

Consider creating a shared composable like useNetworkChart to reduce code duplication:

// composables/useNetworkChart.ts
export function useNetworkChart(period: Ref<Period>, range: Ref<Range>, values: Ref<any[]>) {
  const data = ref([])
  const cardRef = useTemplateRef<HTMLElement | null>('cardRef')
  const { width } = useElementSize(cardRef)
  
  const formatNumber = new Intl.NumberFormat('ru', { 
    style: 'currency', 
    currency: 'RUB', 
    maximumFractionDigits: 0 
  }).format
  
  function formatDate(date: Date, period: Period): string {
    // shared date formatting logic
  }
  
  // shared data processing logic
  // shared chart configuration
  
  return {
    data,
    cardRef,
    width,
    formatNumber,
    formatDate,
    // other shared utilities
  }
}
🧹 Nitpick comments (6)
apps/web-app/app/components/Navigation.vue (1)

132-137: Consider using i18n for consistency.

The new navigation item follows the established pattern correctly. However, while other menu items use t('app.menu.xxx') for internationalization, this item uses a hardcoded Russian label.

Consider adding an i18n key for consistency:

-    label: 'Показатели сети',
+    label: t('app.menu.network-metrics'),
apps/web-app/app/components/chart/NetworkRevenue.client.vue (3)

75-94: Optimize the data processing logic.

The watch function processes data on every change, but the date string matching logic could be more efficient and robust.

Consider these improvements:

  watch([() => period, () => range, () => values], () => {
    const dates = ({
      daily: eachDayOfInterval,
      weekly: eachWeekOfInterval,
      monthly: eachMonthOfInterval,
    } as Record<Period, typeof eachDayOfInterval>)[period](range)

+   // Create a map for O(1) lookups
+   const valuesMap = new Map(values.map(v => [v.date.substring(0, 10), v]))

    data.value = dates.map((date) => {
      const dateStr = format(date, 'yyyy-MM-dd')
-     const value = values.find((d) => d.date.startsWith(dateStr))
+     const value = valuesMap.get(dateStr)

      return {
        date,
        total: value?.total ?? 0,
        checks: value?.checks ?? 0,
        averageCheck: value?.averageCheck ?? 0,
        averageTotal: value?.averageTotal ?? 0,
      }
    })
  }, { immediate: true })

96-105: Simplify chart configuration functions.

The color and line dash array functions are overly complex for their simple purpose.

Simplify these functions:

-const color = (_: DataRecord, i: number) => ['var(--ui-secondary)', 'var(--ui-secondary)'][i]
-const lineDashArray = (_: DataRecord, i: number) => [i === 0 ? undefined : 3]
+const color = () => 'var(--ui-secondary)'
+const lineDashArray = (_: DataRecord, i: number) => i === 0 ? undefined : [3]

126-126: Consider breaking down the complex tooltip template.

The tooltip template is quite long and complex, making it hard to maintain.

Consider extracting the tooltip logic:

+function formatTooltip(d: DataRecord): string {
+  const dateStr = `${formatDate(d.date)}, ${format(d.date, 'eeee', { locale: ru })}`
+  const checksStr = `${d.checks} ${pluralizationRu(d.checks, ['чек', 'чека', 'чеков'])}`
+  const avgCheckStr = `средний ${formatNumber(d.averageCheck)}`
+  const revenueStr = `Выручка: ${formatNumber(d.total)}`
+  const avgTotalStr = `Средняя у кухни: ${formatNumber(d.averageTotal)}`
+  
+  return `<strong>${dateStr}</strong><br> ${checksStr}, ${avgCheckStr}<br> ${revenueStr}<br> ${avgTotalStr}`
+}

-const template = (d: DataRecord) => `<strong>${formatDate(d.date)}, ${format(d.date, 'eeee', { locale: ru })}</strong><br> ${d.checks} ${pluralizationRu(d.checks, ['чек', 'чека', 'чеков'])}, средний ${formatNumber(d.averageCheck)}<br> Выручка: ${formatNumber(d.total)}<br> Средняя у кухни: ${formatNumber(d.averageTotal)}`
+const template = formatTooltip
apps/web-app/app/components/chart/NetworkChecks.client.vue (2)

73-90: Apply the same data processing optimization as NetworkRevenue.

This component has the same inefficient data lookup pattern as the NetworkRevenue component.

Apply the same optimization using a Map for O(1) lookups:

  watch([() => period, () => range, () => values], () => {
    const dates = ({
      daily: eachDayOfInterval,
      weekly: eachWeekOfInterval,
      monthly: eachMonthOfInterval,
    } as Record<Period, typeof eachDayOfInterval>)[period](range)

+   const valuesMap = new Map(values.map(v => [v.date.substring(0, 10), v]))

    data.value = dates.map((date) => {
      const dateStr = format(date, 'yyyy-MM-dd')
-     const value = values.find((d) => d.date.startsWith(dateStr))
+     const value = valuesMap.get(dateStr)

      return {
        date,
        checks: value?.checks ?? 0,
        averageCheck: value?.averageCheck ?? 0,
      }
    })
  }, { immediate: true })

96-97: Remove unused array indexing in chart configuration.

The color and lineDashArray functions reference array indices that aren't used since this component only has one data series.

Simplify these functions:

-const color = (_: DataRecord, i: number) => ['var(--ui-info)', 'var(--ui-info)'][i]
-const lineDashArray = (_: DataRecord, i: number) => [i === 0 ? undefined : 3]
+const color = () => 'var(--ui-info)'
+const lineDashArray = () => undefined
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 8e1deaf and 7c68c86.

📒 Files selected for processing (4)
  • apps/web-app/app/components/Navigation.vue (1 hunks)
  • apps/web-app/app/components/chart/NetworkChecks.client.vue (1 hunks)
  • apps/web-app/app/components/chart/NetworkRevenue.client.vue (1 hunks)
  • apps/web-app/app/pages/network/index.vue (1 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/app/pages/network/index.vue (1)

28-31: Fix the date range calculation.

The date range calculation has an off-by-one error. Subtracting days: 30 - 1 results in a 30-day range, but the logic suggests it should be exactly 30 days from today.

Apply this fix for clarity:

  const range = shallowRef<Range>({
-   start: sub(today, { days: 30 - 1 }),
+   start: sub(today, { days: 29 }),
    end: today,
  })

Or if you want exactly 30 days including today:

  const range = shallowRef<Range>({
-   start: sub(today, { days: 30 - 1 }),
+   start: sub(today, { days: 30 }),
    end: today,
  })

Likely an incorrect or invalid review comment.

Comment thread apps/web-app/app/components/chart/NetworkChecks.client.vue
import type { Period, Range } from '#shared/types'
import { sub } from 'date-fns'

const { data: metrics } = useFetch('/api/network/metrics')

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 for the API fetch.

The useFetch call lacks error handling, which could result in a poor user experience if the API fails.

Consider adding error handling:

-const { data: metrics } = useFetch('/api/network/metrics')
+const { data: metrics, error } = useFetch('/api/network/metrics')

Then handle the error state in the template or show a fallback UI.

📝 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 { data: metrics } = useFetch('/api/network/metrics')
const { data: metrics, error } = useFetch('/api/network/metrics')
🤖 Prompt for AI Agents
In apps/web-app/app/pages/network/index.vue at line 25, the useFetch call to
'/api/network/metrics' lacks error handling. Modify the code to capture any
errors returned by useFetch, typically by destructuring an error property
alongside data. Then, update the template to check for this error state and
display an appropriate fallback UI or error message to improve user experience
when the API call fails.

@sonarqubecloud

sonarqubecloud Bot commented Aug 1, 2025

Copy link
Copy Markdown

Quality Gate Failed Quality Gate failed

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

See analysis details on SonarQube Cloud

@hmbanan666 hmbanan666 merged commit ee80625 into main Aug 1, 2025
7 of 8 checks passed
@hmbanan666 hmbanan666 deleted the network-page branch August 1, 2025 13:14
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