Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Locked learning resources

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Porting the Invoice Script

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: JSON and Math are globals, and whole cents replace decimal. The settings keep their capitals and gain const. 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 an n on 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 from json.loads(), with keepIdText() as its reviver. A plain parse rounds the nineteen-digit order numbers: Larder Lane’s invoice would list the first as 1849327348870116000. 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 reaches 72.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 .length counts the orders.
  • Template literals have no format specs, so the port builds two formatters once: euros, with thousands separators, and percent, whose roundingMode: "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. So toCents() turns each price into whole cents: Number() only reads the text, and Math.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, as quantize() does. The month’s total adds whole cents.
  • Each print() becomes console.log(), its template literals joined by +, because JavaScript doesn’t join side-by-side strings. .toFixed(1) formats the kilos, percent the share, and euros the 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, with toCents() on the shop’s total. Both branches print the total, so the port formats it once, above the if.
  • node --check reads 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:

Language: Python
"""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}")

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

00:00 The bookkeeper runs this Python script on the web shop’s export. It prints fourteen lines: the month’s weight, each café’s invoice and orders, the check against the shop, and where next month’s export starts.

00:14 The dashboard runs on JavaScript, so the script moves there, and one wrong digit means a wrong bill. You’ll port it and compare the first thirteen lines.

00:24 The last one is your exercise.

00:28 The docstring becomes a JSDoc block, and the imports go: JSON and Math are globals, and whole cents replace the decimal module.

00:38 The settings keep their capitals and gain const. 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.

00:54 Python’s rf_reference() becomes a function declaration. Its 17-digit number is past what a JavaScript number holds exactly, so the check works in BigInt, with an n on every literal.

01:06 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 the two-digit format, a zero is added in front of a check below ten.

01:24 JSON.parse() takes over from json.loads(), with keepIdText() as its reviver. A plain parse rounds the nineteen-digit order numbers: Larder Lane’s invoice would list the first ending in zeros.

01:39 The reviver gets the ID’s source text and returns it, so every order number stays exact.

01:46 Python’s sum() compensates for float error, but a += loop in kilos doesn’t, in either language: the month’s line would say seven drum loads instead of six.

01:58 So the port adds whole grams. The drum loads divide by the drum’s grams, and Math.ceil() rounds up: six. Kilos come back only for the output line, and .length counts the orders.

02:15 Template literals have no format specs, so the port builds two formatters once. euros formats euros with thousands separators. percent gives whole percents, and its rounding mode rounds a half to even, as Python’s spec does.

02:32 Without it, Bluebell’s invoice would show its exact twelve and a half percent as thirteen.

02:40 JavaScript has no decimal type, and Number() in its place leaves the month’s total a fraction of a cent off: the check fails. So toCents() turns each price into whole cents: Number() only reads the text, and Math.round() drops its float error.

02:58 Over the café’s orders, the port adds the grams. 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.

03:11 One Math.round(), after dividing by a thousand, rounds a half up, as quantize() does.

03:19 The share divides the café’s grams by the month’s. Each print() becomes console.log(), its template literals joined by +: JavaScript doesn’t join side-by-side strings.

03:32 .toFixed(1) formats the kilos, percent the share, and euros the amount, back from cents, with its own euro sign. The order lines print each order number as the text the reviver kept.

03:47 On whole cents, === replaces Python’s == on Decimals, with toCents() on the shop’s total. Both branches print the total, so the port formats it once, above the if statement.

04:01 The last line stays in Python: it’s your exercise.

04:07 node --check reads the file without running it and prints nothing: no syntax errors. Python prints its fourteen lines. With the port’s five checkpoints in view: which of its thirteen lines, if any, will differ from Python’s?

04:25 Your turn: pause the video and predict.

04:33 None of them. Weights, shares, amounts, references, order numbers and the check all match. A whole script ports line by line: keep each line’s logic, and change only what JavaScript does differently.

04:51 Here, that’s grams and cents, order numbers as text, BigInt check digits, and formatters that round like Python. Next up: the exercise Finish the Invoice Script.

05:04 You’ll add the last line, so both scripts print the same fourteen lines, for October and for one more month.

Become a Member to join the conversation.