Fix the billing settlement that charges and records
Your task
Your billing service charges a customer through a payment gateway, then saves a record of the charge in the database. An agent's test only checked that both calls happened, so the team now checks the settlement itself, one log line per action.
An assistant wrote settle_charges(requests, charge_ids, insert_ok). It is in the editor. It has a bug. Find it and fix it.
Input and output:
requests: one charge request per entry,"<customer>|<amount_cents>".charge_ids: entry i is the charge id the gateway returned for request i, or""when the gateway declined it. The list can be shorter thanrequests.insert_ok: entry i is true when the database insert for request i succeeded and false when it failed. The list can be shorter thanrequests.- Return the action log, a list of strings, in request order.
Rules the tests check:
- Handle the requests in order. Entry i of
charge_idsand ofinsert_okalways belongs to request i, even when an earlier request was invalid or declined. - Split a request at its first
|. The part before it is the customer. The part after it is the amount in cents. - A request is invalid in any of these cases:
- it has no
| - the customer is empty
- the amount is not 1 to 9 digits (0 to 9 only), or its value is 0
- it has no
- The amounts
"5.00","-25","0","500|extra"and any 10-digit amount are all invalid. - For an invalid request, log
"invalid:<request>"with the request exactly as given, and nothing else. - Otherwise, when
charge_idshas no entry i or the entry is"", the gateway declined. Log"declined:<customer>"and nothing else for it. - Otherwise log
"charged:<customer>:<amount>:<charge_id>". Write the amount as a plain integer: leading zeros go away, so"000000500"becomes500. - Right after a charge, when
insert_okhas entry i and it is true, log"recorded:<charge_id>". In every other case, log"refunded:<charge_id>". A missing entry counts as a failed insert. - No requests returns an empty list.
Examples
settle_charges(requests: list[str], charge_ids: list[str], insert_ok: list[bool]) -> list[str]Example 1
Input
settle_charges(["cus_1|500"], ["ch_1"], [True])Output
["charged:cus_1:500:ch_1", "recorded:ch_1"]Example 2
Input
settle_charges(["cus_1|500"], ["ch_1"], [False])Output
["charged:cus_1:500:ch_1", "refunded:ch_1"]Example 3
Input
settle_charges(["cus_1|5.00"], ["ch_1"], [True])Output
["invalid:cus_1|5.00"]