Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 9 additions & 6 deletions backend/commercial.py
Original file line number Diff line number Diff line change
Expand Up @@ -158,21 +158,24 @@ def pack_unit_cx_is_pack_rollup(cx, snap, unit=None):

recompute_lead stores pack payable on the lead. Overlay used to copy that
onto unit 1, so Unit 1 locked to the sum of every unit.

A lower RTO / insurance drops today's gross vehicle cost under the agreed
price. That gap is the extra-discount rule (Additional shrinks, payable
stays), so a price above today's GVC is still this unit. The pack total
is another vehicle: more than one and a half times this unit's ex-showroom.
"""
cx = round2(num(cx))
if cx <= 0:
return False
snap = snap or {}
unit = unit or {}
ex = round2(num(snap.get("exShowroom") or unit.get("exShowroom")))
if ex > 0:
return cx > ex * 1.5 + DEAL_AMOUNT_EQUAL_RUPEES
Comment on lines +172 to +174

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔴 Legacy pack totals double-count cheaper vehicles

On older packs with the order total copied to unit 1, pack_unit_cx_is_pack_rollup accepts totals below the new cutoff. Recompute then adds the sibling prices again, inflating the customer’s balance.

Learn more

Older pack price hydration could copy the lead’s commercial fields onto the first unit. The existing legacy data regression test covers a copied order total, but its total is far above the new cutoff. Price Structure runs recompute after an edit. Unit payable refresh keeps the copied Cx Demand as the first unit’s price when the cutoff misses it. Pack recompute then persists the inflated sum as payable and uses it for outstanding.

Example: A Storm with ₹12,00,000 ex-showroom has an agreed price of ₹11,80,000. A sibling costs ₹5,90,000. If unit 1 still carries the copied ₹17,70,000 pack total, the new ₹18,00,001 cutoff accepts it, and a price save writes ₹23,60,000 instead of ₹17,70,000.

Recommended fix: Distinguish explicit per-unit agreements from legacy copied totals using their source, with pack context available during reconciliation. Cover both a mixed-price pack with a copied total below the cutoff and a genuine unit agreement that exceeds GVC after a charge cut.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

Comment on lines +172 to +174

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔴 Missing extra income on pack sales

When an RTO or insurance cut exhausts the discount, pack_unit_cx_is_pack_rollup now preserves the higher agreed price. Recompute adds the difference to dealer margin only for single vehicles. Dealer Earnings omits the pack’s extra income.

Learn more

An owner can lower RTO and insurance through Price Structure. When the agreed price remains above the revised charges, unit payable refresh keeps the agreed price and records the positive gap as extra customer income. Lead recompute only derives that income directly for single vehicles, and its lead-level margin and earnings use that single-vehicle result. The Dealer Earnings register uses the persisted lead margin, so saving or reloading the report does not recover the omitted amount.

Example: A pack unit stays at ₹8,05,000 after its gross cost falls to ₹7,95,000 and the discount reaches zero. The unit records ₹10,000 in extra customer income, but none of that ₹10,000 reaches Dealer Earnings.

Recommended fix: Roll up extra customer income from the freshly computed pack units and include it exactly once in persisted margin and total earnings. Extend the large-cut regression to assert the lead-level margin and the earnings register contribution.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Keep low-ratio pack totals from locking as unit prices

For a mixed-SKU pack whose first unit costs much more than another vehicle, the pack total can be below 1.5× the first unit’s ex-showroom (for example, a Storm LR200 plus a HiRange SR). This returns false for a legacy pack roll-up copied onto unit 1, so _refresh_unit_payables treats the whole pack total as unit 1’s deal and then adds unit 2’s payable, overstating the customer balance and potentially blocking delivery.

Useful? React with 👍 / 👎.

gvc = _gvc_from_charges(snap)
if gvc <= 0:
gvc = _gvc_from_charges(unit)
if gvc > 0 and cx > gvc + DEAL_AMOUNT_EQUAL_RUPEES:
return True
ex = round2(num(snap.get("exShowroom") or unit.get("exShowroom")))
if ex > 0 and cx > ex * 1.5 + DEAL_AMOUNT_EQUAL_RUPEES:
return True
return False
return gvc > 0 and cx > gvc + DEAL_AMOUNT_EQUAL_RUPEES


def pack_unit_locked_cx_demand(snap, unit=None):
Expand Down
59 changes: 35 additions & 24 deletions backend/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -7489,36 +7489,47 @@ async def owner_set_lead_field(lead_id: str, body: OwnerFieldIn, act=Depends(act
else:
patch_val = ce.round2(max(0.0, ce.num(value)))
old = {field: lead.get(field)}
pack = oem_sync.is_same_order_pack(lead)
units = [dict(u or {}) for u in (lead.get("units") or [])]
target = None
if body.unitSno:
target, resolved = _resolve_unit_index(lead, body.unitSno)
units = [dict(u or {}) for u in resolved]
elif units and isinstance(units[0], dict):
target = 0
# Unit 2+ keeps its own RTO / insurance. The lead header is unit 1.
header_edit = target in (None, 0)
price_set = {
field: patch_val, "lastUpdated": now_iso(),
"lastUpdated": now_iso(),
"lastUpdatedBy": act.get("email", ""),
}
if field == "insuranceAmount":
price_set["insurance"] = patch_val
saved_prices = [str(x) for x in (lead.get("savedPriceFields") or []) if str(x or "").strip()]
if field not in saved_prices:
saved_prices.append(field)
price_set["savedPriceFields"] = saved_prices
if not oem_sync.is_same_order_pack(lead):
cx_now = ce.num(lead.get("cxDemand"))
pay_now = ce.num(lead.get("customerPayable"))
if cx_now <= 0 and pay_now > 0:
price_set["cxDemand"] = ce.round2(pay_now)
price_set["useDealPrice"] = True
units = list(lead.get("units") or [])
if units and isinstance(units[0], dict) and not body.unitSno:
u0 = dict(units[0])
u0[field] = patch_val
if header_edit:
price_set[field] = patch_val
if field == "insuranceAmount":
u0["insurance"] = patch_val
unit_saved = [str(x) for x in (u0.get("savedPriceFields") or []) if str(x or "").strip()]
price_set["insurance"] = patch_val
saved_prices = [str(x) for x in (lead.get("savedPriceFields") or []) if str(x or "").strip()]
if field not in saved_prices:
saved_prices.append(field)
price_set["savedPriceFields"] = saved_prices
if not pack:
cx_now = ce.num(lead.get("cxDemand"))
pay_now = ce.num(lead.get("customerPayable"))
if cx_now <= 0 and pay_now > 0:
price_set["cxDemand"] = ce.round2(pay_now)
price_set["useDealPrice"] = True
if target is not None and target < len(units) and isinstance(units[target], dict):
u = dict(units[target])
u[field] = patch_val
if field == "insuranceAmount":
u["insurance"] = patch_val
unit_saved = [str(x) for x in (u.get("savedPriceFields") or []) if str(x or "").strip()]
if field not in unit_saved:
unit_saved.append(field)
u0["savedPriceFields"] = unit_saved
if ce.num(u0.get("cxDemand")) <= 0 and ce.num(u0.get("customerPayable")) > 0:
u0["cxDemand"] = ce.round2(ce.num(u0.get("customerPayable")))
u0["useDealPrice"] = True
units[0] = u0
u["savedPriceFields"] = unit_saved
if ce.num(u.get("cxDemand")) <= 0 and ce.num(u.get("customerPayable")) > 0:
u["cxDemand"] = ce.round2(ce.num(u.get("customerPayable")))
u["useDealPrice"] = True
units[target] = u
price_set["units"] = units
await db.leads.update_one({"leadId": lead_id}, {"$set": price_set})
await recompute_lead(lead_id)
Expand Down
108 changes: 108 additions & 0 deletions backend/tests/test_deal_pass_meet_cx.py
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,17 @@ def test_pack_unit_lock_ignores_pack_total_cx_on_unit():
assert ce.pack_unit_locked_cx_demand(snap, unit) == 0
own = {"additionalDiscount": 59500, "cxDemand": 790000, "exShowroom": 825000}
assert ce.pack_unit_locked_cx_demand(snap, own) == 790000
# Agreed price sits above today's GVC after a large RTO / insurance cut.
# That is this unit's deal, not the pack total.
reduced = {
"model": "Turbo Max", "variant": "Maxx (PV)",
"exShowroom": 785000, "registrationRto": 0, "insurance": 10000,
"accessories": 0, "fastag": 0, "handlingCharges": 0, "trc": 0,
"extendedWarranty": 0, "rsaAmc": 0, "otherCharges": 0,
}
agreed = {"additionalDiscount": 4500, "cxDemand": 805000, "exShowroom": 785000}
assert ce.pack_unit_cx_is_pack_rollup(805000, reduced, agreed) is False
assert ce.pack_unit_locked_cx_demand(reduced, agreed) == 805000


def test_additional_discount_has_no_maximum():
Expand Down Expand Up @@ -259,6 +270,103 @@ async def test_pack_rto_insurance_cut_shrinks_additional_not_payable(client):
assert ce.num(u1.get("customerPayable")) != 820074


@pytest.mark.asyncio
async def test_confirmed_rto_cut_leaves_additional_200(client):
"""Extra discount 4,500 on list RTO 5,500 / insurance 19,000.

