Skip to content

fix: implement real conversion rate in sales analytics views#1014

Open
ayesha1145 wants to merge 1 commit intoalphaonelabs:mainfrom
ayesha1145:feat/sales-analytics-conversion-rate
Open

fix: implement real conversion rate in sales analytics views#1014
ayesha1145 wants to merge 1 commit intoalphaonelabs:mainfrom
ayesha1145:feat/sales-analytics-conversion-rate

Conversation

@ayesha1145
Copy link

@ayesha1145 ayesha1145 commented Mar 9, 2026

Replaces the placeholder conversion rate (0.00) in the sales analytics views with a real calculation based on actual storefront page visits tracked by WebRequest.

Changes in web/views.py:

  • sales_analytics: replaced conversion_rate = 0.00 # Temporary placeholder with a query against WebRequest filtered by the storefront's URL path, aggregating visit counts and computing (completed orders / total visits) * 100
  • sales_data: replaced inaccurate path__contains="ref=" visit counting with the same consistent storefront path filter

Formula: conversion_rate = round((total_orders / total_visits) * 100, 2)
Returns 0.00 when there are no visits to avoid division by zero.

Summary

This PR implements a real conversion rate calculation in the sales analytics views, replacing a placeholder value with data-driven metrics.

Key Changes

Conversion Rate Calculation:

  • Implemented a formula that calculates conversion rate as: (completed_and_shipped_orders / total_visits) * 100, rounded to 2 decimal places
  • Returns 0.00 when there are no visits to avoid division by zero errors

Visit Data Source:

  • Aggregates visitor data from the WebRequest model using an exact path match filter (path__exact="/storefront/{store_slug}/"), summing the count field to get total visits

Order Status Update:

  • Modified order filtering across analytics views from status="completed" to status__in=["completed", "shipped"], expanding the set of completed orders included in the conversion rate calculation

Affected Views:

  • sales_analytics(): Displays conversion rate metrics in the analytics dashboard
  • sales_data(): Returns conversion rate data as JSON for API consumers
  • Related analytics view classes also use this consistent conversion rate logic

Impact

  • Conversion rate metrics now reflect actual user behavior rather than placeholder values
  • Accounts for both completed and shipped orders in conversion calculations
  • Provides accurate visitor-to-order conversion insights for storefront owners
  • No changes to method signatures or public API contracts

@github-actions
Copy link
Contributor

github-actions bot commented Mar 9, 2026

👀 Peer Review Required

Hi @ayesha1145! This pull request does not yet have a peer review.

Before this PR can be merged, please request a review from one of your peers:

  • Go to the PR page and click "Reviewers" on the right sidebar.
  • Select a team member or contributor to review your changes.
  • Once they approve, this reminder will be automatically removed.

Thank you for contributing! 🎉

@github-actions github-actions bot added the files-changed: 1 PR changes 1 file label Mar 9, 2026
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Mar 9, 2026

Warning

Rate limit exceeded

@ayesha1145 has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 0 minutes and 27 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository: alphaonelabs/coderabbit/.coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 892005fc-4765-4cb2-b023-c45952a44731

📥 Commits

Reviewing files that changed from the base of the PR and between 3f840e2 and dabed3f.

📒 Files selected for processing (1)
  • web/views.py

Note

.coderabbit.yaml has unrecognized properties

CodeRabbit is using all valid settings from your configuration. Unrecognized properties (listed below) have been ignored and may indicate typos or deprecated fields that can be removed.

⚠️ Parsing warnings (1)
Validation error: Unrecognized key(s) in object: 'tools'
⚙️ Configuration instructions
  • Please see the configuration documentation for more information.
  • You can also validate your configuration using the online YAML validator.
  • 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

Walkthrough

Storefront analytics in web/views.py were updated: order filtering now includes statuses "completed" and "shipped", and conversion rate is computed dynamically by counting WebRequest visits to the storefront path and computing (total_orders / total_visits) × 100, rounded to two decimals (0.00 fallback).

