DEV Community

Jing Zhang
Jing Zhang

Posted on

Converting EDI 810 Invoices to Balanced QuickBooks Desktop (.IIF) Files: Handling N2 Implied Decimals & SAC Allowances

Importing an ANSI X12 810 Invoice into QuickBooks Desktop via File -> Utilities -> Import -> IIF Files fails in one notoriously cryptic way: QuickBooks pops up "Transaction is not in balance" and aborts the transaction—often without telling you which split row caused the mismatch or by how many cents.

In wholesale retail EDI integrations (Walmart, Target, Amazon Vendor Central, Lowe's, Costco), that error almost always comes down to two implementation bugs:

  1. Mixing X12 numeric representations with IEEE-754 floats: Line-item quantities and unit prices in IT1 use explicit decimals (R), whereas header totals (TDS01) and promotional allowances or freight charges (SAC05) use implied two-place decimals (N2) with no decimal point at all.
  2. Inverted double-entry signs on SAC splits: QuickBooks .IIF requires every transaction block (TRNS + all SPL lines) to sum to exact zero. While merchandise revenue and freight charges are negative credits, a promotional allowance (SAC*A) reduces Accounts Receivable and must be posted as a positive debit split.

Below is a complete walkthrough of an X12 810 invoice, the integer-cent accounting identities required to reconcile it, and a zero-dependency JavaScript ES module that generates balanced QuickBooks Desktop .IIF files.


1. Anatomy of a Real Retail X12 810 Invoice

Here is a complete, standards-compliant ANSI X12 005010 810 Commercial Invoice. It includes a fixed 106-byte ISA interchange header, two IT1 merchandise lines carrying 12-digit UP UPCs and VN vendor SKUs, a TDS monetary summary, one promotional allowance (SAC*A*D240), and one freight/handling charge (SAC*C*D500):

ISA*00*          *00*          *12*5551234567     *08*925485US00     *261109*1430*^*00501*000041810*0*P*:~
GS*IN*5551234567*925485US00*20261109*1430*41810*X*005010~
ST*810*0001~
BIG*20261109*INV-2026-9042*20261104*PO-8844201***DI~
N1*BY*Walmart Stores Inc*92*0078~
ITD*01*3*****30*****Net 30~
IT1*1*24*EA*18.95*PE*UP*012345678905*VN*SKU-TOWEL-BLU-L~
PID*F****ORGANIC COTTON BATH TOWEL ROYAL BLUE~
IT1*2*30*EA*34.19*PE*UP*012345678912*VN*SKU-ROBE-WHT-XL~
PID*F****LUXURY WAFFLE ROBE WHITE XL~
TDS*146550*148050~
SAC*A*D240***5000**********PROMOTIONAL ALLOWANCE~
SAC*C*D500***3500**********FREIGHT AND HANDLING CHARGE~
CTT*2~
SE*13*0001~
GE*1*41810~
IEA*1*000041810~
Enter fullscreen mode Exit fullscreen mode

Segment & Element Data Type Breakdown

Notice how X12 switches numeric data types (R vs N2 vs N0) inside the same transaction set:

Segment & Element Raw Value X12 Data Type Parsed Meaning Accounting Role
ISA (00..16) ISA*00*...*:~ Fixed 106-byte Element sep * (idx 3), Component : (idx 104), Term ~ (idx 105) Interchange envelope & delimiter source
GS*01 / ST*01 IN / 810 ID Invoice Functional Group / Transaction Set 810 Guards against importing non-invoice files
BIG01 / BIG02 20261109 / INV-2026-9042 DT / AN Invoice Date (11/09/2026) & Invoice Number .IIF DATE and DOCNUM
BIG03 / BIG04 20261104 / PO-8844201 DT / AN Original Purchase Order Date & Buyer PO Number Reference for downstream 820 cash matching
BIG07 DI ID DI = Debit Invoice (CR / CN = Credit Memo) Selects INVOICE vs CREDIT MEMO
N1*01..04 BY*Walmart Stores Inc*92*0078 ID / AN Buying Party Name & Assigned Store/Buyer ID .IIF NAME (Customer Job)
ITD07 / ITD12 30 / Net 30 N0 / AN Net Days (30) & Payment Terms Description .IIF TERMS
IT102 / IT104 (Line 1) 24 / 18.95 R (Explicit) 24 EA × $18.95 = $454.80 (45480 cents) Merchandise credit (SKU-TOWEL-BLU-L)
IT102 / IT104 (Line 2) 30 / 34.19 R (Explicit) 30 EA × $34.19 = $1,025.70 (102570 cents) Merchandise credit (SKU-ROBE-WHT-XL)
TDS01 146550 N2 (Implied) Net Invoice Total = $1,465.50 (146550 cents) .IIF TRNS A/R total
TDS02 148050 N2 (Implied) Gross Merchandise Subject to Discount = $1,480.50 Pre-allowance subtotal (45480 + 102570)
SAC01..05 (SAC*A) A*D240***5000 ID / N2 Promotional Allowance = -$50.00 (5000 cents) Reduces A/R; positive debit SPL
SAC01..05 (SAC*C) C*D500***3500 ID / N2 Freight/Handling Charge = +$35.00 (3500 cents) Increases A/R; negative credit SPL
CTT01 / SE01 2 / 13 N0 2 IT1 line items; 13 segments from ST through SE Structural integrity counters

Two structural details matter when writing a parser:

  • Never hardcode * and ~: Always read the element separator at byte offset 3 of the ISA segment and walk 16 element delimiters to extract ISA16 (component separator) and the segment terminator. Some retail VANs transmit | or \x1c instead of *, or wrap segments at column 80 with \r\n.
  • TDS precedes summary SAC in X12 Table 3: In the official ASC X12 810 specification, TDS sits at Summary position 010 while summary-level SAC segments sit at position 050. You cannot validate TDS01 the moment you encounter TDS; you must finish reading through SE first.

2. Two Root Causes Behind "Transaction is not in balance"

Root Cause 1: Mixed Numeric Types (R vs N2) and IEEE-754 Float Drift

In X12, IT102 (quantity) and IT104 (unit price) are R (decimal numeric) elements—they include a literal decimal point when fractional (18.95, 34.19).

By contrast, TDS01, TDS02, and SAC05 are N2 (implied two-decimal numeric) elements. Decimal points are forbidden by the standard:

  • TDS*146550~ means $1,465.50, not $146,550.00.
  • SAC*A*D240***5000~ means $50.00, not $5,000.00.
  • SAC*C*D500***3500~ means $35.00, not $3,500.00.

If a naive script parses SAC05 or TDS01 with parseFloat() without scaling, totals blow up by 100x. Worse, even if you divide N2 fields by 100, doing invoice math in IEEE-754 floating point introduces silent penny drift. Everyone knows 0.1 + 0.2 === 0.30000000000000004, and Number.parseInt(19.99 * 100, 10) evaluates to 1998 because 19.99 * 100 is 1998.9999999999998.

Run the exact numbers from our sample 810 invoice above in Node.js:

// Line 1: 24 * 18.95 -> 454.79999999999995
// Line 2: 30 * 34.19 -> 1025.6999999999998
const floatNet = 24 * 18.95 + 30 * 34.19 - 50.00 + 35.00;
console.log(floatNet);              // 1465.4999999999998
console.log(floatNet === 1465.50);  // false!
Enter fullscreen mode Exit fullscreen mode

When an invoice has 40 IT1 lines—or fractional four-decimal wholesale unit prices like $12.505 per unit—rounding each line in floating point vs rounding the header can leave a $0.01 gap between TRNS and SPL. QuickBooks Desktop has zero cent tolerance: a $0.01 discrepancy rejects the entire transaction.

The fix: Convert every number into integer cents at the parser boundary (N2 strings parse straight to integer cents; R quantity × unit price scales via BigInt decimal arithmetic), and assert the X12 internal balance before emitting a single line of .IIF:

sum(IT1_cents) + sum(SAC_charge_cents) - sum(SAC_allowance_cents) === TDS01_cents
  (45480 + 102570) + 3500 - 5000 = 148050 + 3500 - 5000 = 146550 cents
Enter fullscreen mode Exit fullscreen mode

Root Cause 2: QuickBooks .IIF Double-Entry Sign Symmetry

An .IIF (Intuit Interchange Format) invoice is a tab-delimited double-entry journal voucher wrapped in TRNS (header), SPL (distribution splits), and ENDTRNS. QuickBooks enforces a strict sign convention for TRNSTYPE = INVOICE:

.IIF Row ACCNT (GL Account) Sign Rule (Standard Invoice) Sample Cents .IIF AMOUNT Why
TRNS Accounts Receivable Positive +(TDS01_cents / 100) +146550 1465.50 Debits A/R for net amount buyer owes
SPL (Line 1) Wholesale Sales Negative -(Line1_cents / 100) -45480 -454.80 Credits revenue (QNTY = -24, PRICE = 18.95)
SPL (Line 2) Wholesale Sales Negative -(Line2_cents / 100) -102570 -1025.70 Credits revenue (QNTY = -30, PRICE = 34.19)
SPL (SAC*A) Sales Discounts Positive +(Allowance_cents / 100) +5000 50.00 Debits contra-revenue (reduces A/R!)
SPL (SAC*C) Freight Income Negative -(Charge_cents / 100) -3500 -35.00 Credits shipping/handling income (increases A/R)
Sum TRNS + Σ(SPL) === 0 0 0.00 Balanced to the exact cent

The single most common mistake in custom .IIF exporters is writing SAC*A allowances as negative numbers because "discounts are negative" or "every SPL row on an invoice is negative." Look at what happens if you write -50.00 instead of 50.00:

  • 1465.50 + (-454.80) + (-1025.70) + (-50.00) + (-35.00) = -100.00 (off by 2 × Allowance).
  • Conversely, if you omit SAC segments altogether and only export IT1 lines against TDS01, the sum is 1465.50 - 1480.50 = -15.00.

Two practical rules save hours of debugging here:

  1. Key sign logic strictly off SAC01 (A vs C), never SAC02: Across retail trading partners, SAC02 service codes get reused inconsistently—one retailer sends D240 for a freight charge (SAC*C*D240), while another uses D240 or F800 with SAC15 text for a promotional allowance (SAC*A*D240), and D500 or G830 for handling/freight. SAC01 (A = Allowance, C = Charge) is the only authoritative sign indicator.
  2. Leave INVITEM, QNTY, and PRICE blank on GL-level SAC splits: Unless you maintain dedicated QuickBooks Service/Discount items in every company file's Item List, leaving INVITEM, QNTY, and PRICE empty on SAC split lines instructs QuickBooks Desktop to post the adjustment directly to the specified ACCNT (Sales Discounts or Freight Income) without throwing missing-item warnings.

3. Zero-Dependency JavaScript Converter (convertEdi810ToQuickBooksIif)

The ES module below runs in Node.js 18+ and modern browsers with zero npm dependencies. It dynamically sniffs ISA delimiters, parses 810 header/detail/summary segments, scales R and N2 amounts into integer cents, validates SE01/CTT01/TDS01, and verifies TRNS + Σ(SPL) === 0 before returning the .IIF string:

/**
 * Parse an X12 N2 implied-decimal element (e.g., "146550" -> 146550 cents).
 * Rejects explicit decimal points to catch non-compliant N2 values at the boundary.
 */
export function parseN2ToCents(raw, fieldName = 'N2') {
  const clean = String(raw ?? '').trim();
  if (!clean) return 0;
  if (!/^-?\d+$/.test(clean)) {
    throw new Error(`Invalid X12 ${fieldName} implied-decimal value: "${raw}"`);
  }
  return Number.parseInt(clean, 10);
}

/**
 * Multiply X12 R-type quantity and unit price into integer cents using exact BigInt
 * decimal scaling, avoiding IEEE-754 floating-point multiplication drift.
 */
export function computeLineCents(qtyRaw, priceRaw) {
  const toScaledBigInt = (val, label) => {
    const clean = String(val ?? '').trim();
    const match = clean.match(/^(-?)(\d+)(?:\.(\d+))?$/);
    if (!match) throw new Error(`Invalid X12 R numeric ${label}: "${val}"`);
    const [, sign, whole, frac = ''] = match;
    const digits = BigInt(whole + frac);
    return { value: sign === '-' ? -digits : digits, decimals: frac.length };
  };

  const q = toScaledBigInt(qtyRaw, 'quantity');
  const p = toScaledBigInt(priceRaw, 'unitPrice');
  const rawProduct = q.value * p.value;
  const extraDecimals = q.decimals + p.decimals - 2; // target scale: 10^2 (cents)

  if (extraDecimals <= 0) {
    return Number(rawProduct * 10n ** BigInt(-extraDecimals));
  }
  const divisor = 10n ** BigInt(extraDecimals);
  const half = divisor / 2n;
  const rounded =
    rawProduct >= 0n
      ? (rawProduct + half) / divisor
      : (rawProduct - half) / divisor;
  return Number(rounded);
}

export function centsToDollars(cents) {
  const sign = cents < 0 ? '-' : '';
  const abs = Math.abs(cents);
  return `${sign}${Math.trunc(abs / 100)}.${String(abs % 100).padStart(2, '0')}`;
}

function formatUnitPrice(rawPrice) {
  const num = Math.abs(Number(rawPrice));
  const fixed2 = num.toFixed(2);
  const fixed4 = num.toFixed(4);
  if (Math.abs(Number(fixed2) - Number(fixed4)) < 1e-6) return fixed2;
  return fixed4.replace(/0+$/, '');
}

function sniffX12Delimiters(rawEdi) {
  const stream = rawEdi.replace(/^\uFEFF/, '').trimStart();
  if (!stream.startsWith('ISA')) {
    throw new Error('Expected X12 interchange starting with an ISA segment.');
  }
  const element = stream[3];
  let cursor = 0;
  let count = 0;
  // Walk the 16 element delimiters of the fixed ISA header, ignoring hard line wraps
  while (cursor < stream.length && count < 16) {
    const ch = stream[cursor++];
    if (ch === '\r' || ch === '\n') continue;
    if (ch === element) count += 1;
  }
  if (count < 16) {
    throw new Error(`Malformed ISA header: expected 16 "${element}" delimiters, found ${count}.`);
  }
  while (cursor < stream.length && (stream[cursor] === '\r' || stream[cursor] === '\n')) {
    cursor += 1;
  }
  const component = stream[cursor++];
  let segment = stream[cursor++] || '~';
  if (segment === '\r') segment = '\n';
  return { stream, element, component, segment };
}

function formatX12DateToUs(yyyymmdd) {
  const clean = String(yyyymmdd ?? '').trim();
  if (!/^\d{8}$/.test(clean)) {
    throw new Error(`Expected 8-digit YYYYMMDD date in BIG01, got "${yyyymmdd}".`);
  }
  return `${clean.slice(4, 6)}/${clean.slice(6, 8)}/${clean.slice(0, 4)}`;
}

function cleanTsvCell(value) {
  return String(value ?? '').replace(/[\t\r\n]+/g, ' ').trim();
}

function resolveLineSku(elements, startIndex = 6, skuCrossRef = {}) {
  const qualifiers = {};
  for (let i = startIndex; i + 1 < elements.length; i += 2) {
    const qual = (elements[i] || '').trim().toUpperCase();
    const code = (elements[i + 1] || '').trim();
    if (qual && code) qualifiers[qual] = code;
  }
  for (const code of Object.values(qualifiers)) {
    if (skuCrossRef[code]) return skuCrossRef[code];
  }
  for (const key of ['VN', 'VP', 'UP', 'EN', 'UK', 'IN', 'BP']) {
    if (qualifiers[key]) return qualifiers[key];
  }
  return 'Wholesale Item';
}

/**
 * Convert an ANSI X12 810 Invoice into a balanced QuickBooks Desktop (.IIF) payload.
 */
export function convertEdi810ToQuickBooksIif(rawEdi, options = {}) {
  const {
    arAccount = 'Accounts Receivable',
    incomeAccount = 'Wholesale Sales',
    discountAccount = 'Sales Discounts',
    freightAccount = 'Freight Income',
    defaultCustomerName = 'Retailer Customer',
    skuCrossRef = {},
  } = options;

  const { stream, element, segment } = sniffX12Delimiters(rawEdi);
  const rawSegments =
    segment === '\n'
      ? stream.split(/\r?\n/).map((s) => s.trim()).filter(Boolean)
      : stream.replace(/[\r\n]+/g, '').split(segment).map((s) => s.trim()).filter(Boolean);

  let stType = '';
  let stSegmentCount = 0;
  let declaredLineCount = null;
  let invoiceDate = '';
  let invoiceNumber = '';
  let poNumber = '';
  let big07Type = 'DI';
  let terms = 'Net 30';
  const parties = {};
  const lineItems = [];
  const sacAdjustments = [];
  let tds01Cents = null;
  let tds02Cents = null;

  for (const segText of rawSegments) {
    const el = segText.split(element);
    const tag = el[0];

    if (tag === 'ST') {
      stType = (el[1] || '').trim();
      if (stType !== '810') {
        throw new Error(`Expected X12 810 Invoice, received ST*${stType}.`);
      }
      stSegmentCount = 1;
      continue;
    }
    if (stSegmentCount > 0) stSegmentCount += 1;

    if (tag === 'BIG') {
      invoiceDate = formatX12DateToUs(el[1]);
      invoiceNumber = (el[2] || '').trim();
      poNumber = (el[4] || '').trim();
      big07Type = (el[7] || 'DI').trim().toUpperCase();
    } else if (tag === 'N1') {
      const role = (el[1] || '').trim();
      if (role) parties[role] = (el[2] || '').trim();
    } else if (tag === 'ITD') {
      const netDays = Number.parseInt(el[7] || '30', 10) || 30;
      terms = (el[12] || '').trim() || `Net ${netDays}`;
    } else if (tag === 'IT1') {
      const qtyRaw = (el[2] || '0').trim();
      const priceRaw = (el[4] || '0').trim();
      lineItems.push({
        lineNumber: el[1] || String(lineItems.length + 1),
        qty: Math.abs(Number(qtyRaw)),
        rawPrice: priceRaw,
        lineCents: Math.abs(computeLineCents(qtyRaw, priceRaw)),
        sku: resolveLineSku(el, 6, skuCrossRef),
        description: '',
      });
    } else if (tag === 'PID' && lineItems.length > 0) {
      const current = lineItems[lineItems.length - 1];
      if (!current.description) {
        current.description = (el[5] || el[4] || '').trim();
      }
    } else if (tag === 'TDS') {
      tds01Cents = parseN2ToCents(el[1], 'TDS01');
      if (el[2]) tds02Cents = parseN2ToCents(el[2], 'TDS02');
    } else if (tag === 'SAC') {
      const indicator = (el[1] || '').trim().toUpperCase();
      if (indicator !== 'A' && indicator !== 'C') continue;
      sacAdjustments.push({
        indicator, // 'A' = Allowance (reduces A/R), 'C' = Charge (increases A/R)
        code: (el[2] || '').trim(),
        amountCents: Math.abs(parseN2ToCents(el[5], 'SAC05')),
        description: (el[15] || '').trim(),
      });
    } else if (tag === 'CTT') {
      if (el[1]) declaredLineCount = Number.parseInt(el[1], 10);
    } else if (tag === 'SE') {
      const declaredSeCount = Number.parseInt(el[1] || '0', 10);
      if (declaredSeCount !== stSegmentCount) {
        throw new Error(`SE01 segment count mismatch: declared ${declaredSeCount}, parsed ${stSegmentCount}.`);
      }
      break;
    }
  }

  if (stType !== '810' || tds01Cents === null) {
    throw new Error('Incomplete EDI 810 payload: missing ST*810 or mandatory TDS segment.');
  }
  if (declaredLineCount !== null && declaredLineCount !== lineItems.length) {
    throw new Error(`CTT01 line count mismatch: declared ${declaredLineCount}, parsed ${lineItems.length}.`);
  }

  // 1. Reconcile X12 internal integer-cent totals BEFORE emitting QuickBooks .IIF rows
  const isCreditMemo = ['CR', 'CN', 'CE', 'CM'].includes(big07Type) || tds01Cents < 0;
  const absTds01Cents = Math.abs(tds01Cents);
  const merchandiseCents = lineItems.reduce((sum, item) => sum + item.lineCents, 0);
  const sacChargeCents = sacAdjustments
    .filter((s) => s.indicator === 'C')
    .reduce((sum, s) => sum + s.amountCents, 0);
  const sacAllowanceCents = sacAdjustments
    .filter((s) => s.indicator === 'A')
    .reduce((sum, s) => sum + s.amountCents, 0);

  const expectedNetCents = merchandiseCents + sacChargeCents - sacAllowanceCents;
  if (expectedNetCents !== absTds01Cents) {
    throw new Error(
      `EDI 810 out of balance: IT1 (${merchandiseCents}c) + SAC*C (${sacChargeCents}c) ` +
        `- SAC*A (${sacAllowanceCents}c) = ${expectedNetCents}c, but TDS01 declared ${absTds01Cents}c.`
    );
  }
  if (absTds01Cents === 0) {
    throw new Error('Zero-dollar ($0.00) EDI 810 invoice blocked from QuickBooks A/R export.');
  }

  const trnsType = isCreditMemo ? 'CREDIT MEMO' : 'INVOICE';
  // Standard INVOICE: signMultiplier = 1 (TRNS is +A/R, revenue SPL is -Sales).
  // CREDIT MEMO: signMultiplier = -1 (inverts TRNS and every SPL row).
  const signMultiplier = isCreditMemo ? -1 : 1;
  const customerName = parties.BT || parties.BY || parties.ST || defaultCustomerName;

  const headerLines = [
    ['!TRNS', 'TRNSTYPE', 'DATE', 'ACCNT', 'NAME', 'DOCNUM', 'AMOUNT', 'TERMS'].join('\t'),
    ['!SPL', 'TRNSTYPE', 'DATE', 'ACCNT', 'NAME', 'AMOUNT', 'INVITEM', 'QNTY', 'PRICE', 'MEMO'].join('\t'),
    '!ENDTRNS',
  ];

  const trnsCents = signMultiplier * absTds01Cents;
  const splRows = [];
  let splSumCents = 0;

  for (const item of lineItems) {
    const splCents = -signMultiplier * item.lineCents;
    const iifQty = -signMultiplier * item.qty;
    splSumCents += splCents;

    splRows.push(
      [
        'SPL',
        trnsType,
        invoiceDate,
        incomeAccount,
        customerName,
        centsToDollars(splCents),
        item.sku,
        String(iifQty),
        formatUnitPrice(item.rawPrice),
        item.description || (poNumber ? `PO #${poNumber}` : ''),
      ]
        .map(cleanTsvCell)
        .join('\t')
    );
  }

  for (const sac of sacAdjustments) {
    // SAC*A (Allowance) reduces A/R -> positive debit SPL on an INVOICE (+amountCents)
    // SAC*C (Charge) increases A/R  -> negative credit SPL on an INVOICE (-amountCents)
    const splCents =
      sac.indicator === 'A'
        ? signMultiplier * sac.amountCents
        : -signMultiplier * sac.amountCents;
    const account = sac.indicator === 'A' ? discountAccount : freightAccount;
    const memo = `SAC*${sac.indicator}*${sac.code}${sac.description ? ` ${sac.description}` : ''}`;
    splSumCents += splCents;

    splRows.push(
      [
        'SPL',
        trnsType,
        invoiceDate,
        account,
        customerName,
        centsToDollars(splCents),
        '',
        '',
        '',
        memo,
      ]
        .map(cleanTsvCell)
        .join('\t')
    );
  }

  // 2. Assert QuickBooks double-entry algebraic identity: TRNS + sum(SPL) === 0 cents
  if (trnsCents + splSumCents !== 0) {
    throw new Error(
      `QuickBooks IIF double-entry imbalance: TRNS (${trnsCents}c) + SPL (${splSumCents}c) !== 0.`
    );
  }

  const trnsRow = [
    'TRNS',
    trnsType,
    invoiceDate,
    arAccount,
    customerName,
    invoiceNumber,
    centsToDollars(trnsCents),
    terms,
  ]
    .map(cleanTsvCell)
    .join('\t');

  return {
    iif: [...headerLines, trnsRow, ...splRows, 'ENDTRNS'].join('\n'),
    summary: {
      invoiceNumber,
      poNumber,
      merchandiseCents,
      tds02Cents,
      sacChargeCents,
      sacAllowanceCents,
      trnsCents,
      splSumCents,
      netBalanceCents: trnsCents + splSumCents,
    },
  };
}
Enter fullscreen mode Exit fullscreen mode

Generated .IIF Output

Running convertEdi810ToQuickBooksIif(sampleEdi810) produces the following tab-delimited .IIF file (fields are separated by literal \t characters):

!TRNS   TRNSTYPE    DATE    ACCNT   NAME    DOCNUM  AMOUNT  TERMS
!SPL    TRNSTYPE    DATE    ACCNT   NAME    AMOUNT  INVITEM QNTY    PRICE   MEMO
!ENDTRNS
TRNS    INVOICE 11/09/2026  Accounts Receivable Walmart Stores Inc  INV-2026-9042   1465.50 Net 30
SPL INVOICE 11/09/2026  Wholesale Sales Walmart Stores Inc  -454.80 SKU-TOWEL-BLU-L -24 18.95   ORGANIC COTTON BATH TOWEL ROYAL BLUE
SPL INVOICE 11/09/2026  Wholesale Sales Walmart Stores Inc  -1025.70    SKU-ROBE-WHT-XL -30 34.19   LUXURY WAFFLE ROBE WHITE XL
SPL INVOICE 11/09/2026  Sales Discounts Walmart Stores Inc  50.00               SAC*A*D240 PROMOTIONAL ALLOWANCE
SPL INVOICE 11/09/2026  Freight Income  Walmart Stores Inc  -35.00              SAC*C*D500 FREIGHT AND HANDLING CHARGE
ENDTRNS
Enter fullscreen mode Exit fullscreen mode

4. Verifying the Ledger Balance & Production Edge Cases

Before importing a batch of .IIF transactions into a live QuickBooks company file (and always back up your .QBW file before running .IIF imports, as QuickBooks Desktop bypasses several UI validation guards during .IIF ingestion), you can audit any generated .IIF file with a 15-line ledger check:

function assertIifZeroBalance(iifContent) {
  const lines = iifContent.trim().split(/\r?\n/);
  const trnsAmountCol = lines[0].split('\t').indexOf('AMOUNT');
  const splAmountCol = lines[1].split('\t').indexOf('AMOUNT');

  let balanceCents = 0;
  for (const line of lines) {
    const cols = line.split('\t');
    if (cols[0] === 'TRNS') {
      balanceCents += computeLineCents('1', cols[trnsAmountCol]);
    } else if (cols[0] === 'SPL') {
      balanceCents += computeLineCents('1', cols[splAmountCol]);
    }
  }
  if (balanceCents !== 0) {
    throw new Error(`IIF out of balance by ${balanceCents} cents`);
  }
  return true;
}
Enter fullscreen mode Exit fullscreen mode

Checking every row of our output confirms exact zero-cent symmetry:

  • TRNS (Accounts Receivable): +146550 cents ($1,465.50)
  • SPL #1 (Wholesale Sales): -45480 cents (-$454.80)
  • SPL #2 (Wholesale Sales): -102570 cents (-$1,025.70)
  • SPL #3 (Sales Discounts, SAC*A*D240): +5000 cents (+$50.00)
  • SPL #4 (Freight Income, SAC*C*D500): -3500 cents (-$35.00)
  • Net Sum: 146550 - 45480 - 102570 + 5000 - 3500 = 0 cents.

Three Production Edge Cases to Watch For

  1. Credit Memos (BIG07 = CR or CN): When issuing or importing a retail credit memo, TRNSTYPE switches from INVOICE to CREDIT MEMO and every sign flips (TRNS becomes negative to reduce A/R, merchandise SPL rows and QNTY become positive to debit sales returns and restock inventory, and SAC*A allowances flip negative). Note that some trading partners transmit positive unsigned numbers alongside BIG07=CR, while others transmit negative quantities—normalizing with Math.abs() before applying signMultiplier prevents double negation.
  2. Blocking $0.00 Shells and Non-Ledger X12 Files: Operational EDI folders frequently mix 810 invoices with 856 ASNs, 997 Functional Acknowledgments, and 824 Application Advice rejections (OTI*TR). Always check ST01 === '810' and reject $0.00 totals so non-financial acknowledgments never pollute Accounts Receivable.
  3. Carrying PONUM and DUEDATE for 820 Cash Application: QuickBooks .IIF headers are column-name driven. If you reconcile retail ACH wire remittances (EDI 820) by buyer PO number, append PONUM and DUEDATE to the !TRNS header row and pass BIG04 (PO-8844201) plus BIG01 + ITD07 days on each TRNS row.

5. Sample Files & Browser-Side Converters

Disclosure: I build EDIParse, the client-side X12 parser and QuickBooks converter linked above. All code in this article is zero-dependency JavaScript and can be used standalone in any project.

Top comments (0)