Skip to content

Commit 429cb50

Browse files
Merge pull request #299 from writerish07-pixel/cursor/rto-insurance-extra-discount-996c
RTO and insurance changes move extra discount, not the customer price
2 parents d60b894 + c976735 commit 429cb50

6 files changed

Lines changed: 301 additions & 33 deletions

File tree

‎backend/commercial.py‎

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -158,21 +158,24 @@ def pack_unit_cx_is_pack_rollup(cx, snap, unit=None):
158158
159159
recompute_lead stores pack payable on the lead. Overlay used to copy that
160160
onto unit 1, so Unit 1 locked to the sum of every unit.
161+
162+
A lower RTO / insurance drops today's gross vehicle cost under the agreed
163+
price. That gap is the extra-discount rule (Additional shrinks, payable
164+
stays), so a price above today's GVC is still this unit. The pack total
165+
is another vehicle: more than one and a half times this unit's ex-showroom.
161166
"""
162167
cx = round2(num(cx))
163168
if cx <= 0:
164169
return False
165170
snap = snap or {}
166171
unit = unit or {}
172+
ex = round2(num(snap.get("exShowroom") or unit.get("exShowroom")))
173+
if ex > 0:
174+
return cx > ex * 1.5 + DEAL_AMOUNT_EQUAL_RUPEES
167175
gvc = _gvc_from_charges(snap)
168176
if gvc <= 0:
169177
gvc = _gvc_from_charges(unit)
170-
if gvc > 0 and cx > gvc + DEAL_AMOUNT_EQUAL_RUPEES:
171-
return True
172-
ex = round2(num(snap.get("exShowroom") or unit.get("exShowroom")))
173-
if ex > 0 and cx > ex * 1.5 + DEAL_AMOUNT_EQUAL_RUPEES:
174-
return True
175-
return False
178+
return gvc > 0 and cx > gvc + DEAL_AMOUNT_EQUAL_RUPEES
176179

177180

178181
def pack_unit_locked_cx_demand(snap, unit=None):

‎backend/server.py‎

Lines changed: 81 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1779,6 +1779,18 @@ async def recompute_lead(lead_id):
17791779
updates["oemExtraSupportReceived"] = oem_pack["oemExtraSupportReceived"]
17801780
updates["oemExtraSupportPassed"] = oem_pack["oemExtraSupportPassed"]
17811781
updates["oemExtraSupportRetained"] = oem_pack["oemExtraSupportRetained"]
1782+
# Single files add extra-from-customer in the margin above. Pack units
1783+
# record it per vehicle; the lead total has to include each unit once
1784+
# or Dealer Earnings drops the amount.
1785+
pack_extra = ce.round2(sum(
1786+
ce.num((u or {}).get("extraIncomeFromCustomer")) for u in (pack_units or [])))
1787+
updates["extraIncomeFromCustomer"] = pack_extra
1788+
updates["dealerMarginNetExGst"] = ce.round2(margin["marginNetExGst"] + pack_extra)
1789+
updates["dealerTotalEarnings"] = ce.round2(
1790+
margin["marginNetExGst"] + income["retainedIncomeTotal"] + _oem_extra_earn
1791+
+ extra_income + _dealer_ins_income + pack_extra
1792+
- _dealer_funded_benefit
1793+
- _wo["oemUnpayableScheme"])
17821794
# Authoritative Insurance Benefit projection (parallel to loyaltyBonus offer field).
17831795
# Available amount is stored on insuranceBenefit; CB feeds the Dealer Earnings sheet
17841796
# column Customer Insurance Benefit Passed. Historical leads without auth allocation
@@ -7489,36 +7501,47 @@ async def owner_set_lead_field(lead_id: str, body: OwnerFieldIn, act=Depends(act
74897501
else:
74907502
patch_val = ce.round2(max(0.0, ce.num(value)))
74917503
old = {field: lead.get(field)}
7504+
pack = oem_sync.is_same_order_pack(lead)
7505+
units = [dict(u or {}) for u in (lead.get("units") or [])]
7506+
target = None
7507+
if body.unitSno:
7508+
target, resolved = _resolve_unit_index(lead, body.unitSno)
7509+
units = [dict(u or {}) for u in resolved]
7510+
elif units and isinstance(units[0], dict):
7511+
target = 0
7512+
# Unit 2+ keeps its own RTO / insurance. The lead header is unit 1.
7513+
header_edit = target in (None, 0)
74927514
price_set = {
7493-
field: patch_val, "lastUpdated": now_iso(),
7515+
"lastUpdated": now_iso(),
74947516
"lastUpdatedBy": act.get("email", ""),
74957517
}
7496-
if field == "insuranceAmount":
7497-
price_set["insurance"] = patch_val
7498-
saved_prices = [str(x) for x in (lead.get("savedPriceFields") or []) if str(x or "").strip()]
7499-
if field not in saved_prices:
7500-
saved_prices.append(field)
7501-
price_set["savedPriceFields"] = saved_prices
7502-
if not oem_sync.is_same_order_pack(lead):
7503-
cx_now = ce.num(lead.get("cxDemand"))
7504-
pay_now = ce.num(lead.get("customerPayable"))
7505-
if cx_now <= 0 and pay_now > 0:
7506-
price_set["cxDemand"] = ce.round2(pay_now)
7507-
price_set["useDealPrice"] = True
7508-
units = list(lead.get("units") or [])
7509-
if units and isinstance(units[0], dict) and not body.unitSno:
7510-
u0 = dict(units[0])
7511-
u0[field] = patch_val
7518+
if header_edit:
7519+
price_set[field] = patch_val
7520+
if field == "insuranceAmount":
7521+
price_set["insurance"] = patch_val
7522+
saved_prices = [str(x) for x in (lead.get("savedPriceFields") or []) if str(x or "").strip()]
7523+
if field not in saved_prices:
7524+
saved_prices.append(field)
7525+
price_set["savedPriceFields"] = saved_prices
7526+
if not pack:
7527+
cx_now = ce.num(lead.get("cxDemand"))
7528+
pay_now = ce.num(lead.get("customerPayable"))
7529+
if cx_now <= 0 and pay_now > 0:
7530+
price_set["cxDemand"] = ce.round2(pay_now)
7531+
price_set["useDealPrice"] = True
7532+
if target is not None and target < len(units) and isinstance(units[target], dict):
7533+
u = dict(units[target])
7534+
u[field] = patch_val
75127535
if field == "insuranceAmount":
7513-
u0["insurance"] = patch_val
7514-
unit_saved = [str(x) for x in (u0.get("savedPriceFields") or []) if str(x or "").strip()]
7536+
u["insurance"] = patch_val
7537+
unit_saved = [str(x) for x in (u.get("savedPriceFields") or []) if str(x or "").strip()]
75157538
if field not in unit_saved:
75167539
unit_saved.append(field)
7517-
u0["savedPriceFields"] = unit_saved
7518-
if ce.num(u0.get("cxDemand")) <= 0 and ce.num(u0.get("customerPayable")) > 0:
7519-
u0["cxDemand"] = ce.round2(ce.num(u0.get("customerPayable")))
7520-
u0["useDealPrice"] = True
7521-
units[0] = u0
7540+
u["savedPriceFields"] = unit_saved
7541+
if ce.num(u.get("cxDemand")) <= 0 and ce.num(u.get("customerPayable")) > 0:
7542+
u["cxDemand"] = ce.round2(ce.num(u.get("customerPayable")))
7543+
u["useDealPrice"] = True
7544+
units[target] = u
75227545
price_set["units"] = units
75237546
await db.leads.update_one({"leadId": lead_id}, {"$set": price_set})
75247547
await recompute_lead(lead_id)
@@ -8262,6 +8285,36 @@ def _lead_overlay_unit(lead, unit, index=0):
82628285
return out
82638286

82648287

8288+
def _cx_copies_pack_total(cx, lead, units, idx):
8289+
"""True when this unit's Cx Demand is the order total copied onto the unit.
8290+
8291+
A lower RTO / insurance can leave the agreed price a few thousand above
8292+
today's on-road cost. That is still one vehicle. The copied order total
8293+
matches the lead's Cx Demand and also covers another unit's ex-showroom.
8294+
"""
8295+
cx = ce.round2(ce.num(cx))
8296+
if cx <= 0 or not isinstance(units, list) or len(units) < 2:
8297+
return False
8298+
lead_cx = ce.round2(ce.num(
8299+
(lead or {}).get("cxDemand") or (lead or {}).get("customerPayable")
8300+
or (lead or {}).get("budget")))
8301+
if abs(cx - lead_cx) > ce.DEAL_AMOUNT_EQUAL_RUPEES:
8302+
return False
8303+
this_ex = ce.round2(ce.num((units[idx] or {}).get("exShowroom") or (lead or {}).get("exShowroom")))
8304+
if this_ex <= 0:
8305+
return False
8306+
for j, other in enumerate(units):
8307+
if j == idx or not isinstance(other, dict):
8308+
continue
8309+
other_ex = ce.round2(ce.num(other.get("exShowroom")))
8310+
if other_ex <= ce.DEAL_AMOUNT_EQUAL_RUPEES:
8311+
continue
8312+
# The figure includes about half of another vehicle, not just RTO / insurance.
8313+
if cx > this_ex + other_ex * 0.5 + ce.DEAL_AMOUNT_EQUAL_RUPEES:
8314+
return True
8315+
return False
8316+
8317+
82658318
def _refresh_unit_payables(lead, scheme_rows=None):
82668319
"""Write each unit's payable and return (total_of_counted, units, filled, pending)."""
82678320
units = list((lead or {}).get("units") or [])
@@ -8294,7 +8347,8 @@ def _refresh_unit_payables(lead, scheme_rows=None):
82948347
if (not pack) and u.get("useDealPrice") and ce.num(u.get("cxDemand")) > 0:
82958348
pay = ce.round2(ce.num(u.get("cxDemand")))
82968349
elif pack:
8297-
if ce.pack_unit_cx_is_pack_rollup(u.get("cxDemand"), snap, u):
8350+
if (ce.pack_unit_cx_is_pack_rollup(u.get("cxDemand"), snap, u)
8351+
or _cx_copies_pack_total(u.get("cxDemand"), lead, units, i)):
82988352
u.pop("cxDemand", None)
82998353
u["useDealPrice"] = False
83008354
lock = ce.pack_unit_locked_cx_demand(snap, u)
@@ -8312,8 +8366,10 @@ def _refresh_unit_payables(lead, scheme_rows=None):
83128366
u["useDealPrice"] = True
83138367
pay = lock
83148368
else:
8369+
u["extraIncomeFromCustomer"] = 0
83158370
pay = ce.round2(ce.num(totals.get("customerPayable")))
83168371
else:
8372+
u["extraIncomeFromCustomer"] = 0
83178373
pay = ce.round2(ce.num(totals.get("customerPayable")))
83188374
else:
83198375
pay = ce.round2(ce.num(totals.get("customerPayable")))