Changes

Cohort / File(s) Summary
Analytics view updates
web/views.py
Replaced hardcoded/placeholder conversion_rate with dynamic calculation that sums WebRequest.count for path "/storefront/{store_slug}/" and computes percent (total_orders ÷ total_visits) rounded to 2 decimals; expanded order filtering from status="completed" to status__in=["completed", "shipped"] in analytics code paths.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant StoreAnalyticsView
    participant DB as Database (Orders, WebRequest)

    Client->>StoreAnalyticsView: request analytics for store_slug
    StoreAnalyticsView->>DB: query Orders (status in ["completed","shipped"])
    StoreAnalyticsView->>DB: query WebRequest where path == "/storefront/{store_slug}/"
    DB-->>StoreAnalyticsView: total_orders, total_visits (sum counts)
    StoreAnalyticsView->>StoreAnalyticsView: compute conversion_rate = round((total_orders/total_visits)*100,2) or 0.00
    StoreAnalyticsView-->>Client: return analytics payload (including conversion_rate)
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 33.33% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main change: implementing real conversion rate calculations in sales analytics views, replacing placeholder values with data-driven logic.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Contributor

@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

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@web/views.py`:
- Around line 4353-4357: sales_analytics currently computes conversion_rate
using total_orders that counts only "completed" while sales_data uses
["completed","shipped"], causing inconsistent metrics; refactor to compute
total_orders via a shared helper or shared queryset used by both views (e.g.,
extract a function get_storefront_orders_queryset or compute_total_orders that
returns the same annotated/filtered queryset used in sales_data), then have
sales_analytics call that helper to derive total_orders and conversion_rate
(keep WebRequest aggregation for total_visits unchanged), ensuring the same
numerator (the helper's total_orders) is reused in both views.
- Around line 4315-4319: Make conversion_rate consistent by using the same
order-status definition in both sales_analytics and sales_data: change the
orders filter to status__in=["completed","shipped"] (or update both to only
"completed" if you prefer the stricter metric) and apply that same filter in
both places, and also tighten the web request lookup by replacing
path__icontains with path__exact=f"/storefront/{storefront.store_slug}/" in the
WebRequest.objects.filter(...) that computes total_visits so total_visits and
conversion_rate use the exact same criteria.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository: alphaonelabs/coderabbit/.coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 0f5dfd17-49a3-4dd2-8418-c1388d459305

📥 Commits

Reviewing files that changed from the base of the PR and between c94caf8 and 100ee70.

📒 Files selected for processing (1)
  • web/views.py

@ayesha1145 ayesha1145 force-pushed the feat/sales-analytics-conversion-rate branch from 100ee70 to 3f840e2 Compare March 9, 2026 17:44
Copy link
Contributor

@github-actions github-actions bot left a comment

Choose a reason for hiding this comment

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

This PR has 2 unresolved review conversations. Please resolve them before this PR can be merged.

@ayesha1145
Copy link
Author

Fixed: updated sales_analytics to use status__in=["completed", "shipped"] to match sales_data, and changed path__icontains to path__exact for precise storefront path matching. Both views now use consistent order status definitions and identical visit counting logic.

Copy link
Contributor

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
web/views.py (1)

4257-4275: ⚠️ Potential issue | 🟠 Major

Update StoreAnalyticsView to match the analytics context or remove its route.

Both StoreAnalyticsView and sales_analytics are currently routed and both render analytics/analytics_dashboard.html. However, StoreAnalyticsView provides only total_sales, total_revenue, top_products, and storefront, while the template expects total_orders, conversion_rate, and best_selling_products.

Although the template includes default filters that prevent rendering errors, this mismatch violates Django best practices and creates inconsistency. Either:

  • Update StoreAnalyticsView.get_context_data() to compute and supply all required keys (matching sales_analytics), or
  • Remove the StoreAnalyticsView route if sales_analytics is the intended replacement.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@web/views.py` around lines 4257 - 4275, StoreAnalyticsView.get_context_data
