This is Part 3 of the “Restaurant PO Automation” series. Part 1 wired the Gmail Trigger to collect purchase-order emails and PDF attachments; Part 2 used Extract From File plus the Information Extractor to turn PDF text into one structured order object. This post solves the step that makes the workflow useful to a warehouse: turning that object into one row per product line, and normalising the two dates the AI returned in the wrong format. Series guide: Restaurant Purchase Order Automation: Series Guide & Case Study

The final running workflow has five main nodes - Gmail Trigger -> Extract From File -> Information Extractor -> Code -> Google Sheets - with the AI Chat Model attached as a sub-node of the Information Extractor, not counted as a sixth.

Planned five-node workflow from Gmail Trigger through the Code node to Google Sheets

1. Why one PDF must become many rows

The client is a Singapore warehouse operator receiving purchase orders by email from restaurants of the same brand but different outlets. Goods span fresh produce, protein, frozen and dry goods. Each email carries a PDF; the manual job is opening it, reading the PO number and quantities, and typing them into Google Sheets for daily dispatch. The client wants every order, from whichever outlet, recorded automatically and labelled with its outlet or restaurant.

One email does not mean one record: a PO holds several product lines, and a warehouse dispatches products in quantities and units, not a document. An order for 5 vegetables, 3 meats and 2 frozen items should produce 10 rows, not one cell holding ten concatenated products. Without a node emitting one item per line, one PDF becomes one spreadsheet row with everything crammed into that cell - useless for picking and dispatch.

Our four simulated PDFs (PO-20261123-001 through -004, for Orchard, Marina Bay, Jurong East and Tampines) each carry five lines, so the pipeline must land 20 rows in Sheets.

2. What the AI node hands over

The Information Extractor returns one order object with an items array, not rows. Order-level fields are shared by every line; line-level fields come from each item.

{
  "po_number": "PO-20261123-001",
  "order_date": "20 Nov 2026",
  "delivery_date": "23 Nov 2026",
  "brand": "Harbour Kitchen",
  "outlet": "Harbour Kitchen - Orchard",
  "outlet_code": "HK-ORC-01",
  "items": [
    { "sku": "VEG-001", "product": "Fresh Tomatoes", "category": "Produce", "quantity": 20, "unit": "KG" },
    { "sku": "PRO-001", "product": "Boneless Chicken Breast", "category": "Protein", "quantity": 15, "unit": "KG" }
  ]
}

The model may wrap this object in an output property instead of returning top-level JSON, so the read is order.json.output ?? order.json (single-item equivalent: $json.output ?? $json); the fallback handles both shapes. Only one outlet code appears in our notes - HK-ORC-01 for Orchard - so we invent none for the other three; the Code node passes through whatever outlet_code the AI extracted.

3. Code node configuration

We add the Code node after the Information Extractor with two deliberate settings:

SettingValueReason
LanguageJavaScriptNo build step; a plain JS snippet is the smallest thing that can reshape items.
ModeRun Once for All ItemsWe must read all incoming items and emit a different number of output items, which needs the whole input array in scope.

Mode is the important one. “Run Once for Each Item” keeps cardinality at 1:1 and cannot express one order becoming five lines. “Run Once for All Items” gives the script $input.all(), so it can push one item per product line into a rows array and return rows with the count under our control. It loops over orders then po.items - a free robustness benefit, not a feature we tested in the MVP.

4. The full script

This is the exact JavaScript running in the Code node.

const orders = $input.all();
const rows = [];

function normalizeDate(value) {
  if (!value) return "";

  // Already YYYY-MM-DD
  if (/^\d{4}-\d{2}-\d{2}$/.test(value)) {
    return value;
  }

  // Example: 20 Nov 2026
  const months = {
    Jan: "01", Feb: "02", Mar: "03",
    Apr: "04", May: "05", Jun: "06",
    Jul: "07", Aug: "08", Sep: "09",
    Oct: "10", Nov: "11", Dec: "12"
  };

  const match = value.match(
    /^(\d{1,2})\s+([A-Za-z]{3})\s+(\d{4})$/
  );

  if (!match) return value;

  const day = match[1].padStart(2, "0");
  const month = months[match[2]];
  const year = match[3];

  return month ? `${year}-${month}-${day}` : value;
}

for (const order of orders) {
  const po = order.json.output ?? order.json;

  for (const item of po.items ?? []) {
    rows.push({
      json: {
        PO_Number: po.po_number,
        Order_Date: normalizeDate(po.order_date),
        Delivery_Date: normalizeDate(po.delivery_date),
        Brand: po.brand,
        Outlet: po.outlet,
        Outlet_Code: po.outlet_code,
        SKU: item.sku,
        Product: item.product,
        Category: item.category,
        Quantity: item.quantity,
        Unit: item.unit
      }
    });
  }
}

return rows;

The mapping is one-to-one on names and flat on structure:

Output keySourceTransform
PO_Numberpo.po_numbercopied
Order_Date / Delivery_Datepo.order_date / po.delivery_datenormalizeDate
Brand / Outlet / Outlet_Codematching po fieldscopied
SKU / Product / Categorymatching item fieldscopied
Quantity / Unitmatching item fieldscopied, unconverted

