Automated Dealer-Based Pincode Pricing (B2C) — Implementation Plan

Document Purpose: Technical & functional proposal for team review and approval before implementation.
Scope: Automated B2C pincode pricing derived from dealer inventory prices (±20 pincode range).
System Risk Level: Low (zero changes to existing product/pincode tables, zero customer-frontend changes, instant rollback toggle).


1. Problem Statement & Business Goal

Current Process (Manual)

Today, every product variant in CKart has two layers of pricing entered manually by the Admin/Brand team:

  1. Base / Fixed Price in product_variants (price, b2bPrice, mrp).
  2. Pincode-Specific Price Overrides in product_pincodes (amount, b2bPrice, mrp).

When onboarding or collaborating with dealers in an area, dealers quote different prices for the same products. Currently, the operations team manually collects these prices, calculates the average offline, and overwrites the product/pincode prices in the database.

Target Process (Automated)

We want to automate this end-to-end:

  1. Give dealers an option in the Dealer App to enter a price for products they add/manage in their inventory (dealer_inventories).
  2. For any customer pincode P, automatically look at all qualifying dealers located within [P - 20, P + 20] and calculate the average of their entered prices for each product variant.
  3. Use that average as the B2C selling price for pincode P.
  4. If no dealer within [P - 20, P + 20] has entered a price for a product, seamlessly fall back to CKart's prior admin-entered price (product_pincodes first, then product_variants).

Core Engineering Constraint

Pricing touches product listing, search, product details, best-prices, cart totals, taxes, coupons, and order checkout. The design must:


2. Agreed Business Rules & Scope

