Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
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
6 changes: 4 additions & 2 deletions services/api/app/services/ledger/templates.py
Original file line number Diff line number Diff line change
Expand Up @@ -245,8 +245,10 @@ def refund_lane2(
PostingLeg(AccountRef("commission_revenue"), -restocking),
PostingLeg(AccountRef("marketing_expense"), -promo),
)
# Zero legs are dropped only for the coupon leg so the legacy shape is unchanged.
legs = candidates if promo else candidates[:4]
# A posting leg must be non-zero: pickup orders (no outbound delivery, no return
# transport) retain 0 for the vendor, and a 0% restocking fee posts none. Drop
# zero legs; the remaining legs still balance (escrow = refund + retained + fee).
legs = tuple(leg for leg in candidates if leg.amount_ngwee != 0)
_assert_balanced(legs)
return TemplateResult(kind=LedgerTemplate.REFUND_LANE2, legs=legs)

Expand Down
24 changes: 14 additions & 10 deletions services/api/app/services/returns/lane2.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
from app.services.refunds.execute import RefundExecutionResult, execute_refund
from app.services.refunds.math import compute_lane2_refund, normalize_restocking_fee_bps
from app.services.refunds.payout_port import CustomerRail
from app.services.returns.lane1 import _load_customer_refund_destination

