```python def settle_order(order): if not isinstance(order, dict): raise ValueError("order must be a dict") required_order_fields = ("order_id", "discount_cents", "shipping_cents", "lines") for field in required_order_fields: if field not in order: raise ValueError("missing order field: %s" % field) discount = order["discount_cents"] shipping = order["shipping_cents"] raw_lines = order["lines"] if type(discount) is not int: raise ValueError("discount_cents must be an integer") if type(shipping) is not int or shipping < 0: raise ValueError("shipping_cents must be a non-negative integer") if not isinstance(raw_lines, (list, tuple)) or len(raw_lines) == 0: raise ValueError("lines must be a non-empty list") parsed_lines = [] subtotal = 0 for item in raw_lines: if not isinstance(item, dict): raise ValueError("each line must be a dict") for field in ("sku", "qty", "unit_price_cents"): if field not in item: raise ValueError("missing line field: %s" % field) qty = item["qty"] unit_price = item["unit_price_cents"] if type(qty) is not int or qty <= 0: raise ValueError("qty must be a positive integer") if type(unit_price) is not int or unit_price < 0: raise ValueError("unit_price_cents must be a non-negative integer") gross = qty * unit_price parsed_lines.append((item["sku"], gross)) subtotal += gross if discount < 0 or discount > subtotal: raise ValueError("discount_cents must be between 0 and subtotal_cents") if subtotal == 0: if discount != 0: raise ValueError("discount_cents must be 0 when subtotal_cents is 0") allocations = [0] * len(parsed_lines) else: allocations = [] remainders = [] allocated_total = 0 for _, gross in parsed_lines: product = gross * discount base = product // subtotal remainder = product % subtotal allocations.append(base) remainders.append(remainder) allocated_total += base leftover = discount - allocated_total if leftover: ranked_indices = sorted( range(len(parsed_lines)), key=lambda index: (-remainders[index], index) ) for index in ranked_indices[:leftover]: allocations[index] += 1 result_lines = [] for (sku, gross), allocated in zip(parsed_lines, allocations): net = gross - allocated if net < 0: raise ValueError("invalid allocation produced a negative net amount") result_lines.append({ "sku": sku, "gross_cents": gross, "discount_cents": allocated, "net_cents": net, }) return { "order_id": order["order_id"], "subtotal_cents": subtotal, "shipping_cents": shipping, "payable_cents": subtotal - discount + shipping, "lines": result_lines, } ```