po.items ?? [] yields zero rows rather than a thrown error, and each row is wrapped as { json: { ... } }, the shape n8n expects. We do not convert 8 CTN into kilograms or merge quantity and unit into one string: 10 KG, 10 CTN and 10 BAG are completely different orders. Keys named exactly as the spreadsheet header let the Google Sheets node map columns automatically.

5. The date normalisation problem

The AI returned 20 Nov 2026 and 23 Nov 2026 rather than YYYY-MM-DD, even though the instructions asked for that format. Stored as text, a date will not sort chronologically, and a QUERY grouping by delivery date would treat 23 Nov 2026 and 2026-11-23 as two values - a correctness bug.

We fixed it in the Code node instead of touching the already-working AI node: re-prompting risks regressing what is correct, and a deterministic transform is testable whereas “ask the model to behave” is not.

normalizeDate handles four cases:

InputResultLogic
empty / falsy""if (!value) return ""; - never emit null into a cell
2026-11-202026-11-20matches /^\d{4}-\d{2}-\d{2}$/, returned unchanged
20 Nov 20262026-11-20regex match; Nov -> 11 via month map, day padded
unmatched valueunchangedif (!match) return value; and return month ? ... : value

The month map is a plain object, Jan: "01" through Dec: "12", looked up rather than parsed by a date library; padStart(2, "0") pads a single-digit day. Passing unmatched values through is conservative: an unfamiliar format survives into the sheet rather than being silently mis-dated.

6. Reading the output

Executing the step returns 5 items from one PDF: one order object in, five line items out.

Code node output in Schema view showing five items and the field tree

The first view is usually Schema, which renders a field tree rather than a grid - a UI display choice, not a data problem. Clicking Table switches the same five items into one row per item; JSON shows the raw structure. None changes the data.

Code node output in Table view with one row per order line

The five expected rows, with the shared order-level fields repeated on each:

#ProductCategoryQuantityUnit
1Fresh TomatoesProduce20KG
2Romaine LettuceProduce12KG
3Boneless Chicken BreastProtein15KG
4Frozen French FriesFrozen8CTN
5Jasmine RiceDry Goods10BAG

All five share the same PO_Number (PO-20261123-001), Outlet and Delivery_Date, with Order_Date = 2026-11-20 and Delivery_Date = 2026-11-23 on every row.

CheckExpected
Item count5 items, not 1
Order_Date / Delivery_Date2026-11-20 / 2026-11-23 on all rows
Shared fieldsidentical PO number, brand, outlet, outlet code
Line fieldsdistinct SKU, product, category, quantity, unit per row
Quantity + Unitpreserved together, unconverted

If Table shows one item containing an items array, the mode is wrong; if dates still read 20 Nov 2026, normalizeDate was not applied. Both are fixable at this node.

7. What the Code node deliberately does NOT do

We stopped at five nodes. The Code node does not standardise categories, detect duplicates, flag anything for review, keep the original PDF, or write a dispatch status - each is a conscious phase-two decision.

Category standardisation is the most tempting: the reliable SKU prefixes (VEG-, PRO-, FRZ-, DRY-) would support a two-line lookup into Produce / Protein / Frozen / Dry Goods. We chose not to, because the reporting formulas do not use Category - a phase-two candidate with no downstream consumer yet.

Duplicate detection is deliberately absent: production needs a key such as PO Number + Store + line id and a lookup before appending; we simply append. Review flags are absent too, so an unrecognised quantity, outlet or PO number still goes through. Revised POs are not handled - a corrected order is appended as new lines. There is no Airtable, no inventory deduction, no dispatch confirmation emails, and no exception / Needs Review queue.

We repeat this in Part 4: this is a DEMO, not a production warehouse system. A real warehouse needs to keep the original PDF for audit, and human review for unrecognised quantities, outlets or PO numbers before rows reach a dispatch list. Neither is present here. All business data - Harbour Kitchen, its four outlets, PO numbers, SKUs, quantities and dates - is fictional mock data for a Self-initiated Demonstration.

8. Category drift observed on PO 04

The fourth PDF is laid out differently, using labels such as Purchase Order Reference, Outlet Name, Qty and UOM instead of PO Number / Outlet / Quantity / Unit. The AI still extracted the meaning correctly - by meaning, not fixed position - but returned Vegetables and Meat where the first three used Produce and Protein.

That drift is real, but it does not break order capture: SKU, product, quantity and unit are correct. It would matter only if a report grouped by Category, but the QUERY reports driving the daily dispatch and product summary views do not use Category at all - they group by delivery date, outlet, SKU, product and unit. Because the SKU prefixes are stable, a small Code node mapping, marked as phase two, could rewrite the category deterministically without touching the AI schema. The MVP’s correctness rests on dates, outlet, SKU, quantity and unit, and those survived the layout change.

That flat, five-row output has keys matching the spreadsheet header. In Part 4 we design that header, share the workbook, and configure Append Row so these five items become five rows.

Next: Part 4 - Designing the Google Sheets Data Model and Append Row

Data note: all business data in this series is fictional mock data created for a Self-initiated Demonstration. This is a demo, not a production warehouse system, and it is not drawn from any real business.

Related reading