Legacy checkout refactor
Juniper Retail's checkout owner needs a safe policy refactor. The supplied order lines contain quantities, integer unit amounts and optional policy fields. Deliver a pure replayable total with explicit validation, discount, cancellation, tax and duplicate-ID boundaries.
Juniper Retail has a checkout calculation that grew by adding conditions to one loop. The team needs to introduce validation, discounts, cancellations, tax and replay protection without changing unrelated behavior. You start by preserving a characterized total.
Each later step adds one named policy and begins from the preceding reference implementation. Keep calculation in a helper so record selection and arithmetic remain separate. Monetary amounts are fictional integer units; the tax rule rounds down on each line because that is the supplied contract. Don't substitute a rule from a real jurisdiction. A duplicate event ID is applied once only after validation and cancellation checks. This order determines which record becomes the accepted first occurrence.
import json
def process_payload(payload: str) -> str:
data = json.loads(payload)
def subtotal(row):
amount = row['quantity'] * row['unit']
return amount
amounts, seen = [], set()
for row in data['rows']:
amounts.append(subtotal(row))
return json.dumps(sum(amounts))
A characterization check preserves the existing result before changing policy. Keep record selection outside the subtotal helper so one policy can change without mixing arithmetic and validation. The implementation visits each line once and keeps a set only when replay protection is introduced.