‎backend/tests/test_deal_pass_meet_cx.py‎

Lines changed: 111 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -176,6 +176,17 @@ def test_pack_unit_lock_ignores_pack_total_cx_on_unit():
176176
assert ce.pack_unit_locked_cx_demand(snap, unit) == 0
177177
own = {"additionalDiscount": 59500, "cxDemand": 790000, "exShowroom": 825000}
178178
assert ce.pack_unit_locked_cx_demand(snap, own) == 790000
179+
# Agreed price sits above today's GVC after a large RTO / insurance cut.
180+
# That is this unit's deal, not the pack total.
181+
reduced = {
182+
"model": "Turbo Max", "variant": "Maxx (PV)",
183+
"exShowroom": 785000, "registrationRto": 0, "insurance": 10000,
184+
"accessories": 0, "fastag": 0, "handlingCharges": 0, "trc": 0,
185+
"extendedWarranty": 0, "rsaAmc": 0, "otherCharges": 0,
186+
}
187+
agreed = {"additionalDiscount": 4500, "cxDemand": 805000, "exShowroom": 785000}
188+
assert ce.pack_unit_cx_is_pack_rollup(805000, reduced, agreed) is False
189+
assert ce.pack_unit_locked_cx_demand(reduced, agreed) == 805000
179190

