Parsing Modern and Legacy Shopify Product CSVs with Integer-Cent Math and Formula-Safe Order Forms
A source-level walkthrough of Shopify variant import, integer-cent USD pricing, catalog validation, and buyer-specific PDF and CSV exports.
Download both buyer groups’ sample PDFs and order forms to see the finished files.
Two buyers can receive the same candle SKU at different prices. In the example below, CND-CED-08 costs $10.10 in Group A and $9.09 in Group B, while CND-CED-04 appears only in B. Both rows belong to one Shopify product. The second row has a blank title, which the importer fills from the first row’s product data. The wholesale price, minimum order quantity, and case pack still belong to the individual variant.
URL handle,Title,SKU,Price,Compare-at price,Option1 value,MOQ,Case Pack
cedar-candle,Cedar Candle,CND-CED-08,10.10,22.00,8 oz,12,6
cedar-candle,,CND-CED-04,7.25,16.00,4 oz,6,6
How the importer recognizes two Shopify formats
csv-parser.ts reads the records before interpreting the headers. Its state machine accepts a UTF-8 BOM, doubled quotes inside quoted cells, and CRLF or LF line endings. A newline inside a quoted cell advances the physical line counter without ending the record. A row keeps the line where the record started, so a later validation message can point back to the right place in a spreadsheet export even after a multiline note. The reader measures the input as UTF-8 bytes and allows up to 1 MiB and 1,000 nonblank data records.
Header normalization trims outer whitespace, lowercases the result, and replaces runs of whitespace or hyphens with underscores. Headers that become duplicates after normalization cause csvHeaders. Modern Shopify detection requires the normalized keys for URL handle, SKU, and Price. Legacy detection checks for Variant SKU and Variant Price. In the legacy case, Handle supplies the inheritance key when that header exists. Shopify product CSV reference
const modernShopify =
keys.includes('url_handle') && keys.includes('sku') && keys.includes('price');
const legacyShopify =
keys.includes('variant_sku') && keys.includes('variant_price');
const shopify = modernShopify || legacyShopify;
The wholesale and MSRP alias lists explain what happens to the price columns in each format. The importer picks the first matching alias when the user has no applicable saved mapping. An explicit mapping can choose another header or leave a field unmapped.
wholesale: ['wholesale', 'wholesale_price', 'variant_price', 'price'],
msrp: [
'msrp',
'retail_price',
'variant_compare_at_price',
'compare_at_price',
],
Shopify’s selling price and compare-at price are inputs to the workbench’s wholesale and MSRP fields. They carry whatever amounts the merchant exported. Review the mapping and values before giving a buyer a price. A blank compare-at field remains missing and fails the MSRP check until it has a valid value. Columns for individual Shopify Markets sit outside these automatic aliases.
Where inheritance stops
The handle selects the last product metadata seen for that exact trimmed key. With either URL handle or legacy Handle, a later row with the same handle can reuse a title or category even if another product appeared between those rows. The current row takes precedence when it provides a value.
const handle = cells[handleColumn]?.trim();
const previous = shopify && handle ? products.get(handle) : undefined;
const name = get('name') || previous?.name || '';
const category = get('category') || previous?.category || '';
if (shopify && handle) products.set(handle, { name, category });
The map stores only name and category. The two rows above become Cedar Candle / 8 oz and Cedar Candle / 4 oz because the parser appends Option1 value unless it is blank or exactly Default Title. The SKU, prices, and quantities come from the current row. Shopify rows with an attachment field but no mapped SKU, name, wholesale price, MSRP, or first option are skipped as image continuations. For recognized Shopify files, each absent MOQ or case-pack mapping defaults to one. An empty cell under a mapped quantity column yields null and needs review.
Convert decimal USD text once
Multiplying a floating-point dollar amount by 100 can produce a fractional cent before rounding. For example, 1.005 * 100 evaluates just below 100.5 in JavaScript. This parser accepts up to two decimal places and builds cents directly from the integral and fractional digit groups. It rejects 1.005 at input, and $1,234.5 becomes 123450.
const cents =
Number(match[2].replaceAll(',', '')) * 100 +
Number((match[3] ?? '').padEnd(2, '0'));
return Number.isSafeInteger(cents) && cents <= MAX_CENTS
? match[1] && cents
? -cents
: cents
: null;
The parser uses JavaScript Number for integer amounts. The cap of 100 billion cents also leaves room for multiplying a valid price by a discount factor on the 10,000-point basis without crossing the safe-integer limit. For the normal workbench discount range, the calculation adds half the divisor to the integer numerator and rounds down. An override, if set for the selected group, supplies the price directly.
const override = row.overrides[group];
if (override !== undefined) return override;
if (row.wholesaleCents === null) return null;
const factor = BASIS - groups[group].discountBps;
// Round once, half up, using cents and whole basis points.
return Math.floor((row.wholesaleCents * factor + BASIS / 2) / BASIS);
At 1,000 basis points off, the 1,010-cent candle becomes 909 cents. The 725-cent variant yields 652.5 cents before rounding and becomes 653. Both results stay in cents through comparison and until the exporter formats them. money uses the integer dollar portion and the cents remainder to emit two decimal digits.
Validate catalog rules before either export
validator.ts tallies SKUs with the key produced by sku.trim().normalize('NFC').toLowerCase(). A second row with cnd-ced-08 marks both matching rows as duplicates, regardless of their group membership. The SKU displayed to the buyer comes from the row itself. Validation requires positive safe-integer prices within the cap and quantities in the range 1 to 99,999,999.
if ((counts.get(key) ?? 0) > 1) add('duplicateSku');
if (!validQuantity(row.moq) || !validQuantity(row.casePack)) {
add('quantity');
} else if (row.moq < row.casePack || row.moq % row.casePack !== 0) {
add('caseMismatch');
}
An MOQ of 10 with a case pack of 6 is impossible to fill at the stated minimum using whole cases. An MOQ of 12 works. A wholesale price at or above MSRP is a margin warning. The export gate rejects errors, including an invalid group price, an empty selection, or a catalog exceeding 48 SKUs. It checks general catalog errors across the full draft, including rows outside the selected group. A group-specific error blocks only that group.
Build a separate Letter PDF for each buyer group
compareGroups is the seller’s view and computes the signed difference as B minus A when both prices exist. The artifact generators use a narrower projection. groupRows selects the requested membership and calculates one effective wholesale price per included row.
return rows
.filter((row) => row.membership[group])
.map((row) => ({ ...row, price: groupPrice(row, groups, group) }));
makeLineSheetPdf validates the selected group, creates a fresh PDFDocument with pdf-lib, and uses the projected rows for pagination and table drawing. The page constants are 612 by 792 points, which is US Letter.
if (!canExport(draft.rows, draft.groups, group))
throw new Error('Catalog cannot be exported');
const { PDFDocument, StandardFonts, rgb } = await import('pdf-lib');
const document = await PDFDocument.create({ updateMetadata: false });
For the example, remove the 4 oz candle from A and enter 10% for B’s discount (1,000 basis points). A’s PDF has the 8 oz candle at $10.10. B’s PDF shows that SKU at $9.09 and the 4 oz candle at $6.53. The PDF draws row.price in the wholesale column. Its header identifies the selected group and USD, and shared brand terms and MSRP are rendered from the draft. Order CSVs use the same group projection.
Escape text at the order-form boundary
makeOrderCsv leaves Order Qty blank for the buyer and sends the SKU, product, category, lead time, and notes through textCell. Price and quantity columns come from validated numbers. The CSV writes comma-separated fields with CRLF record endings.
function textCell(value: string) {
const safe = /^\s*[=+\-@=+-@\t\r\n]/u.test(value) ? "'" + value : value;
return '"' + safe.replaceAll('"', '""') + '"';
}
The test checks ASCII formula markers and their full-width counterparts after optional leading whitespace. Tab, carriage return, and line feed are also triggers, including when preceded by spaces. Because the whitespace quantifier can backtrack, a leading control character still matches when the next visible character is ordinary text. A matched cell gets an apostrophe before the original text. Wrapping every text field in double quotes and doubling internal quotes keeps embedded newlines, commas, and quotes inside their field. Spreadsheet save-and-reopen behavior depends on the application and can strip protections. OWASP CSV Injection guidance
Reproduce the buyer split
Import the two synthetic rows, check the mapping, remove the 4 oz candle from A, and enter 10% for B’s discount (1,000 basis points). At $0 you can import, validate, preview up to four SKUs per group, and compare A and B before buying. Try the free workbench
The $9 One-Time Catalog Pass unlocks full PDF and CSV exports for one catalog of up to 48 SKUs, with revisions and re-exports for that project. Pro costs $9/month (or $69/year) and includes up to 12 catalogs per UTC month, saved presets, and comparison against a saved price snapshot. See LineSheetPack pricing