Porting the Invoice Script
In this lesson, you ported the bookkeeper’s Python invoice script to JavaScript, all but its last line, then checked the port’s output against Python’s, line by line.
- The script prints fourteen lines from the web shop’s export: the month’s weight, each café’s invoice and orders, the check against the shop, and where next month’s export starts. The dashboard runs on JavaScript, so the script moves there, and one wrong digit means a wrong bill.
- The docstring becomes a JSDoc block. The imports go:
JSONandMathare globals, and whole cents replacedecimal. The settings keep their capitals and gainconst. Each café swaps its dict for an object, its price still text. The export’s triple quotes turn into backticks: a template literal spans lines too, though like an f-string it runs a${inside as code. rf_reference()becomes a function declaration under a JSDoc block. Its 17-digit number is past what a JavaScript number holds exactly, so the check works in BigInt, with annon every literal. If you keep Python’s 98 and 97, the line stops with a TypeError and no invoice prints: BigInts and numbers don’t mix. For:02d, a"0"goes in front of a check below ten.JSON.parse()takes over fromjson.loads(), withkeepIdText()as its reviver. A plain parse rounds the nineteen-digit order numbers: Larder Lane’s invoice would list the first as1849327348870116000. The reviver returns the ID’s source text, so every order number stays exact. Weights stay numbers, and the total stays text.- Python’s
sum()compensates for float error, but a+=loop in kilos doesn’t, in either language: it reaches72.00000000000001, and the month’s line would say seven drum loads instead of six. So the port adds whole grams, and the drum loads divide by the drum’s grams. Kilos come back only for the output line, and.lengthcounts the orders. - Template literals have no format specs, so the port builds two formatters once:
euros, with thousands separators, andpercent, whoseroundingMode: "halfEven"rounds a half to even as Python’s.0%does. Without it, Bluebell’s invoice would show its exact 12.5% as 13%. - JavaScript has no decimal type, and
Number()in its place leaves the month’s total a fraction of a cent off the shop’s: the check fails. SotoCents()turns each price into whole cents:Number()only reads the text, andMath.round()drops its float error. - Over the café’s orders, the port adds the grams, and the amount adds the price in cents times the grams. A gram is a
thousandth of a kilo, so that’s thousandths of a cent: one
Math.round(amount / 1000)rounds a half up, asquantize()does. The month’s total adds whole cents. - Each
print()becomesconsole.log(), its template literals joined by+, because JavaScript doesn’t join side-by-side strings..toFixed(1)formats the kilos,percentthe share, andeurosthe amount, back from cents, with its own€. The order lines print each order number as the text the reviver kept. - On whole cents,
===replaces==on Decimals, withtoCents()on the shop’s total. Both branches print the total, so the port formats it once, above theif. node --checkreads the file without running it and prints nothing when there’s no syntax error. The port then prints the same thirteen lines as Python’s first thirteen.
Here’s the bookkeeper’s Python script, invoices.py:
"""Print the month's café invoices from the shop's export."""
import json
import math
from decimal import ROUND_HALF_UP, Decimal
MONTH = "October 2026"
INVOICE_MONTH = "202610"
DRUM_KG = 12
CENT = Decimal("0.01")
CAFES = [
{"name": "Larder Lane", "customer": "40417",
"price_per_kg": "18.50"},
{"name": "Bluebell Café", "customer": "40422",
"price_per_kg": "19.20"},
{"name": "Northside Kitchen", "customer": "40436",
"price_per_kg": "17.20"},
]
EXPORT_TEXT = """{"total": "1303.20", "orders": [
{"id": 1849327348870116187, "cafe": "Larder Lane", "kg": 12.6},
{"id": 1851209668946987412, "cafe": "Larder Lane", "kg": 11.6},
{"id": 1851490640428150336, "cafe": "Bluebell Café", "kg": 4.8},
{"id": 1852256687796522101, "cafe": "Northside Kitchen",
"kg": 9.7},
{"id": 1854088576215510147, "cafe": "Bluebell Café", "kg": 4.2},
{"id": 1854747213763410747, "cafe": "Northside Kitchen",
"kg": 8.9},
{"id": 1856614906249543762, "cafe": "Larder Lane", "kg": 11.8},
{"id": 1859100422386321067, "cafe": "Northside Kitchen",
"kg": 8.4}
]}"""
def rf_reference(reference):
"""Return the RF creditor reference the bank matches."""
check = 98 - int(reference + "271500") % 97
return f"RF{check:02d}{reference}"
shop_export = json.loads(EXPORT_TEXT)
orders = shop_export["orders"]
total_kg = sum(order["kg"] for order in orders)
drum_loads = math.ceil(total_kg / DRUM_KG)
print(f"{MONTH}: {total_kg:.1f} kg in {len(orders)} "
f"orders, {drum_loads} drum loads")
month_total = Decimal("0")
for cafe in CAFES:
price = Decimal(cafe["price_per_kg"])
cafe_kg = 0.0
amount = Decimal("0")
for order in orders:
if order["cafe"] == cafe["name"]:
cafe_kg += order["kg"]
amount += price * Decimal(str(order["kg"]))
amount = amount.quantize(CENT, rounding=ROUND_HALF_UP)
month_total += amount
share = cafe_kg / total_kg
rf = rf_reference(cafe["customer"] + INVOICE_MONTH)
print(f"{cafe['name']}: {cafe_kg:.1f} kg ({share:.0%}), "
f"€{amount:,.2f}, {rf}")
for order in orders:
if order["cafe"] == cafe["name"]:
print(f" order {order['id']}: {order['kg']:.1f} kg")
if month_total == Decimal(shop_export["total"]):
print(f"Month total €{month_total:,} matches the web shop")
else:
shop_total = shop_export["total"]
print(f"Check the export: €{month_total:,} here, "
f"€{shop_total} in the shop")
next_id = max(order["id"] for order in orders) + 1
print(f"Next export starts at order {next_id}")