# Rule / Area Agreed Behavior
1 Customer Segment B2C price only. B2B pricing (b2bPrice and /b2b/* endpoints) remains 100% untouched.
2 Pincode Range ±20 numeric pincode range ([customerPincode - 20, customerPincode + 20]). Configurable via constant/env. (Existing ±10 stock/delivery radius remains untouched.)
3 Stock Dependency Independent of stock. Once a dealer adds a product with a price in active inventory (status = true), their price counts even if currentStock = 0.
4 Dealer Eligibility Only dealers with dealers.status = 'Approved', active warehouse address (dealer_addresses.status = 1), active inventory row (dealer_inventories.status = true), and a valid entered price (price IS NOT NULL AND price > 0).
5 CKart's Own Dealer Included for now (ckartDealer = true counts in the average), controlled by a single config flag (INCLUDE_CKART_DEALER = true) so it can be toggled anytime without rewriting code.
6 Warehouses per Dealer Currently 1 warehouse per dealer.
7 Price Guardrails Enforced on dealer input (blocks accidental typos / unrealistic outliers before saving).
8 MRP & Tax mrp continues to come from product_pincodes / product_variants. Dealer-entered price is GST-inclusive (matching existing product_variants.price and product_pincodes.amount).

3. Why We Are NOT Writing Dealer Averages Into product_pincodes

At first glance, overwriting product_pincodes whenever a dealer saves a price might look simpler. However, auditing the codebase revealed 4 critical risks with that approach:

  1. 41× Row Explosion: One dealer at pincode P affects every pincode in [P - 20, P + 20] (41 pincodes per variant per dealer). Materializing those rows would bloat product_pincodes massively with auto-generated and non-existent pincodes.
  2. Breaks Admin & Brand Edit Forms: Both src/services/admin/productService.js (line 708) and src/services/brand/productService.js (line 583) load all ProductPincode rows into the product edit form. When an admin clicks Save, the backend runs ProductPincode.destroy({ where: { productVariantId } }) and recreates only what the form submitted — which would flood the admin UI and wipe out dealer averages.
  3. Breaks GET /shared/product/prices: src/services/common/productService.js (line 784) currently queries a pincode range (±10). Inserting 41 synthetic rows per dealer would cause duplicate entries per variant to be returned.
  4. Sync Drift Across 6+ Events: Keeping pre-computed rows accurate would require syncing on dealer inventory add/update/status/delete, dealer address edits, dealer approve/block, and admin product edits — plus extra backup columns to restore manual prices when dealers leave.

Conclusion: Leave product_variants and product_pincodes 100% untouched as CKart's safe admin baseline, store dealer prices only on dealer_inventories, and compute the effective B2C price at read time through one central resolver service.


4. Proposed Architecture: 3-Layer Price Resolution

Think of customer B2C pricing as 3 simple layers checked top-to-bottom:

[Diagram]

Why This Design Is Clean & Safe


5. Zero Customer Frontend Risk (No New JSON Fields!)

A key concern is avoiding any new response field or object (such as dealer_avg_prices) that would force changes across mobile and web frontends.

With this plan, ZERO new keys are added to any customer API response. The backend injects the averaged price in-memory directly into the exact fields (amount and price) that frontends already read today.

Example: GET /shared/product/prices?pincode=110050

Before (Current API Response):

[
  {
    "productVariantId": 101,
    "pincode": "110050",
    "amount": "410.00",
    "mrp": "480.00",
    "b2bPrice": "395.00"
  }
]

After (When Dealer Average = ₹400.00):

[
  {
    "productVariantId": 101,
    "pincode": "110050",
    "amount": "400.00",
    "mrp": "480.00",
    "b2bPrice": "395.00"
  }
]

Impact Across All Applications & Panels

Application / Panel Changes Required? Notes
Customer Mobile App (current & older versions) None (0 changes) Continues reading amount / price as today
Customer Web App None (0 changes) Continues reading amount / price as today
B2B App / Portal (/b2b/*) None (0 changes) Completely untouched
Admin Panel & Brand Panel None (0 changes) product_variants & product_pincodes CRUD untouched
Dealer App UI Input Only Add "Price" input on Add/Edit Inventory screen (older Dealer App builds won't break because price is optional)

6. Concrete Real-World Examples

Assume one product in the database:

Suppose the following dealers have this product in dealer_inventories:

Dealer Warehouse Pincode Dealer Status Stock Entered Price Eligible?
Dealer A 110045 Approved 500 ₹390 Yes
Dealer B 110060 Approved 0 ₹410 Yes (counts regardless of stock)
Dealer C (CKart) 110052 Approved 200 ₹400 Yes (INCLUDE_CKART_DEALER = true)
Dealer D 110055 Approved 100 (NULL / blank) No (no price entered)
Dealer E 110050 Blocked 100 ₹350 No (dealer not Approved)
Dealer F 110090 Approved 300 ₹430 Only if within customer's ±20

Walkthrough Scenarios

  1. B2C Customer at Pincode 110050

    • Range searched: 110030 to 110070 (110050 ± 20).
    • Qualifying dealers: Dealer A (₹390), Dealer B (₹410), Dealer C (₹400). (Dealer D has no price; Dealer E is Blocked; Dealer F at 110090 is outside range.)
    • Final B2C Price: (390 + 410 + 400) / 3 = ₹400.00 (MRP stays ₹480).
    • Reflected consistently in /shared/product/prices, /shared/product/best-prices, Cart, and Checkout.
  2. B2C Customer at Pincode 110075

    • Range searched: 110055 to 110095 (110075 ± 20).
    • Qualifying dealers: Dealer B (₹410 at 110060) and Dealer F (₹430 at 110090).
    • Final B2C Price: (410 + 430) / 2 = ₹420.00.
  3. B2C Customer at Pincode 400001 (No dealers nearby)

    • Range searched: 399981 to 400021 → 0 dealers found.
    • Checks product_pincodes for 400001 → none found.
    • Final B2C Price: Falls back to product_variants.price = ₹420.00.
  4. All Dealers Near 110050 Remove the Product (or Clear Their Price)

    • Range 110030–110070 → 0 dealers with price.
    • Checks product_pincodes for 110050 → finds original Admin entry.
    • Final B2C Price: Automatically reverts to ₹410.00 (zero manual cleanup needed).
  5. Dealer Enters a Mistake / Outlier Price

    • Dealer A accidentally types ₹40 (forgot a zero) or ₹550 (above MRP ₹480).
    • Rejected at API validation with a clear error message before saving — customer averages are protected from typos.
  6. B2B Customer at Pincode 110050

    • Completely unaffected — still receives b2bPrice = ₹395.00 from product_pincodes / product_variants.

7. Detailed Technical Implementation Plan

7.1 Database Migration (1 Column + 1 Index)

Create a Sequelize migration in src/migrations/:

  1. dealer_inventories table:
    • Add column price: DECIMAL(10, 2), allowNull: true, defaultValue: null.
    • Update src/models/dealerInventoryModel.js to declare price.
  2. dealer_addresses table:
    • Add composite index idx_dealer_addresses_pincode_status on (pincode, status) for fast ±20 range lookups.
  3. product_variants & product_pincodes tables:
    • No changes.

7.2 Dealer Inventory APIs & Price Guardrail

Files to update:

Changes:

  1. POST /dealer/inventory/addProductToInventory
    • Accept optional price in request body.
    • Validate price against the guardrail (if provided).
    • Save price on DealerInventory.
  2. POST /dealer/inventory/updateProductStockInInventory
    • Accept optional price alongside currentStock so the Dealer App can update both in one call if desired.
  3. POST /dealer/inventory/updateProductPriceInInventory (New Endpoint)
    • Allows updating (or clearing to null) the dealer's price for a productVariantId independently of stock.
  4. GET Inventory Endpoints (getInventoryByDealerId, getInventoryByProductVariantId)
    • Automatically include price in returned DealerInventory rows.
  5. Price Guardrail Validation Helper
    • Fetch the target ProductVariant (price, mrp) before saving DealerInventory.price.
    • Enforce:
      • price must be a valid number > 0.
      • price <= variant.mrp (cannot exceed MRP).
      • Lower bound guard (configurable — see Section 10 sign-off, e.g., price >= variant.price * MIN_PRICE_RATIO such as 0.5 or 0.7 of admin base price).
  6. Cache Invalidation on Write
    • Whenever a dealer adds/updates price, toggles inventory status, or deletes an inventory row, invalidate Redis keys:
      • cache:productPrices:*
      • cache:dealerInventory:*
      • cache:productList:*, cache:userProductList:*, cache:productDetail:* (if WebStore is included)

7.3 Central Resolver Service (src/services/common/pincodePriceResolver.js)

Create a new service with 3 configuration toggles (readable from .env with safe defaults):

const ENABLE_DEALER_AVG_PRICING = process.env.ENABLE_DEALER_AVG_PRICING !== "false"; // default: true
const DEALER_PRICE_PINCODE_RANGE = parseInt(process.env.DEALER_PRICE_PINCODE_RANGE || "20", 10);
const INCLUDE_CKART_DEALER = process.env.INCLUDE_CKART_DEALER !== "false"; // default: true

Core SQL Aggregation (Batched — 1 Query per Request)

SELECT
  di.productVariantId,
  ROUND(AVG(di.price), 2) AS avgPrice
FROM dealer_inventories di
INNER JOIN dealer_addresses da ON da.id = di.dealerAddressId
INNER JOIN dealers d ON d.id = di.dealerId
WHERE di.status = true
  AND di.price IS NOT NULL
  AND di.price > 0
  AND da.status = 1
  AND da.pincode REGEXP '^[0-9]{6}
    
AND CAST(da.pincode AS UNSIGNED) BETWEEN :minPincode AND :maxPincode AND d.status = 'Approved' -- If INCLUDE_CKART_DEALER is false: AND d.ckartDealer = false -- If variantIds passed: AND di.productVariantId IN (:variantIds) GROUP BY di.productVariantId;

Note on pincode validation: Because dealer_addresses.pincode is stored as VARCHAR, checking REGEXP '^[0-9]{6}

#39; (or normalizing 6-digit string bounds '110030' to '110070') guarantees malformed addresses can never break the query and keeps index scans fast.

Exposed Methods

  1. getEffectiveB2CPriceMap(variantIds, pincode, { transaction } = {})
    • Fetches dealer averages for variantIds within [pincode - 20, pincode + 20].
    • Fetches existing ProductPincode rows for (variantIds, String(pincode)).
    • Merges into Map<variantId, { amount, b2bPrice, mrp }> where:
      • amount = dealerAvg ?? manualRow.amount
      • mrp = manualRow?.mrp ?? null (caller keeps variant.mrp when null)
      • b2bPrice = manualRow?.b2bPrice ?? null (B2B completely untouched)
  2. getAllEffectivePricesForPincode(pincode)
    • Used by GET /shared/product/prices?pincode=....
    • Merges all existing ProductPincode rows for that pincode with all dealer averages in [pincode - 20, pincode + 20].
    • For variants that have a dealer average but no ProductPincode row, fetches ProductVariant.mrp in one batch query and constructs a plain object with the exact ProductPincode response shape: { productVariantId, pincode: String(pincode), amount: dealerAvg, mrp: variant.mrp, b2bPrice: null }.

7.4 Exact Code Injection Touchpoints

Only 2 B2C service files (3 query blocks) need a 1-line swap — plus 1 optional file if /webStore is included:

1. src/services/common/productService.js — getPincodeProductPrices (Line 782)

2. src/services/common/productService.js — getBestPricesForAllProducts (Lines 974–991 & 1131–1140)

3. src/services/common/cartService.js — calculateTotalPrice (Lines 616–627)

4. Optional: src/services/webStore/productService.js (Lines 423–446 & 594–618)


8. Backward Compatibility, Safety & Rollback Plan

Safety Aspect How It Is Guaranteed
Older Customer Apps Exact same API endpoints and JSON fields (amount, price, mrp). No forced app update required.
Older Dealer Apps dealer_inventories.price is nullable/optional. Old dealer app builds can still add/update stock without sending price.
Historical Orders order_products and orders snapshot prices at checkout time. Future dealer price changes never alter past orders.
Auctions CommonCartServices.calculateTotalPrice uses useItemPrice = true for auctions, bypassing pincode pricing completely.
Instant Rollback Set ENABLE_DEALER_AVG_PRICING=false in .env and restart — the entire platform instantly reverts to pure product_pincodes + product_variants pricing with zero database rollback required.

9. QA & Verification Checklist (Post-Implementation)


10. Items for Team Sign-Off Before Implementation Begins

Please confirm these 2 final details so development can start cleanly:

  1. Exact Dealer Price Guardrail Bounds:
    • Upper bound: price <= variant.mrp (recommended).
    • Lower bound: What minimum should we enforce?
      • Option A: price > 0 only (no lower bound other than positive).
      • Option B: price >= 50% (or 70%) of admin's variant.price (protects against missing-digit typos like ₹40 instead of ₹400).
  2. WebStore (/webStore/*) Inclusion:
    • Should /webStore/product/* also use this B2C dealer-average pricing, or should we scope Phase 1 strictly to /shared/* (Customer B2C App)?