MIN_RETURN_WINDOW_HOURS = 48
MAX_RETURN_WINDOW_HOURS = 168
Expand Down Expand Up @@ -310,7 +311,12 @@ def create_lane2_return(
customer_momo: str | None = None,
customer_rail: CustomerRail = "mtn",
) -> Lane2ReturnRecord:
"""Insert lane-2 return row and execute M08-P10 lane-2 refund."""
"""Insert lane-2 return row and execute M08-P10 lane-2 refund.

The refund goes only to the verified destination (the Mobile Money number that
paid, else the SMS-confirmed phone; qa-1 #1224). ``customer_momo`` and
``customer_rail`` are ignored: a request can never choose where the money goes.
"""
if not unused_declared:
raise AppError(
"validation_error",
Expand Down Expand Up @@ -361,20 +367,18 @@ def create_lane2_return(
{"order_item_id": order_item_id},
)

if not customer_momo:
raise AppError(
"validation_error",
"customer_momo is required to execute lane-2 refund",
422,
)

# Payout kill switch: a lane-2 return immediately executes a customer refund.
# Refuse after read-only validation but before ANY write (return row, ledger,
# refund row, payout row).
assert_customer_refund_allowed(
surface="returns_lane2_create", details={"order_item_id": order_item_id}
)

# Resolve the verified destination BEFORE any write: a refusal leaves no return row.
refund_momo, refund_rail = _load_customer_refund_destination(
service_client, order_id=order_id, customer_id=customer_id
)

return_id = str(uuid.uuid4())
fee_breakdown = breakdown.as_dict()
insert_row = {
Expand All @@ -395,8 +399,8 @@ def create_lane2_return(
order_id=order_id,
lane=2,
return_transport_ngwee=breakdown.return_transport,
customer_rail=customer_rail,
customer_momo=customer_momo,
customer_rail=refund_rail,
customer_momo=refund_momo,
idempotency_key=f"return-{return_id}",
# Scope the refund to the single returned item (and its prorated outbound
# delivery) instead of the whole order, matching the previewed breakdown.
Expand Down
31 changes: 31 additions & 0 deletions services/api/tests/test_ledger.py
Original file line number Diff line number Diff line change
Expand Up @@ -225,6 +225,37 @@ def test_refund_lane2_golden() -> None:
)


def test_refund_lane2_pickup_order_drops_zero_vendor_retained_leg() -> None:
"""qa-1 #1224: pickup + no return transport retains 0 for the vendor (no 0 leg)."""
result = refund_lane2(
escrow_release_ngwee=100_000,
refund_to_customer_ngwee=90_000,
vendor_retained_ngwee=0,
restocking_fee_ngwee=10_000,
vendor_id=VENDOR_A,
)
assert _sum_legs(result) == 0
assert result.legs == (
PostingLeg(AccountRef("escrow"), 100_000),
PostingLeg(AccountRef("platform_cash"), -90_000),
PostingLeg(AccountRef("commission_revenue"), -10_000),
)


def test_refund_lane2_zero_restocking_fee_drops_commission_leg() -> None:
result = refund_lane2(
escrow_release_ngwee=100_000,
refund_to_customer_ngwee=100_000,
vendor_retained_ngwee=0,
restocking_fee_ngwee=0,
vendor_id=VENDOR_A,
)
assert result.legs == (
PostingLeg(AccountRef("escrow"), 100_000),
PostingLeg(AccountRef("platform_cash"), -100_000),
)


def ensure_idempotency_column(conn: PgConn) -> None:
result = conn.run(
"""
Expand Down
119 changes: 116 additions & 3 deletions services/api/tests/test_returns_lane2.py
Original file line number Diff line number Diff line change
Expand Up @@ -318,9 +318,7 @@ def test_eligible_within_window(self) -> None:
class TestRestockingConfig:
def test_load_restocking_fee_bps_from_platform_config(self) -> None:
fake = FakeSupabaseClient()
fake.tables["platform_config"].rows.append(
{"key": "restocking_fee_bps", "value": 1250}
)
fake.tables["platform_config"].rows.append({"key": "restocking_fee_bps", "value": 1250})
assert load_restocking_fee_bps(FakeServiceClient(fake)) == 1250

def test_load_restocking_fee_bps_defaults_when_absent(self) -> None:
Expand All @@ -344,6 +342,17 @@ def test_sub_percent_bps_survives_across_paths(self) -> None:
assert breakdown.restocking == 25_000 # 12.5%, not 24_000 (12%)


VERIFIED_DESTINATION = ("260971234567", "mtn")


@pytest.fixture(autouse=True)
def _verified_destination(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(
"app.services.returns.lane2._load_customer_refund_destination",
lambda *_a, **_k: VERIFIED_DESTINATION,
)


class TestCreateLane2Return:
@patch("app.services.returns.lane2.execute_refund")
def test_create_lane2_return_executes_matching_refund(self, mock_execute: MagicMock) -> None:
Expand Down Expand Up @@ -445,6 +454,110 @@ def test_multi_item_order_refunds_only_returned_item(self, mock_execute: MagicMo
assert kwargs["item_ngwee_override"] == 200_000
assert kwargs["delivery_fee_ngwee_override"] == prorated_delivery

@patch("app.services.returns.lane2.execute_refund")
def test_request_cannot_redirect_refund_destination(
self, mock_execute: MagicMock, monkeypatch: pytest.MonkeyPatch
) -> None:
"""qa-1 #1224: lane 2 pays only the verified number, never the caller's."""
fake = FakeSupabaseClient()
_seed_eligible_order(
fake,
delivered_at=datetime.now(tz=UTC) - timedelta(hours=24),
item_ngwee=200_000,
delivery_fee=10_000,
)
preview = compute_lane2_breakdown(
item_ngwee=200_000,
outbound_delivery_ngwee=10_000,
return_transport_ngwee=0,
restocking_fee_bps=1000,
)
mock_execute.return_value = RefundExecutionResult(
refund_id="refund-1",
order_id=ORDER_ID,
lane=2,
phase=RefundPhase.PRE_RELEASE,
amount_ngwee=preview.refund_ngwee,
payout_id="payout-1",
lenco_reference="pay-ref",
ledger_transaction_ids=("ledger-1",),
breakdown={"refund_ngwee": preview.refund_ngwee},
created=True,
)
create_lane2_return(
FakeServiceClient(fake),
order_item_id=ORDER_ITEM_ID,
customer_id=CUSTOMER_ID,
unused_declared=True,
customer_momo="260977000000",
customer_rail="airtel",
)
kwargs = mock_execute.call_args.kwargs
assert kwargs["customer_momo"] == VERIFIED_DESTINATION[0]
assert kwargs["customer_rail"] == VERIFIED_DESTINATION[1]

@patch("app.services.returns.lane2.execute_refund")
def test_works_without_any_customer_momo_in_the_request(self, mock_execute: MagicMock) -> None:
"""The router passes no number; lane 2 used to 422 on that, always."""
fake = FakeSupabaseClient()
_seed_eligible_order(
fake,
delivered_at=datetime.now(tz=UTC) - timedelta(hours=24),
item_ngwee=200_000,
delivery_fee=0,
)
preview = compute_lane2_breakdown(
item_ngwee=200_000,
outbound_delivery_ngwee=0,
return_transport_ngwee=0,
restocking_fee_bps=1000,
)
mock_execute.return_value = RefundExecutionResult(
refund_id="refund-1",
order_id=ORDER_ID,
lane=2,
phase=RefundPhase.PRE_RELEASE,
amount_ngwee=preview.refund_ngwee,
payout_id="payout-1",
lenco_reference="pay-ref",
ledger_transaction_ids=("ledger-1",),
breakdown={"refund_ngwee": preview.refund_ngwee},
created=True,
)
record = create_lane2_return(
FakeServiceClient(fake),
order_item_id=ORDER_ITEM_ID,
customer_id=CUSTOMER_ID,
unused_declared=True,
)
assert record.refund.amount_ngwee == preview.refund_ngwee

@patch("app.services.returns.lane2.execute_refund")
def test_unverified_destination_refuses_before_any_write(
self, mock_execute: MagicMock, monkeypatch: pytest.MonkeyPatch
) -> None:
def refuse(*_a: Any, **_k: Any) -> None:
raise AppError("refund.destination_unverified", "no verified number", 422)

monkeypatch.setattr("app.services.returns.lane2._load_customer_refund_destination", refuse)
fake = FakeSupabaseClient()
_seed_eligible_order(
fake,
delivered_at=datetime.now(tz=UTC) - timedelta(hours=24),
item_ngwee=200_000,
delivery_fee=10_000,
)
with pytest.raises(AppError) as exc:
create_lane2_return(
FakeServiceClient(fake),
order_item_id=ORDER_ITEM_ID,
customer_id=CUSTOMER_ID,
unused_declared=True,
)
assert exc.value.code == "refund.destination_unverified"
assert fake.tables["returns"].rows == []
mock_execute.assert_not_called()

def test_create_requires_unused_declaration(self) -> None:
fake = FakeSupabaseClient()
_seed_eligible_order(
Expand Down
Loading