RTO 2,200 and insurance 18,000 cut 4,300, so Additional becomes 200.
Payable stays. Same on one vehicle, on pack unit 2, and when the cut
is larger than the discount (Additional goes to 0, payable stays).
"""
ex, list_rto, list_ins = 785000, 5500, 19000
pay = ex + list_rto + list_ins - 4500 # 805000

async def make(lid, *, pack=False):
await server.db.leads.delete_many({"leadId": lid})
await server.db.price_master.delete_many({"priceId": f"PM-{lid}"})
await server.db.price_master.insert_one({
"priceId": f"PM-{lid}", "model": "Turbo Max", "variant": "Maxx Confirmed",
"exShowroom": ex, "rto": list_rto, "insurance": list_ins,
"status": "active", "oemSyncedAt": "2026-11-01T00:00:00",
})
unit = {
"model": "Turbo Max", "variant": "Maxx Confirmed",
"exShowroom": ex, "rto": list_rto, "insuranceAmount": list_ins, "insurance": list_ins,
"additionalDiscount": 4500, "customerPayable": pay, "cxDemand": pay,
"useDealPrice": True, "priceStructureSaved": True,
"schemeAllocationExplicit": True, "benefitPassedBreakup": "{}",
}
doc = {
"leadId": lid, "customerName": lid, "mobile": "9000003344",
"interestedModel": "Turbo Max", "variant": "Maxx Confirmed",
"executive": "Amit", "accountStatus": "Active", "currentStatus": "Booked",
"bookingDate": "2026-11-06", "priceStructureSaved": True,
"schemeAllocationExplicit": True, "benefitPassedBreakup": "{}",
"exShowroom": ex, "rto": list_rto, "insuranceAmount": list_ins, "insurance": list_ins,
"additionalDiscount": 4500, "customerPayable": pay, "cxDemand": pay, "useDealPrice": True,
"units": [dict(unit, sno=1)],
}
if pack:
doc["sameOrderMultiUnit"] = True
doc["units"] = [dict(unit, sno=1), dict(unit, sno=2)]
doc["customerPayable"] = pay * 2
doc["cxDemand"] = pay * 2
await server.db.leads.insert_one(doc)

await make("LD-CONF-RTO")
saved = await client.put("/api/leads/LD-CONF-RTO/price-structure", json={
"exShowroom": ex, "rto": 2200, "insuranceAmount": 18000,
})
assert saved.status_code == 200, saved.text
one = saved.json()
assert ce.num(one["customerPayable"]) == pay
assert ce.num(one["additionalDiscount"]) == 200

await make("LD-CONF-RTO-PACK", pack=True)
pack_saved = await client.put("/api/leads/LD-CONF-RTO-PACK/price-structure", json={
"exShowroom": ex, "rto": 2200, "insuranceAmount": 18000, "unitSno": 2,
})
assert pack_saved.status_code == 200, pack_saved.text
after = await server.db.leads.find_one({"leadId": "LD-CONF-RTO-PACK"})
u1, u2 = after["units"][0], after["units"][1]
assert ce.num(u2["customerPayable"]) == pay
assert ce.num(u2["additionalDiscount"]) == 200
assert ce.num(u1["additionalDiscount"]) == 4500
assert ce.num(u1["rto"]) == list_rto

await make("LD-CONF-RTO-OF", pack=True)
rto = await client.put("/api/leads/LD-CONF-RTO-OF/owner-field", json={
"field": "rto", "value": 2200, "unitSno": 2,
})
assert rto.status_code == 200, rto.text
ins = await client.put("/api/leads/LD-CONF-RTO-OF/owner-field", json={
"field": "insuranceAmount", "value": 18000, "unitSno": 2,
})
assert ins.status_code == 200, ins.text
edited = await server.db.leads.find_one({"leadId": "LD-CONF-RTO-OF"})
edited_u1, edited_u2 = edited["units"][0], edited["units"][1]
assert ce.num(edited_u2["rto"]) == 2200
assert ce.num(edited_u2["insuranceAmount"]) == 18000
assert ce.num(edited_u2["customerPayable"]) == pay
assert ce.num(edited_u2["additionalDiscount"]) == 200
assert ce.num(edited_u1["additionalDiscount"]) == 4500
assert ce.num(edited["rto"]) == list_rto

# Cut 14,500 is larger than Additional 4,500. Discount goes to 0.
# Payable stays; the rest is extra from the customer, not a cheaper price.
await make("LD-CONF-RTO-BIG", pack=True)
big = await client.put("/api/leads/LD-CONF-RTO-BIG/price-structure", json={
"exShowroom": ex, "rto": 0, "insuranceAmount": 10000, "unitSno": 2,
})
assert big.status_code == 200, big.text
big_doc = await server.db.leads.find_one({"leadId": "LD-CONF-RTO-BIG"})
big_u2 = big_doc["units"][1]
assert ce.num(big_u2["customerPayable"]) == pay
assert ce.num(big_u2["cxDemand"]) == pay
assert ce.num(big_u2["additionalDiscount"]) == 0
assert ce.num(big_u2.get("extraIncomeFromCustomer")) == 10000


@pytest.mark.asyncio
async def test_actual_rto_and_insurance_cut_additional_not_payable(client):
"""Lower real RTO and insurance shrink Additional. Payable and excess stay."""
Expand Down
5 changes: 3 additions & 2 deletions frontend/src/pages/LeadDrawer.js
Original file line number Diff line number Diff line change
Expand Up @@ -1875,8 +1875,9 @@ export function SchemeTab({ lead, c, actions = {}, isOwner = false, masters, onS
});
setUsedMap(inferred);
// Billed date drives scheme month per pack unit; a model / variant change
// brings different scheme pools.
}, [lead.leadId, unitSno, lead.schemeAsOf, lead.bookingDate, unitSoldDate, src.interestedModel, src.variant]);
// brings different scheme pools. Additional follows a price save: a lower
// RTO / insurance shrinks it, and this form must not save the old figure.
}, [lead.leadId, unitSno, lead.schemeAsOf, lead.bookingDate, unitSoldDate, src.interestedModel, src.variant, src.additionalDiscount]);
useEffect(() => {
if (!lead.leadId || !schemeDate) return;
get(`/leads/${lead.leadId}/scheme-rules`, { on: schemeDate, ...(units ? { unit: unitSno } : {}) })
Expand Down
28 changes: 28 additions & 0 deletions frontend/src/pages/LeadDrawer.overview.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,34 @@ test("owner can edit additional when Cx Demand locks the deal", async () => {
host.remove();
});

test("scheme additional follows a price save that shrinks the discount", async () => {
const { host, root } = await renderScheme({ isOwner: true, dealLocked: true });
expect(Number(host.querySelector('[data-testid="scheme-additionalDiscount"]').value)).toBe(29500);
await act(async () => {
root.render(
<SchemeTab
lead={{
leadId: "LD-SCHEME-ADDL",
cxDemand: 960000,
budget: 960000,
useDealPrice: true,
additionalDiscount: 200,
interestedModel: "Storm",
variant: "Storm TR",
}}
c={{}}
actions={{ canScheme: true }}
isOwner
masters={{}}
onSaved={() => {}}
/>,
);
});
expect(Number(host.querySelector('[data-testid="scheme-additionalDiscount"]').value)).toBe(200);
await act(async () => { root.unmount(); });
host.remove();
});

test("staff additional stays locked when Cx Demand is the deal", async () => {
const { host, root } = await renderScheme({ isOwner: false, dealLocked: true });
const input = host.querySelector('[data-testid="scheme-additionalDiscount"]');
Expand Down
Loading