180191

181192
def test_additional_discount_has_no_maximum():
@@ -259,6 +270,106 @@ async def test_pack_rto_insurance_cut_shrinks_additional_not_payable(client):
259270
assert ce.num(u1.get("customerPayable")) != 820074
260271

261272

273+
@pytest.mark.asyncio
274+
async def test_confirmed_rto_cut_leaves_additional_200(client):
275+
"""Extra discount 4,500 on list RTO 5,500 / insurance 19,000.
276+
277+
RTO 2,200 and insurance 18,000 cut 4,300, so Additional becomes 200.
278+
Payable stays. Same on one vehicle, on pack unit 2, and when the cut
279+
is larger than the discount (Additional goes to 0, payable stays).
280+
"""
281+
ex, list_rto, list_ins = 785000, 5500, 19000
282+
pay = ex + list_rto + list_ins - 4500 # 805000
283+
284+
async def make(lid, *, pack=False):
285+
await server.db.leads.delete_many({"leadId": lid})
286+
await server.db.price_master.delete_many({"priceId": f"PM-{lid}"})
287+
await server.db.price_master.insert_one({
288+
"priceId": f"PM-{lid}", "model": "Turbo Max", "variant": "Maxx Confirmed",
289+
"exShowroom": ex, "rto": list_rto, "insurance": list_ins,
290+
"status": "active", "oemSyncedAt": "2026-11-01T00:00:00",
291+
})
292+
unit = {
293+
"model": "Turbo Max", "variant": "Maxx Confirmed",
294+
"exShowroom": ex, "rto": list_rto, "insuranceAmount": list_ins, "insurance": list_ins,
295+
"additionalDiscount": 4500, "customerPayable": pay, "cxDemand": pay,
296+
"useDealPrice": True, "priceStructureSaved": True,
297+
"schemeAllocationExplicit": True, "benefitPassedBreakup": "{}",
298+
}
299+
doc = {
300+
"leadId": lid, "customerName": lid, "mobile": "9000003344",
301+
"interestedModel": "Turbo Max", "variant": "Maxx Confirmed",
302+
"executive": "Amit", "accountStatus": "Active", "currentStatus": "Booked",
303+
"bookingDate": "2026-11-06", "priceStructureSaved": True,
304+
"schemeAllocationExplicit": True, "benefitPassedBreakup": "{}",
305+
"exShowroom": ex, "rto": list_rto, "insuranceAmount": list_ins, "insurance": list_ins,
306+
"additionalDiscount": 4500, "customerPayable": pay, "cxDemand": pay, "useDealPrice": True,
307+
"units": [dict(unit, sno=1)],
308+
}
309+
if pack:
310+
doc["sameOrderMultiUnit"] = True
311+
doc["units"] = [dict(unit, sno=1), dict(unit, sno=2)]
312+
doc["customerPayable"] = pay * 2
313+
doc["cxDemand"] = pay * 2
314+
await server.db.leads.insert_one(doc)
315+
316+
await make("LD-CONF-RTO")
317+
saved = await client.put("/api/leads/LD-CONF-RTO/price-structure", json={
318+
"exShowroom": ex, "rto": 2200, "insuranceAmount": 18000,
319+
})
320+
assert saved.status_code == 200, saved.text
321+
one = saved.json()
322+
assert ce.num(one["customerPayable"]) == pay
323+
assert ce.num(one["additionalDiscount"]) == 200
324+
325+
await make("LD-CONF-RTO-PACK", pack=True)
326+
pack_saved = await client.put("/api/leads/LD-CONF-RTO-PACK/price-structure", json={
327+
"exShowroom": ex, "rto": 2200, "insuranceAmount": 18000, "unitSno": 2,
328+
})
329+
assert pack_saved.status_code == 200, pack_saved.text
330+
after = await server.db.leads.find_one({"leadId": "LD-CONF-RTO-PACK"})
331+
u1, u2 = after["units"][0], after["units"][1]
332+
assert ce.num(u2["customerPayable"]) == pay
333+
assert ce.num(u2["additionalDiscount"]) == 200
334+
assert ce.num(u1["additionalDiscount"]) == 4500
335+
assert ce.num(u1["rto"]) == list_rto
336+
337+
await make("LD-CONF-RTO-OF", pack=True)
338+
rto = await client.put("/api/leads/LD-CONF-RTO-OF/owner-field", json={
339+
"field": "rto", "value": 2200, "unitSno": 2,
340+
})
341+
assert rto.status_code == 200, rto.text
342+
ins = await client.put("/api/leads/LD-CONF-RTO-OF/owner-field", json={
343+
"field": "insuranceAmount", "value": 18000, "unitSno": 2,
344+
})
345+
assert ins.status_code == 200, ins.text
346+
edited = await server.db.leads.find_one({"leadId": "LD-CONF-RTO-OF"})
347+
edited_u1, edited_u2 = edited["units"][0], edited["units"][1]
348+
assert ce.num(edited_u2["rto"]) == 2200
349+
assert ce.num(edited_u2["insuranceAmount"]) == 18000
350+
assert ce.num(edited_u2["customerPayable"]) == pay
351+
assert ce.num(edited_u2["additionalDiscount"]) == 200
352+
assert ce.num(edited_u1["additionalDiscount"]) == 4500
353+
assert ce.num(edited["rto"]) == list_rto
354+
355+
# Cut 14,500 is larger than Additional 4,500. Discount goes to 0.
356+
# Payable stays; the rest is extra from the customer, not a cheaper price.
357+
await make("LD-CONF-RTO-BIG", pack=True)
358+
big = await client.put("/api/leads/LD-CONF-RTO-BIG/price-structure", json={
359+
"exShowroom": ex, "rto": 0, "insuranceAmount": 10000, "unitSno": 2,
360+
})
361+
assert big.status_code == 200, big.text
362+
big_doc = await server.db.leads.find_one({"leadId": "LD-CONF-RTO-BIG"})
363+
big_u2 = big_doc["units"][1]
364+
assert ce.num(big_u2["customerPayable"]) == pay
365+
assert ce.num(big_u2["cxDemand"]) == pay
366+
assert ce.num(big_u2["additionalDiscount"]) == 0
367+
assert ce.num(big_u2.get("extraIncomeFromCustomer")) == 10000
368+
base_margin = ce.compute_dealer_margin({"exShowroom": ex})["marginNetExGst"]
369+
assert ce.num(big_doc.get("extraIncomeFromCustomer")) == 10000
370+
assert ce.num(big_doc.get("dealerMarginNetExGst")) == ce.round2(base_margin + 10000)
371+
372+
262373
@pytest.mark.asyncio
263374
async def test_actual_rto_and_insurance_cut_additional_not_payable(client):
264375
"""Lower real RTO and insurance shrink Additional. Payable and excess stay."""

‎backend/tests/test_same_order_multi_unit.py‎

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -833,6 +833,75 @@ def test_refresh_drops_pack_total_locked_onto_unit1():
833833
assert total == 1580000
834834

835835

836+
def test_refresh_drops_copied_pack_total_under_one_and_a_half_ex():
837+
"""A Storm plus a cheaper sibling can copy an order total under 1.5× ex.
838+
839+
12,00,000 × 1.5 is 18,00,000. The copied ₹17,70,000 still includes the
840+
other vehicle, so unit 1 must not lock to it and then add the sibling again.
841+
"""
842+
pack = 1770000
843+
lead = {
844+
"sameOrderMultiUnit": True,
845+
"interestedModel": "Storm", "variant": "LR200",
846+
"exShowroom": 1200000,
847+
"cxDemand": pack, "customerPayable": pack, "budget": pack,
848+
"useDealPrice": True,
849+
"units": [
850+
{
851+
"sno": 1, "model": "Storm", "variant": "LR200",
852+
"exShowroom": 1200000, "rto": 0, "insuranceAmount": 0,
853+
"additionalDiscount": 0, "priceStructureSaved": True,
854+
"cxDemand": pack, "useDealPrice": True, "customerPayable": pack,
855+
},
856+
{
857+
"sno": 2, "model": "HiRange", "variant": "SR",
858+
"exShowroom": 590000, "rto": 0, "insuranceAmount": 0,
859+
"additionalDiscount": 0, "priceStructureSaved": True,
860+
"cxDemand": 590000, "useDealPrice": True, "customerPayable": 590000,
861+
},
862+
],
863+
}
864+
total, rows, _filled, _pending = server._refresh_unit_payables(lead)
865+
# One vehicle, not the copied ₹17,70,000, and not that figure plus the sibling.
866+
assert ce.num(rows[0].get("customerPayable")) < 1300000
867+
assert ce.num(rows[0].get("cxDemand") or 0) != pack
868+
assert ce.num(rows[1].get("customerPayable")) == 590000
869+
assert total == ce.round2(ce.num(rows[0].get("customerPayable")) + 590000)
870+
assert total != pack + 590000
871+
872+
873+
def test_refresh_keeps_agreed_price_a_few_thousand_above_gvc():
874+
"""RTO / insurance cut: payable stays, the gap is extra from the customer."""
875+
lead = {
876+
"sameOrderMultiUnit": True,
877+
"interestedModel": "Turbo Max", "variant": "Maxx (PV)",
878+
"exShowroom": 785000,
879+
"cxDemand": 1610000, "customerPayable": 1610000,
880+
"useDealPrice": True,
881+
"units": [
882+
{
883+
"sno": 1, "model": "Turbo Max", "variant": "Maxx (PV)",
884+
"exShowroom": 785000, "rto": 0, "insuranceAmount": 10000,
885+
"additionalDiscount": 4500, "priceStructureSaved": True,
886+
"cxDemand": 805000, "useDealPrice": True, "customerPayable": 805000,
887+
},
888+
{
889+
"sno": 2, "model": "Turbo Max", "variant": "Maxx (PV)",
890+
"exShowroom": 785000, "rto": 5500, "insuranceAmount": 19000,
891+
"additionalDiscount": 4500, "priceStructureSaved": True,
892+
"cxDemand": 805000, "useDealPrice": True, "customerPayable": 805000,
893+
},
894+
],
895+
}
896+
total, rows, _filled, _pending = server._refresh_unit_payables(lead)
897+
assert ce.num(rows[0].get("customerPayable")) == 805000
898+
assert ce.num(rows[0].get("additionalDiscount")) == 0
899+
assert ce.num(rows[0].get("extraIncomeFromCustomer")) == 10000
900+
assert ce.num(rows[1].get("customerPayable")) == 805000
901+
assert ce.num(rows[1].get("additionalDiscount")) == 4500
902+
assert total == 1610000
903+
904+
836905
def test_pack_billing_summary_lists_each_unit_then_totals():
837906
lead = {
838907
"leadId": "LD-PACK-BILL",

‎frontend/src/pages/LeadDrawer.js‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1875,8 +1875,9 @@ export function SchemeTab({ lead, c, actions = {}, isOwner = false, masters, onS
18751875
});
18761876
setUsedMap(inferred);
18771877
// Billed date drives scheme month per pack unit; a model / variant change
1878-
// brings different scheme pools.
1879-
}, [lead.leadId, unitSno, lead.schemeAsOf, lead.bookingDate, unitSoldDate, src.interestedModel, src.variant]);
1878+
// brings different scheme pools. Additional follows a price save: a lower
1879+
// RTO / insurance shrinks it, and this form must not save the old figure.
1880+
}, [lead.leadId, unitSno, lead.schemeAsOf, lead.bookingDate, unitSoldDate, src.interestedModel, src.variant, src.additionalDiscount]);
18801881
useEffect(() => {
18811882
if (!lead.leadId || !schemeDate) return;
18821883
get(`/leads/${lead.leadId}/scheme-rules`, { on: schemeDate, ...(units ? { unit: unitSno } : {}) })

0 commit comments

Comments
 (0)