currently returns total_sales, total_revenue, top_products and storefront but
the template expects total_orders, conversion_rate, and best_selling_products
(as provided by sales_analytics); either update
StoreAnalyticsView.get_context_data to compute and return the same keys as
sales_analytics (compute total_orders from orders.count(), conversion_rate using
the same numerator/denominator logic, and best_selling_products with the same
aggregation and ordering as sales_analytics) and include storefront, or remove
the StoreAnalyticsView route so only sales_analytics serves
analytics/analytics_dashboard.html; update references to
top_products/total_sales if needed to match the template keys to avoid
duplication/inconsistency.
♻️ Duplicate comments (1)
web/views.py (1)

4309-4319: ⚠️ Potential issue | 🟠 Major

shipped changes the documented conversion-rate definition.

The PR objective describes conversion as completed orders divided by storefront visits, but Line 4309 now includes shipped orders in the numerator. That reports conversions before fulfillment completes. Please either narrow this back to completed orders or explicitly update the metric definition and keep the same status set centralized in both analytics endpoints.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@web/views.py` around lines 4309 - 4319, The conversion numerator currently
uses Order.objects.filter(..., status__in=["completed", "shipped"]) which
contradicts the documented metric (completed orders / visits); change the filter
to only include completed orders (e.g., status="completed" or
status__in=["completed"]) when computing total_orders and conversion_rate, and
instead of hardcoding the list inline, extract the status list into a shared
constant (e.g., STORE_CONVERSION_STATUSES) or helper used by all analytics
endpoints so the same status set is centralized and consistent across views
(also update any other analytics endpoint that references the previous list).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Outside diff comments:
In `@web/views.py`:
- Around line 4257-4275: StoreAnalyticsView.get_context_data currently returns
total_sales, total_revenue, top_products and storefront but the template expects
total_orders, conversion_rate, and best_selling_products (as provided by
sales_analytics); either update StoreAnalyticsView.get_context_data to compute
and return the same keys as sales_analytics (compute total_orders from
orders.count(), conversion_rate using the same numerator/denominator logic, and
best_selling_products with the same aggregation and ordering as sales_analytics)
and include storefront, or remove the StoreAnalyticsView route so only
sales_analytics serves analytics/analytics_dashboard.html; update references to
top_products/total_sales if needed to match the template keys to avoid
duplication/inconsistency.

---

Duplicate comments:
In `@web/views.py`:
- Around line 4309-4319: The conversion numerator currently uses
Order.objects.filter(..., status__in=["completed", "shipped"]) which contradicts
the documented metric (completed orders / visits); change the filter to only
include completed orders (e.g., status="completed" or status__in=["completed"])
when computing total_orders and conversion_rate, and instead of hardcoding the
list inline, extract the status list into a shared constant (e.g.,
STORE_CONVERSION_STATUSES) or helper used by all analytics endpoints so the same
status set is centralized and consistent across views (also update any other
analytics endpoint that references the previous list).

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository: alphaonelabs/coderabbit/.coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 54ab3782-f73c-4fa0-aea5-2fd9b96d3231

📥 Commits

Reviewing files that changed from the base of the PR and between 100ee70 and 3f840e2.

📒 Files selected for processing (1)
  • web/views.py

@ayesha1145 ayesha1145 force-pushed the feat/sales-analytics-conversion-rate branch from 3f840e2 to dabed3f Compare March 9, 2026 18:01
@github-actions github-actions bot dismissed their stale review March 9, 2026 18:02

All review conversations have been resolved.

@ayesha1145
Copy link
Author

Fixed: updated StoreAnalyticsView.get_context_data to use the same context keys as sales_analytics (total_orders, conversion_rate, best_selling_products) and the same conversion rate logic using WebRequest path__exact filter.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

files-changed: 1 PR changes 1 file

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant