IntermediateLesson 8 of 127 min read

Mapping and Validating Vendor Data: Minor Units, Time Zones and Contract Tests

Translate a vendor's order format into your own model: convert amounts using each currency's minor units, normalise time zones, handle missing and unexpected values, check totals with property tests, and cross-check the conversions independently.

In this lesson you will

  • Map vendor fields to an internal model
  • Convert money using minor units
  • Normalise dates and time zones
  • Test mapping with invariants

About 28 minutes

Three vendors, three ways to say “an order”

Noor now sells through two marketplaces besides her own site, and each sends orders in its own format: one gives prices as strings in euros, one as integer yen, and one as integers in thousandths of a Kuwaiti dinar. Dates arrive with different offsets, and one marketplace sometimes omits the postcode. Her warehouse program wants one internal model: an order with an id, a UTC timestamp, a currency, line items in integer minor units, and a total. The code that translates is a mapper. It is the most valuable code in an integration to test, because mistakes in it are silent: wrong totals, wrong days, lost lines.

Currencies have different numbers of decimal places, called minor units. The euro has 2, so 12.50 euros is 1,250 cents. The Japanese yen has 0, so 1,250 yen is 1,250 units. The Kuwaiti dinar has 3, so 1.250 dinars is 1,250 fils. Multiplying every amount by 100 is therefore wrong for two of these three. The mapper should look up the exponent for the currency, from the ISO 4217 table, and fail loudly on a currency it does not know. Another useful tool is an invariant, a rule that must always hold: the line items of an order add up to its total. A test that checks the invariant on many inputs catches a whole family of mistakes that example-based tests miss.

Currency Minor unit exponent 12.5 in minor units
EUR 2 1250
JPY 0 13 (rounded), amounts are whole
KWD 3 12500
Unknown – Error: refuse the order
import json
from decimal import Decimal, ROUND_HALF_UP
from datetime import datetime, timezone

EXPONENT = {"EUR": 2, "JPY": 0, "KWD": 3}          # an excerpt of ISO 4217; hedge: check the full table
def to_minor(amount, cur):
    if cur not in EXPONENT: raise ValueError("unknown currency " + cur)
    return int((Decimal(str(amount)) * 10 ** EXPONENT[cur]).quantize(Decimal(1), rounding=ROUND_HALF_UP))
def to_utc(s): return datetime.fromisoformat(s).astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")

def map_market_a(o):      # prices are strings in major units, dates with offsets
    lines = [{"sku": l["sku"], "qty": l["qty"], "unit_minor": to_minor(l["price"], o["currency"])} for l in o["lines"]]
    return {"id": "A-" + str(o["number"]), "at": to_utc(o["created"]), "currency": o["currency"], "lines": lines, "total_minor": to_minor(o["total"], o["currency"]), "postcode": o.get("postcode") or None}
def map_market_b(o):      # prices are already integers in minor units, total given separately
    lines = [{"sku": l["code"], "qty": l["count"], "unit_minor": l["unit"]} for l in o["items"]]
    return {"id": "B-" + o["ref"], "at": to_utc(o["ts"]), "currency": o["cur"], "lines": lines, "total_minor": o["grand"], "postcode": o.get("zip")}

orders = [
    map_market_a({"number": 1, "created": "2024-03-10T23:30:00-05:00", "currency": "EUR", "lines": [{"sku": "fern", "qty": 2, "price": "4.50"}, {"sku": "pot", "qty": 1, "price": "3.50"}], "total": "12.50", "postcode": "10115"}),
    map_market_a({"number": 2, "created": "2024-03-11T09:00:00+09:00", "currency": "JPY", "lines": [{"sku": "fern", "qty": 3, "price": "650"}], "total": "1950"}),
    map_market_a({"number": 3, "created": "2024-03-11T12:00:00+03:00", "currency": "KWD", "lines": [{"sku": "cactus", "qty": 2, "price": "1.250"}], "total": "2.500", "postcode": ""}),
    map_market_b({"ref": "77", "ts": "2024-03-11T04:30:00Z", "cur": "EUR", "items": [{"code": "fern", "count": 1, "unit": 450}, {"code": "pot", "count": 2, "unit": 350}], "grand": 1150, "zip": "75001"}),
]
for o in orders:
    inv = sum(l["qty"] * l["unit_minor"] for l in o["lines"]) == o["total_minor"]
    print(o["id"].ljust(5), o["at"], o["currency"], "total", o["total_minor"], "| lines add up:", inv, "| postcode:", o["postcode"])
try: map_market_a({"number": 9, "created": "2024-03-11T12:00:00Z", "currency": "XYZ", "lines": [], "total": "0"})
except ValueError as e: print("unknown currency is refused:", e)
print("rounding: 0.125 EUR ->", to_minor("0.125", "EUR"), "cents | 0.5 JPY ->", to_minor("0.5", "JPY"), "| binary float 0.125 * 100 =", 0.125 * 100, "| float 1.005 * 100 =", 1.005 * 100)
print("DATA " + json.dumps({"orders": orders}))
A-1   2024-03-11T04:30:00Z EUR total 1250 | lines add up: True | postcode: 10115
A-2   2024-03-11T00:00:00Z JPY total 1950 | lines add up: True | postcode: None
A-3   2024-03-11T09:00:00Z KWD total 2500 | lines add up: True | postcode: None
B-77  2024-03-11T04:30:00Z EUR total 1150 | lines add up: True | postcode: 75001
unknown currency is refused: unknown currency XYZ
rounding: 0.125 EUR -> 13 cents | 0.5 JPY -> 1 | binary float 0.125 * 100 = 12.5 | float 1.005 * 100 = 100.49999999999999

The mapper turned four vendor orders into one internal shape. Market A’s first order was placed at 23:30 in New York on 10 March, which is 04:30 UTC on 11 March, and the euro prices “4.50” and “3.50” became 450 and 350 cents, so the total of 12.50 euros is 1,250 cents. The yen order priced at 650 yen per fern, three of them, is a total of 1,950 yen with no multiplication by 100, because the yen has no minor unit, and its Tokyo time of 09:00 is midnight UTC. The Kuwaiti order of two items at 1.250 dinars is 2,500 fils, since the dinar has three decimals. Market B already used integer minor units, and its UTC timestamp passed through unchanged.

Every order satisfied the invariant: quantity times unit price, summed over the lines, equals the total, in all four cases. That is a property worth testing on thousands of generated orders and not only on four examples. Missing data was handled with an explicit rule: an empty or absent postcode became None, one value, so the rest of the system need not distinguish an empty string from a missing key. An unknown currency, “XYZ”, raised an error and the order was refused instead of being guessed, which keeps a silent money error out of the warehouse.

The last line shows two classic rounding traps. Converting the amount with the decimal type and an explicit rounding rule gave 0.125 euros as 13 cents, rounding half up, and 0.5 yen as 1. A binary float computing 1.005 x 100 gives 100.49999999999999, not 100.5, so rounding it would give 100 and lose a cent. Always convert from the string form of the amount, never through a float, and decide the rounding rule with your accountant, since half-up and half-even give different answers on exact halves.

Independent check: the minor-unit conversions were repeated with exact fractions, 4.50 x 100, 1.250 x 1,000 and 1,950 x 1, and agree with the mapper. The three time-zone conversions were repeated in Node.js, whose Date implementation is entirely separate from Python’s: it printed 2024-03-11T04:30:00Z, 2024-03-11T00:00:00Z and 2024-03-11T09:00:00Z, identical to the UTC times of the mapped orders. A mapper checked by two languages and an invariant is much more trustworthy than one checked by eye.

Check by hand: New York in March before the clocks change is five hours behind UTC, so 23:30 becomes 04:30 the next day. Tokyo is nine hours ahead, so 09:00 becomes 00:00. Kuwait is three hours ahead, so 12:00 becomes 09:00. And 2 x 450 + 1 x 350 = 1,250, 3 x 650 = 1,950, 2 x 1,250 = 2,500 and 450 + 2 x 350 = 1,150.

Never multiply by 100 for all currencies

Use the currency’s exponent. Yen and many other currencies have no minor unit, and some have three. Look up the current ISO 4217 table, which changes occasionally.

Test invariants on generated data

Rules such as “lines add up to the total” and “UTC times are never in the future” can be checked on thousands of random orders. They find bugs that hand-picked examples miss.

About this course

Every program in this lesson was run while the course was written, with Python 3.13 (standard library only) against small mock APIs that the lesson itself starts on a local port, and cross-checked with curl, OpenSSL, Node.js or a second calculation. The services are invented stand-ins, not real vendors: always read the current documentation of the real API you use. The exponent table here is an excerpt for teaching. Use a maintained currency library or the full ISO 4217 list in real code.

Practice

Add USD, GBP and BHD to the table and generate 1,000 random orders to check the invariant. Make the mapper return a list of problems instead of raising on the first. Convert a daylight-saving boundary time and check it in two languages.

Check what you learned

Five quick questions. Pick an answer and you will see straight away whether it is right and why.

How many cents is 1,950 yen?

  1. There are no cents: 1,950 units
  2. 195,000
  3. 19.50
  4. 195

The yen has exponent 0.

Why convert from the string amount?

  1. Strings are faster
  2. JSON forbids numbers
  3. It saves memory
  4. Floats round incorrectly, like 1.005 x 100

Use Decimal.

What is an invariant?

  1. A variable
  2. A constant
  3. A comment
  4. A rule that must always hold, such as lines summing to the total

Test it on many inputs.

What should the mapper do with an unknown currency?

  1. Assume euros
  2. Multiply by 100
  3. Refuse the order loudly
  4. Ignore it

Silent money errors are the worst.

Why check time zones in a second language?

  1. Python is wrong
  2. Node is faster
  3. Independent implementations agree
  4. It is required

A cross-check.

Summary

  • A mapper turns vendor data into your internal model in one place.
  • Use each currency’s minor unit exponent and convert from strings.
  • Normalise dates to UTC.
  • Test invariants and cross-check conversions.

Next lesson

Lesson 9 covers a payment flow.

Questions

Should I store the vendor's original payload?

Yes, keep the raw payload next to the mapped order for audits and for re-mapping when you find a bug. Protect it as you would any customer data.

What is a contract test?

A test that checks that your mapper still works against recorded real responses, so that you notice when the provider changes the format.

How do I handle daylight saving time?

Convert to UTC at the edge using a library with a current time zone database, and store UTC. Convert to a local time zone only for display.

Progress is saved in this browser.