From 6e1efe7960aee752a31736cb6c6678528979841e Mon Sep 17 00:00:00 2001 From: Aaron Filson Date: Sat, 28 Nov 2026 15:19:04 -0800 Subject: [PATCH] Add category, dimensions, and weight, plus seo improvements. --- README.md | 13 ++- backend/src/catalog.mjs | 14 ++- backend/src/piece-page.mjs | 161 ++++++++++++++++++++++++------ backend/test/shop-pages.test.mjs | 85 ++++++++++++---- docs/seo-plan.md | 4 +- e2e/fixtures/pieces.json | 1 + e2e/piece-page.spec.mjs | 9 +- scripts/load-items.mjs | 44 ++++++-- scripts/ship-weight-attribute.mjs | 72 ++++++++++--- scripts/update-items.mjs | 84 ++++++++++++++-- 10 files changed, 395 insertions(+), 92 deletions(-) diff --git a/README.md b/README.md index 9a01b97..1f2a224 100644 --- a/README.md +++ b/README.md @@ -58,11 +58,18 @@ The build: ## Selling -Products come straight from your Square catalog. Add items in Square Dashboard > Items & services, with a price and a photo. They appear on the shop within a minute. Shop prices and tax are always calculated by Square on the server. +Products come straight from your Square catalog. Every product upload—in Square Dashboard > Items & services or via `scripts/load-items.mjs`—must include: +- **Price** and **photo(s)** (first photo upright/vertical as the primary thumbnail) +- **Category** (e.g. `Bowls`, `Plates & dishes`, `Vases`, `Mugs`, `Sets`; `/p/` maps this automatically to both your shop `product_type` and Google's official `CategoryCode` taxonomy) +- **Dimensions on line 1 of Description** (`size` in batch JSON, e.g. `"9½″ × 3¾″"` for round pieces or `"14″ × 9″ × 1½″"` for oblong slabs; parsed into `depth` / `width` / `height` in inches for Google Merchant Center) +- **Item weight (lb)** custom attribute (`item_lb` in Square, `itemLb` or `itemOz` in batch JSON): the unpacked scale weight of the piece itself, emitted as `Product.weight` (`product_weight` in Google) +- **Ship weight (lb)** custom attribute (`ship_lb` in Square, `shipLb` in batch JSON): the billed weight of the packed double-boxed parcel, used by checkout and emitted as `OfferShippingDetails.weight` (`shipping_weight` in Google) -**Naming & descriptions for search:** Square item names become `/p/` `

` headings and `` tags, and the first line of the Square description becomes the spec line and search snippet. Favor specific, plain-language names (e.g. `"Celadon porcelain mug, 12 oz"` or `"Soda-fired stoneware vase"`) and put clay body, glaze, and dimensions on line 1 (`"Cone 10 stoneware · Tacoma crackle 26 · 9½″ × 3¾″"`). Batch files for `scripts/load-items.mjs` accept optional `clay`, `glaze`, and `description` fields at both the batch and item level. +Items appear on the shop within a minute. Shop prices and tax are always calculated by Square on the server. -**Shipping** is priced per piece, from the delivery ZIP: one double-boxed parcel per piece, at the published label price for its billed weight and zone from Tacoma, rounded up to whole dollars (`backend/src/shipping.mjs`). UPS Ground carries everything it can; USPS Ground Advantage takes PO boxes, military addresses, Alaska, Hawaii and the territories. Each item needs a **Ship weight (lb)** custom attribute in Square: the billed weight of the packed box (the larger of actual and dimensional weight, from the pack-and-ship planner). An item without one can be picked up but not shipped. Rates and zones live in `backend/src/shipping-rates.json`; update it when UPS or USPS change prices (USPS holiday prices end 2027-01-17; the UPS fuel surcharge changes weekly). +**Naming & descriptions for search:** Square item names become `/p/<id>` `<h1>` headings and `<title>` tags, and the first line of the Square description becomes the spec line and search snippet. Favor specific, plain-language names (e.g. `"Celadon porcelain mug, 12 oz"` or `"Soda-fired stoneware vase"`) and put clay body, glaze, and dimensions on line 1 (`"Cone 10 stoneware · Tacoma crackle 26 · 9½″ × 3¾″"`). Batch files for `scripts/load-items.mjs` and `scripts/update-items.mjs` accept `clay`, `glaze`, `size`, `description`, `category`, `itemLb` (or `itemOz`), and `shipLb`. + +**Shipping (both item weight and shipping weight required on every upload):** Shipping is priced per piece from the delivery ZIP: one double-boxed parcel per piece, at the published label price for its **Ship weight (lb)** and zone from Tacoma, rounded up to whole dollars (`backend/src/shipping.mjs`). Both shop checkout and Google Merchant Center's weight-based shipping table require **Ship weight (lb)** (`ship_lb`), while Google Merchant Center's product spec separately uses **Item weight (lb)** (`item_lb`); an item without `Ship weight (lb)` is pickup only. Run `node scripts/ship-weight-attribute.mjs` (or `load-items.mjs` / `update-items.mjs`) once per Square account to create both custom attributes. UPS Ground carries everything it can; USPS Ground Advantage takes PO boxes, military addresses, Alaska, Hawaii and the territories. Rates and zones live in `backend/src/shipping-rates.json`; update it when UPS or USPS change prices (USPS holiday prices end 2027-01-17; the UPS fuel surcharge changes weekly). ## Email signup diff --git a/backend/src/catalog.mjs b/backend/src/catalog.mjs index fd93f0f..9981fed 100644 --- a/backend/src/catalog.mjs +++ b/backend/src/catalog.mjs @@ -2,11 +2,13 @@ import { SQUARE_LOCATION_ID, square, onSquareReset } from "./config.mjs"; import { applyRecentSales, stockOf, soldLines } from "./stock.mjs"; -// Billed shipping weight in lb of one packed piece: a catalog custom attribute on the item, set when -// the piece is listed (see README.md, "Selling"). A piece without one can't be shipped, only picked up. +// Packed shipping weight (ship_lb) and unpacked item scale weight (item_lb), stored as Square +// custom attributes on each item (see scripts/ship-weight-attribute.mjs and README.md, "Selling"). +// A piece without ship_lb can't be shipped, only picked up; item_lb feeds Product.weight for Google. export const SHIP_LB_KEY = "ship_lb"; -const shipLbOf = (item) => { - const v = Object.values(item.customAttributeValues ?? {}).find((x) => x?.key === SHIP_LB_KEY); +export const ITEM_LB_KEY = "item_lb"; +const numberAttr = (item, key) => { + const v = Object.values(item.customAttributeValues ?? {}).find((x) => x?.key === key); const lb = Number(v?.numberValue); return lb > 0 ? lb : null; }; @@ -48,7 +50,8 @@ export async function loadCatalog() { .filter((o) => o.type === "ITEM" && !o.isDeleted && o.itemData?.productType !== "APPOINTMENTS_SERVICE") .filter((o) => !o.itemData.isArchived) .map((o) => { - const shipLb = shipLbOf(o); + const shipLb = numberAttr(o, SHIP_LB_KEY); + const itemLb = numberAttr(o, ITEM_LB_KEY); return { id: o.id, name: o.itemData.name, @@ -57,6 +60,7 @@ export async function loadCatalog() { images: (o.itemData.imageIds ?? []).map((id) => images.get(id)).filter(Boolean), // in the order set in Square category: categoryOf(o.itemData), ...(shipLb ? { shipLb } : {}), + ...(itemLb ? { itemLb } : {}), updatedAt: o.updatedAt ?? null, // the pieces' sitemap (piece-page.mjs) variations: (o.itemData.variations ?? []) .filter((v) => v.itemVariationData?.priceMoney) diff --git a/backend/src/piece-page.mjs b/backend/src/piece-page.mjs index 2249fa5..bf8e8fc 100644 --- a/backend/src/piece-page.mjs +++ b/backend/src/piece-page.mjs @@ -82,41 +82,135 @@ function picture(url, { alt, sizes, widths, eager }) { const FRACTIONS = { "¼": 0.25, "½": 0.5, "¾": 0.75, "⅛": 0.125, "⅜": 0.375, "⅝": 0.625, "⅞": 0.875 }; const toInches = (whole, dec, frac) => (dec ? Number(`${whole}.${dec}`) : Number(whole) + (FRACTIONS[frac] ?? 0)); const qvIn = (n) => ({ "@type": "QuantitativeValue", value: +n.toFixed(3), unitCode: "INH" }); +const qvLb = (n) => ({ "@type": "QuantitativeValue", value: +Number(n).toFixed(2), unitCode: "LBR" }); -/** Parses dimensions (e.g. "9½″ × 3¾″" or "5½″ wide × 3″ tall") from a piece's spec line, in inches. */ +export const GOOGLE_TAXONOMY = "https://www.google.com/basepages/producttype/taxonomy-with-ids.en-US.txt"; + +/** Maps a studio piece to Google's official Product Taxonomy (ID + full path) for Merchant Center. */ +export function googleCategoryFor(item) { + if (item.googleCategory?.codeValue && item.googleCategory?.name) return item.googleCategory; + const cat = String(item.category ?? "").trim(); + const name = String(item.name ?? "").trim(); + const desc = String(item.description ?? ""); + if (/\bcoasters?\b/i.test(name) || /^coasters$/i.test(cat)) + return { codeValue: "2363", name: "Home & Garden > Kitchen & Dining > Barware > Coasters" }; + if (/^vases$/i.test(cat) || /\bvases?\b/i.test(name)) return { codeValue: "602", name: "Home & Garden > Decor > Vases" }; + if (/^planters$/i.test(cat) || /\b(planters?|flower\s*pots?)\b/i.test(name)) + return { codeValue: "721", name: "Home & Garden > Lawn & Garden > Gardening > Pots & Planters" }; + if (/^(mugs|cups|drinkware)$/i.test(cat) || /\b(mugs?|cups?|tumblers?|yunomi|chawan)\b/i.test(name)) + return { codeValue: "2169", name: "Home & Garden > Kitchen & Dining > Tableware > Drinkware > Mugs" }; + if (/\b(pitchers?|creamers?|carafes?|ewers?)\b/i.test(name) || /^pitchers$/i.test(cat)) + return { codeValue: "3330", name: "Home & Garden > Kitchen & Dining > Tableware > Serveware > Serving Pitchers & Carafes" }; + if (/\b(platters?|trays?)\b/i.test(name) || /^platters$/i.test(cat)) + return { codeValue: "3802", name: "Home & Garden > Kitchen & Dining > Tableware > Serveware > Serving Platters" }; + if (/^plates/i.test(cat) || /\b(plates?|dishes?|saucers?)\b/i.test(name)) + return { codeValue: "3553", name: "Home & Garden > Kitchen & Dining > Tableware > Dinnerware > Plates" }; + if (/^bowls$/i.test(cat) || /\bbowls?\b/i.test(name)) { + return /\b(raku|decorative\s+only|not\s+food\s+safe)\b/i.test(desc) + ? { codeValue: "6457", name: "Home & Garden > Decor > Decorative Bowls" } + : { codeValue: "3498", name: "Home & Garden > Kitchen & Dining > Tableware > Dinnerware > Bowls" }; + } + if (/^sets$/i.test(cat)) + return { codeValue: "5537", name: "Home & Garden > Kitchen & Dining > Tableware > Dinnerware > Dinnerware Sets" }; + return { codeValue: "11", name: "Home & Garden > Decor > Artwork > Sculptures & Statues" }; +} + +function parseInchToken(raw) { + const s = raw.trim(); + if (!s || s.length > 32) return null; + const m = s.match( + /^(\d{1,2})(?:\.(\d{1,2})|\s*([¼½¾⅛⅜⅝⅞]))?\s*(?:[″"]|\bin(?:ches)?\b)?\s*(long|length|deep|depth|wide|width|across|diameter|tall|high|height)?$/i, + ); + if (!m) return null; + const n = toInches(m[1], m[2], m[3]); + return n > 0 ? { n, label: (m[4] ?? "").toLowerCase() } : null; +} + +const axisOf = (label) => { + if (label === "long" || label === "length" || label === "deep" || label === "depth") return "depth"; + if (label === "wide" || label === "width" || label === "across" || label === "diameter") return "width"; + if (label === "tall" || label === "high" || label === "height") return "height"; + return ""; +}; + +/** + * Parses 3D product dimensions ({ depth, width, height } in inches; Schema.org depth = Google product_length) + * from explicit item.dimensions or the piece's spec line (e.g. "9½″ × 3¾″", "14″ × 9″ × 1½″", + * "7¼″, 7¾″ and 8″ × 4½″, set of 3", or "5½″ across, set of 3"). + */ export function parseDimensions(item) { + const explicit = item.dimensions; + const base = {}; + if (explicit && typeof explicit === "object") { + const d = Number(explicit.depth ?? explicit.length); + const w = Number(explicit.width); + const h = Number(explicit.height); + if (d > 0) base.depth = d; + if (w > 0) base.width = w; + if (h > 0) base.height = h; + if (base.depth && base.width && base.height) return base; + } const spec = specLine(item.description); - if (!spec) return {}; + if (!spec) return base; for (const raw of spec.split("·")) { - const seg = raw.trim(); - if (!seg || seg.length > 60 || /,|\band\b|\bset\b/i.test(seg)) continue; - const pair = seg.match( - /^(\d{1,2})(?:\.(\d{1,2})|([¼½¾⅛⅜⅝⅞]))?\s*[″"]\s*(wide|across|tall|high)?\s*[×x]\s*(\d{1,2})(?:\.(\d{1,2})|([¼½¾⅛⅜⅝⅞]))?\s*[″"]\s*(wide|across|tall|high)?$/i, - ); - if (pair) { - const a = toInches(pair[1], pair[2], pair[3]); - const la = (pair[4] ?? "").toLowerCase(); - const b = toInches(pair[5], pair[6], pair[7]); - const lb = (pair[8] ?? "").toLowerCase(); - if (!(a > 0 && b > 0)) return {}; - const tallFirst = - la === "tall" || - la === "high" || - lb === "wide" || - lb === "across" || - (!la && !lb && (item.category === "Vases" || /\b(vase|bottle|pitcher|ewer|cylinder|tower)\b/i.test(item.name ?? ""))); - return tallFirst ? { height: a, width: b } : { width: a, height: b }; + const seg = raw + .trim() + .replace(/(?:,|\s)\s*\(?set of \d+\)?$/i, "") + .trim(); + if (!seg || seg.length > 80 || !/[″"]|\bin(?:ches)?\b/i.test(seg) || /\b(oz|ml|lb|kg|cone)\b/i.test(seg)) continue; + const parts = seg.split(/\s*[×x]\s*/); + if (parts.length === 3) { + const toks = parts.map(parseInchToken); + if (toks.every(Boolean)) { + /** @type {{ depth?: number, width?: number, height?: number }} */ + const out = {}; + const rest = []; + for (const t of toks) { + const ax = axisOf(t.label); + if (ax === "depth" && !out.depth) out.depth = t.n; + else if (ax === "width" && !out.width) out.width = t.n; + else if (ax === "height" && !out.height) out.height = t.n; + else rest.push(t.n); + } + if (!out.depth && rest.length) out.depth = rest.shift(); + if (!out.width && rest.length) out.width = rest.shift(); + if (!out.height && rest.length) out.height = rest.shift(); + return { ...out, ...base }; + } + } + if (parts.length === 2) { + const a = parseInchToken(parts[0]); + const b = parseInchToken(parts[1]); + if (a && b) { + const axA = axisOf(a.label); + const axB = axisOf(b.label); + if (axA === "depth" && axB === "width") return { depth: a.n, width: b.n, ...base }; + if (axA === "width" && axB === "depth") return { width: a.n, depth: b.n, ...base }; + const tallFirst = + axA === "height" || + axB === "width" || + (!axA && !axB && (item.category === "Vases" || /\b(vase|bottle|pitcher|ewer|cylinder|tower)\b/i.test(item.name ?? ""))); + const [diam, height] = tallFirst ? [b.n, a.n] : [a.n, b.n]; + return { depth: diam, width: diam, height, ...base }; + } + // Nested / multi-piece sets such as "7¼″, 7¾″ and 8″ × 4½″": largest outer diameter × height. + const list = parts[0].split(/\s*,\s*|\s+and\s+/i).map(parseInchToken); + if (list.length > 1 && list.every(Boolean) && b) { + const diam = Math.max(...list.map((t) => t.n)); + return { depth: diam, width: diam, height: b.n, ...base }; + } } - const single = seg.match(/^(\d{1,2})(?:\.(\d{1,2})|([¼½¾⅛⅜⅝⅞]))?\s*[″"]\s*(wide|across)$/i); - if (single) { - const w = toInches(single[1], single[2], single[3]); - return w > 0 ? { width: w } : {}; + if (parts.length === 1) { + const single = parseInchToken(parts[0]); + if (single && (!single.label || axisOf(single.label) === "width")) { + return { depth: single.n, width: single.n, ...base }; + } } } - return {}; + return base; } -/** OfferShippingDetails for one parcel (WA Zone 3 + US Zone 8 ceiling), or doesNotShip when pickup-only. */ +/** OfferShippingDetails for one parcel (WA Zone 3 + US Zone 8 ceiling + packed weight), or doesNotShip when pickup-only. */ function shippingDetailsFor(shipLb) { if (!(shipLb > 0)) { return { @@ -134,9 +228,11 @@ function shippingDetailsFor(shipLb) { const us = maxForZone(8); if (wa === null || us === null) return null; const handlingTime = { "@type": "QuantitativeValue", minValue: 1, maxValue: 2, unitCode: "DAY" }; + const weight = qvLb(shipLb); return [ { "@type": "OfferShippingDetails", + weight, shippingRate: { "@type": "MonetaryAmount", value: wa.toFixed(2), currency: "USD" }, shippingDestination: { "@type": "DefinedRegion", addressCountry: "US", addressRegion: "WA" }, deliveryTime: { @@ -147,6 +243,7 @@ function shippingDetailsFor(shipLb) { }, { "@type": "OfferShippingDetails", + weight, shippingRate: { "@type": "MonetaryAmount", value: us.toFixed(2), currency: "USD" }, shippingDestination: { "@type": "DefinedRegion", addressCountry: "US" }, deliveryTime: { @@ -163,6 +260,13 @@ export function structuredData(item, site) { const url = `${site}/p/${item.id}`; const many = item.variations.length > 1; const dims = parseDimensions(item); + const gpc = googleCategoryFor(item); + const categoryCode = { + "@type": "CategoryCode", + name: gpc.name, + codeValue: gpc.codeValue, + inCodeSet: GOOGLE_TAXONOMY, + }; const delivery = item.shipLb > 0 ? ["https://schema.org/OnSitePickup", "https://schema.org/ParcelService"] : ["https://schema.org/OnSitePickup"]; const shippingDetails = shippingDetailsFor(item.shipLb); @@ -183,12 +287,13 @@ export function structuredData(item, site) { url, sku: item.id, image: photosOf(item).map((p) => site + sized(p, 1200, "jpeg")), - ...(item.category ? { category: item.category } : {}), + category: item.category ? [item.category, categoryCode] : categoryCode, material: materialOf(item), countryOfOrigin: "US", + ...(dims.depth ? { depth: qvIn(dims.depth) } : {}), ...(dims.width ? { width: qvIn(dims.width) } : {}), ...(dims.height ? { height: qvIn(dims.height) } : {}), - ...(item.shipLb > 0 ? { weight: { "@type": "QuantitativeValue", value: item.shipLb, unitCode: "LBR" } } : {}), + ...(item.itemLb > 0 ? { weight: qvLb(item.itemLb) } : {}), creator: { "@type": "Person", "@id": `${site}/about.html#aaron`, name: "Aaron Filson" }, brand: { "@type": "Brand", name: SITE_NAME }, offers: item.variations.map((v) => ({ diff --git a/backend/test/shop-pages.test.mjs b/backend/test/shop-pages.test.mjs index a5b44a1..83d357e 100644 --- a/backend/test/shop-pages.test.mjs +++ b/backend/test/shop-pages.test.mjs @@ -5,7 +5,7 @@ import { handler, _setSquare } from "../src/handler.mjs"; import sharp from "sharp"; import { parseRequest, handler as images, _resetCatalog, _catalogWaits } from "../src/images.mjs"; import { _resetShell } from "../src/piece.mjs"; -import { renderPiece, structuredData, pieceTitle, parseDimensions } from "../src/piece-page.mjs"; +import { renderPiece, structuredData, pieceTitle, parseDimensions, googleCategoryFor, GOOGLE_TAXONOMY } from "../src/piece-page.mjs"; const SQUARE_PHOTO = "https://items-images-sandbox.s3.us-west-2.amazonaws.com/files/abc/original.jpeg"; @@ -116,7 +116,16 @@ const iter = (arr) => ({ yield* arr; }, }); -function fakeCatalog({ name = "Celadon bowl", description = "Cone 10 porcelain · celadon\nThrown in Tacoma.", shipLb = 14 } = {}) { +function fakeCatalog({ + name = "Celadon bowl", + description = "Cone 10 porcelain · celadon · 8″ × 3½″\nThrown in Tacoma.", + shipLb = 14, + itemLb = 2.25, +} = {}) { + const customAttributeValues = { + ...(shipLb ? { ship_lb: { key: "ship_lb", numberValue: String(shipLb) } } : {}), + ...(itemLb ? { item_lb: { key: "item_lb", numberValue: String(itemLb) } } : {}), + }; return { catalog: { list: async () => @@ -128,7 +137,7 @@ function fakeCatalog({ name = "Celadon bowl", description = "Cone 10 porcelain type: "ITEM", id: "I1", updatedAt: "2026-10-15T18:04:00.000Z", - ...(shipLb ? { customAttributeValues: { ship_lb: { key: "ship_lb", numberValue: String(shipLb) } } } : {}), + ...(Object.keys(customAttributeValues).length ? { customAttributeValues } : {}), itemData: { name, description, @@ -146,7 +155,7 @@ function fakeCatalog({ name = "Celadon bowl", description = "Cone 10 porcelain } const get = (path) => handler({ requestContext: { http: { method: "GET" } }, rawPath: path }); -test("the catalog lists every photo, in order, the piece's type and its shipping weight", async () => { +test("the catalog lists every photo, in order, the piece's type and its item and shipping weights", async () => { _setSquare(fakeCatalog()); const res = await get("/api/catalog"); assert.equal(res.headers["x-robots-tag"], "noindex"); @@ -155,6 +164,7 @@ test("the catalog lists every photo, in order, the piece's type and its shipping assert.deepEqual(items[0].images, [SQUARE_PHOTO, SQUARE_PHOTO.replace("abc", "def")]); assert.equal(items[0].category, "Bowls"); assert.equal(items[0].shipLb, 14); + assert.equal(items[0].itemLb, 2.25); }); // The JSON-LD block of a page. @@ -166,18 +176,18 @@ test("a piece's page has its name, price, photos, words and product data, and no assert.equal(res.statusCode, 200); assert.match(res.headers["content-type"], /text\/html/); assert.match(res.body, /<h1>Celadon bowl<\/h1>/); - assert.match(res.body, /<p class="piece-spec">Cone 10 porcelain · celadon<\/p>/); + assert.match(res.body, /<p class="piece-spec">Cone 10 porcelain · celadon · 8″ × 3½″<\/p>/); assert.match(res.body, /<p>Thrown in Tacoma\.<\/p>/); assert.match(res.body, /<p class="price">\$65\.00<\/p>/); assert.match(res.body, /<a class="btn" href="\/shop\.html#p-I1">Buy in the shop<\/a>/, "works without the script"); - assert.match(res.body, /alt="Celadon bowl — Cone 10 porcelain · celadon"/); + assert.match(res.body, /alt="Celadon bowl — Cone 10 porcelain · celadon · 8″ × 3½″"/); assert.match(res.body, /alt="Celadon bowl, photo 2"/); assert.match(res.body, /<meta property="og:title" content="Celadon bowl · \$65\.00">/); - assert.match(res.body, /<meta property="og:description" content="Cone 10 porcelain · celadon">/); - assert.match(res.body, /<meta property="og:image:alt" content="Celadon bowl — Cone 10 porcelain · celadon">/); + assert.match(res.body, /<meta property="og:description" content="Cone 10 porcelain · celadon · 8″ × 3½″">/); + assert.match(res.body, /<meta property="og:image:alt" content="Celadon bowl — Cone 10 porcelain · celadon · 8″ × 3½″">/); assert.match( res.body, - /<meta name="description" content="Cone 10 porcelain · celadon\. Handmade in Tacoma by Updraft Pottery Studio\.">/, + /<meta name="description" content="Cone 10 porcelain · celadon · 8″ × 3½″\. Handmade in Tacoma by Updraft Pottery Studio\.">/, ); assert.match(res.body, /<meta property="product:price:amount" content="65\.00">/); assert.match(res.body, /<link rel="canonical" href="\/p\/I1">/); @@ -189,17 +199,29 @@ test("a piece's page has its name, price, photos, words and product data, and no assert.ok(!res.body.includes("p.js"), "no redirect to the shop any more"); const [product, crumbs] = ld(res.body)["@graph"]; assert.equal(product["@type"], "Product"); + assert.deepEqual(product.category, [ + "Bowls", + { + "@type": "CategoryCode", + name: "Home & Garden > Kitchen & Dining > Tableware > Dinnerware > Bowls", + codeValue: "3498", + inCodeSet: GOOGLE_TAXONOMY, + }, + ]); assert.equal(product.material, "Porcelain"); assert.equal(product.countryOfOrigin, "US"); - assert.deepEqual(product.weight, { "@type": "QuantitativeValue", value: 14, unitCode: "LBR" }); + assert.deepEqual(product.depth, { "@type": "QuantitativeValue", value: 8, unitCode: "INH" }); + assert.deepEqual(product.width, { "@type": "QuantitativeValue", value: 8, unitCode: "INH" }); + assert.deepEqual(product.height, { "@type": "QuantitativeValue", value: 3.5, unitCode: "INH" }); + assert.deepEqual(product.weight, { "@type": "QuantitativeValue", value: 2.25, unitCode: "LBR" }); assert.equal(product.offers[0].price, "65.00"); assert.equal(product.offers[0].availability, "https://schema.org/InStock"); assert.deepEqual(product.offers[0].availableDeliveryMethod, ["https://schema.org/OnSitePickup", "https://schema.org/ParcelService"]); assert.deepEqual( - product.offers[0].shippingDetails.map((s) => [s.shippingDestination.addressRegion ?? "US", s.shippingRate.value]), + product.offers[0].shippingDetails.map((s) => [s.shippingDestination.addressRegion ?? "US", s.shippingRate.value, s.weight.value]), [ - ["WA", "33.00"], - ["US", "52.00"], + ["WA", "33.00", 14], + ["US", "52.00", 14], ], ); assert.equal(product.image.length, 2); @@ -212,24 +234,53 @@ test("a piece's page has its name, price, photos, words and product data, and no assert.deepEqual(data.variations, [{ id: "V1", name: "R", price: 6500, currency: "USD", stock: 1 }]); }); -test("dimensions and pickup-only shipping details are derived cleanly from piece metadata", () => { +test("3D dimensions, Google categories, and separate item vs shipping weights are derived cleanly", () => { assert.deepEqual(parseDimensions({ name: "Lantern bowl", category: "Bowls", description: "Crackle · 9½″ × 3¾″" }), { + depth: 9.5, width: 9.5, height: 3.75, }); assert.deepEqual(parseDimensions({ name: "Tall flared lantern vase", category: "Vases", description: "Crackle · 11¾″ × 6½″" }), { - height: 11.75, + depth: 6.5, width: 6.5, + height: 11.75, + }); + assert.deepEqual(parseDimensions({ name: "Bowl", description: "Cone 10 · 5½″ wide × 3″ tall" }), { + depth: 5.5, + width: 5.5, + height: 3, }); - assert.deepEqual(parseDimensions({ name: "Bowl", description: "Cone 10 · 5½″ wide × 3″ tall" }), { width: 5.5, height: 3 }); - assert.deepEqual(parseDimensions({ name: "Nested bowls", description: "7¼″, 7¾″ and 8″ × 4½″, set of 3" }), {}); + assert.deepEqual(parseDimensions({ name: "Nested bowls", description: "7¼″, 7¾″ and 8″ × 4½″, set of 3" }), { + depth: 8, + width: 8, + height: 4.5, + }); + assert.deepEqual(parseDimensions({ name: "Coasters", description: "Porcelain · 5½″ across, set of 3" }), { + depth: 5.5, + width: 5.5, + }); + assert.deepEqual(parseDimensions({ name: "Slab platter", description: "Stoneware · 14″ × 9″ × 1½″" }), { + depth: 14, + width: 9, + height: 1.5, + }); + assert.deepEqual(parseDimensions({ name: "Mug", description: "Cone 6 stoneware · holds 12 oz" }), {}); + + assert.equal(googleCategoryFor({ name: '"T O P" coasters, set of 3', category: "Sets" }).codeValue, "2363"); + assert.equal(googleCategoryFor({ name: "Nested lantern bowls, set of 3", category: "Sets" }).codeValue, "3498"); + assert.equal(googleCategoryFor({ name: "Tall flared lantern vase", category: "Vases" }).codeValue, "602"); + assert.equal(googleCategoryFor({ name: "Scalloped lantern dish", category: "Plates & dishes" }).codeValue, "3553"); + assert.equal(googleCategoryFor({ name: "Everyday mug" }).codeValue, "2169"); const pickupOnly = structuredData( { id: "P1", name: "Large sculpture", description: "Cone 10 · 8″ × 5″", variations: [{ id: "V", name: "R", price: 20000, stock: 1 }] }, "https://s.example", )["@graph"][0]; + assert.deepEqual(pickupOnly.depth, { "@type": "QuantitativeValue", value: 8, unitCode: "INH" }); assert.deepEqual(pickupOnly.width, { "@type": "QuantitativeValue", value: 8, unitCode: "INH" }); assert.deepEqual(pickupOnly.height, { "@type": "QuantitativeValue", value: 5, unitCode: "INH" }); + assert.equal(pickupOnly.weight, undefined, "shipLb/itemLb absent leaves Product.weight unset rather than faking it"); + assert.equal(pickupOnly.category.codeValue, "11"); assert.equal(pickupOnly.offers[0].shippingDetails.doesNotShip, true); }); diff --git a/docs/seo-plan.md b/docs/seo-plan.md index 0d934fe..ecad439 100644 --- a/docs/seo-plan.md +++ b/docs/seo-plan.md @@ -6,7 +6,7 @@ This plan helps people find the studio and its pieces in search, and gives share Built across `seo-pieces` (PRs #9 / #11) and the follow-up SEO & breadcrumbs rounds: -- **Piece pages, sitemap & Atom feed (`/p/<id>`, `/p/sitemap.xml`, `/p/feed.xml`):** Live in `piece-shell.html` with `Add to cart`, progressive `Share this piece`, `Home › Shop › <Category> › <Piece>` breadcrumbs, `Product` JSON-LD (including `OfferShippingDetails` with WA + US rates or `doesNotShip`, parsed inch `width`/`height`, `weight` in `LBR`, `material`, `countryOfOrigin`, `availableDeliveryMethod`, and `MerchantReturnPolicy`), `<image:image>` entries in `/p/sitemap.xml`, and an Atom 1.0 feed of available pieces at `/p/feed.xml` (for RSS and Pinterest). +- **Piece pages, sitemap & Atom feed (`/p/<id>`, `/p/sitemap.xml`, `/p/feed.xml`):** Live in `piece-shell.html` with `Add to cart`, progressive `Share this piece`, `Home › Shop › <Category> › <Piece>` breadcrumbs, `Product` JSON-LD (including Google Product Taxonomy `CategoryCode` + shop `category`, 3D inch `depth`/`width`/`height` dimensions, unpacked `Product.weight` from `item_lb` in `LBR`, `OfferShippingDetails` with WA + US rates and packed `weight` from `ship_lb` in `LBR` or `doesNotShip`, `material`, `countryOfOrigin`, `availableDeliveryMethod`, and `MerchantReturnPolicy`), `<image:image>` entries in `/p/sitemap.xml`, and an Atom 1.0 feed of available pieces at `/p/feed.xml` (for RSS and Pinterest). - **Canonical 301 redirects & `X-Robots-Tag`:** CloudFront Function in `deploy/site.yaml` (auto-enabled once `updraft-publish-ssm` includes `cloudfront:*Function*`, mirrored in `scripts/serve.mjs`) `301`-redirects `www.*` → apex, `/index.html` → `/`, and extensionless paths (`/shop` → `/shop.html`, etc.). `/api/*`, `410` responses, and staging responses carry `X-Robots-Tag: noindex`. - **Site-wide breadcrumbs & publish-time prerendering:** Every static subpage renders `<nav class="crumbs">` and matching `BreadcrumbList` JSON-LD; `/shop.html?type=<Category>` filters even below 8 pieces; `scripts/publish.mjs` passes `CATALOG_URL` so `/` and `/shop.html` bake static `<a href="/p/...">` piece links for non-JS crawlers while client JS refreshes live stock. - **Image discoverability, `<lastmod>` & `IndexNow` (item 12):** Gallery files emit descriptive slugged names (`/img/archive/01-green-footed-bowl-800-<hash>.webp`), tile captions surface descriptions visibly with deduplicated `alt` text, `sitemap-pages.xml` includes `<lastmod>` and `<image:image>` URLs for all high-res gallery photos, `past-work.html` exposes all archive pieces via `VisualArtwork` JSON-LD, and `scripts/publish.mjs` / `scripts/update-items.mjs` / `scripts/indexnow.mjs` notify IndexNow on production updates. @@ -105,7 +105,7 @@ Built across `seo-pieces` (PRs #9 / #11) and the follow-up SEO & breadcrumbs rou - **Google Search Console:** add a Domain property with a DNS TXT record in the Route 53 zone (Z88UBBDI22ZJ9), then submit `https://updraftpotterystudio.com/sitemap.xml`. - **Bing Webmaster Tools:** import the site from Search Console. Bing's index also feeds DuckDuckGo, Ecosia and Yahoo. - **Google Business Profile:** a service-area business in Tacoma with the address hidden, under the closest pottery category. Link it to the site. Post photos from each kiln opening. This is what shows on Maps and in "pottery near me" searches. - - **Google Merchant Center** (free listings): add the site and let it read the piece pages' Product data, after item 1 is live. Set shipping and returns there as well. Pieces can then show in the Shopping tab at no cost. + - **Google Merchant Center** (free listings): add the site and let it read the piece pages' Product data, after item 1 is live. Set shipping (2D state × weight cost table in `lb`—all product uploads require category, 3D dimensions, unpacked item weight `item_lb`, and packed shipping weight `ship_lb`) and returns there as well. Pieces can then show in the Shopping tab at no cost. - **Links from other sites** matter most over time, and they come from people: - Tacoma and Pierce County arts listings - local potters' guilds and the studios where Aaron learned diff --git a/e2e/fixtures/pieces.json b/e2e/fixtures/pieces.json index 0595fe6..b2e4d04 100644 --- a/e2e/fixtures/pieces.json +++ b/e2e/fixtures/pieces.json @@ -5,6 +5,7 @@ "name": "Celadon footed bowl", "description": "Cone 10 porcelain · celadon · 5½″ wide × 3″ tall", "category": "Bowls", + "itemLb": 1.75, "shipLb": 14, "image": null, "variations": [ diff --git a/e2e/piece-page.spec.mjs b/e2e/piece-page.spec.mjs index a6ed837..16d807f 100644 --- a/e2e/piece-page.spec.mjs +++ b/e2e/piece-page.spec.mjs @@ -31,9 +31,14 @@ test("a piece's page has its name, price, product data and its own address", asy "Product", "Celadon footed bowl", "65.00", - 14, + 1.75, + ]); + expect([product.depth.value, product.width.value, product.height.value]).toEqual([5.5, 5.5, 3]); + expect([product.category[0], product.category[1].codeValue]).toEqual(["Bowls", "3498"]); + expect(product.offers[0].shippingDetails.map((s) => [s.shippingRate.value, s.weight.value])).toEqual([ + ["33.00", 14], + ["52.00", 14], ]); - expect(product.offers[0].shippingDetails.map((s) => s.shippingRate.value)).toEqual(["33.00", "52.00"]); await expect(page.locator(".crumbs li")).toHaveText(["Home", "Shop", "Bowls", "Celadon footed bowl"]); expect(crumbs.itemListElement.map((c) => c.name)).toEqual(["Home", "Shop", "Bowls", "Celadon footed bowl"]); // Other pieces still for sale, each by its own page; the sold jar isn't among them. diff --git a/scripts/load-items.mjs b/scripts/load-items.mjs index cc8af70..566f7bb 100644 --- a/scripts/load-items.mjs +++ b/scripts/load-items.mjs @@ -1,6 +1,7 @@ -// Loads a batch of pieces into a stage's Square catalog: categories, the "Ship weight (lb)" attribute, -// then each item with its price, description ("<glaze> · <size>" then any batch/item description), category, ship -// weight, photos (cropped as the batch says, see scripts/listing-photo.mjs) and a stock count of 1 at the stage's location. +// Loads a batch of pieces into a stage's Square catalog: categories, "Ship weight (lb)" and "Item weight (lb)" +// attributes, then each item with its price, description ("<clay> · <glaze> · <size>" + body copy, parsed for +// 3D dimensions), category (mapped to Google's Product Taxonomy), item scale weight, packed shipping weight, +// cropped photos (see scripts/listing-photo.mjs) and a stock count of 1 at the stage's location. // Without --go it only prints what it would do. Items whose name is already in the catalog are skipped, // so a run that stopped part way can be run again. // node scripts/load-items.mjs scripts/items/2026-10-13.json --stage staging dry run @@ -12,9 +13,10 @@ import { randomUUID } from "node:crypto"; import path from "node:path"; import { currentStage } from "./stage.mjs"; import { squareClient, squareErrorMessage } from "./square-client.mjs"; -import { ensureShipWeightAttribute, SHIP_LB_KEY } from "./ship-weight-attribute.mjs"; +import { ensureCatalogAttributes, SHIP_LB_KEY, ITEM_LB_KEY } from "./ship-weight-attribute.mjs"; import { listingJpeg } from "./listing-photo.mjs"; import { submitIndexNow } from "./indexnow.mjs"; +import { parseDimensions, googleCategoryFor } from "../backend/src/piece-page.mjs"; const args = process.argv.slice(2); const opt = (name) => (args.includes(name) ? args[args.indexOf(name) + 1] : undefined); @@ -25,10 +27,22 @@ const stage = currentStage(); const batch = JSON.parse(readFileSync(file, "utf8")); const photoDir = opt("--photos") ?? batch.photoDir; -// Check everything local before touching Square. +const itemLbOf = (it) => (it.itemLb > 0 ? +Number(it.itemLb).toFixed(2) : it.itemOz > 0 ? +(Number(it.itemOz) / 16).toFixed(2) : null); +const specOf = (it) => [it.clay ?? batch.clay, it.glaze ?? batch.glaze, it.size].filter(Boolean).join(" · "); + +// Check everything local before touching Square: category, 3D dimensions, item weight, shipping weight, price and photos. const problems = []; for (const it of batch.items) { - if (!(it.price > 0) || !(it.shipLb > 0) || !it.category || !it.size || !it.photos?.length) problems.push(`${it.name}: incomplete entry`); + const itemLb = itemLbOf(it); + const dims = parseDimensions({ ...it, description: specOf(it) }); + if (!it.category) problems.push(`${it.name}: missing category`); + if (!(dims.depth > 0 && dims.width > 0 && dims.height > 0)) + problems.push( + `${it.name}: missing 3D dimensions (give size like "9½″ × 3¾″" or "14″ × 9″ × 1½″", or dimensions: { length, width, height })`, + ); + if (!(itemLb > 0)) problems.push(`${it.name}: missing itemLb / itemOz (all product uploads require an item weight)`); + if (!(it.shipLb > 0)) problems.push(`${it.name}: missing shipLb (all product uploads require a shipping weight in lb)`); + if (!(it.price > 0) || !it.photos?.length) problems.push(`${it.name}: incomplete entry (needs price and photos)`); for (const p of it.photos ?? []) if (!existsSync(path.join(photoDir, p))) problems.push(`${it.name}: missing photo ${path.join(photoDir, p)}`); } @@ -48,8 +62,9 @@ try { else categories.set(o.categoryData.name, o.id); } - const shipDef = await ensureShipWeightAttribute(square, { dryRun: !GO }); - console.log(`"Ship weight (lb)" attribute: ${shipDef.created ? (GO ? "created" : "would be created") : "already there"}`); + const attrs = await ensureCatalogAttributes(square, { dryRun: !GO }); + console.log(`"Ship weight (lb)" attribute: ${attrs.shipLb.created ? (GO ? "created" : "would be created") : "already there"}`); + console.log(`"Item weight (lb)" attribute: ${attrs.itemLb.created ? (GO ? "created" : "would be created") : "already there"}`); for (const name of new Set(batch.items.map((i) => i.category))) { if (categories.has(name)) continue; @@ -68,10 +83,14 @@ try { console.log(`skip ${it.name} (already in the catalog)`); continue; } - const spec = [it.clay ?? batch.clay, it.glaze ?? batch.glaze, it.size].filter(Boolean).join(" · "); + const spec = specOf(it); const description = [spec, it.description ?? batch.description].filter(Boolean).join("\n"); + const itemLb = itemLbOf(it); + const dims = parseDimensions({ ...it, description }); + const gpc = googleCategoryFor({ ...it, description }); console.log( - `${GO ? "create" : "would create"} ${it.name} $${it.price} [${it.category}] ship ${it.shipLb} lb ${it.photos.length} photo(s)`, + `${GO ? "create" : "would create"} ${it.name} $${it.price} [${it.category} -> GPC ${gpc.codeValue}] ` + + `${dims.depth}×${dims.width}×${dims.height}″ item ${itemLb} lb ship ${it.shipLb} lb ${it.photos.length} photo(s)`, ); if (!GO) continue; const categoryId = categories.get(it.category); @@ -80,7 +99,10 @@ try { object: { type: "ITEM", id: "#item", - customAttributeValues: { [SHIP_LB_KEY]: { customAttributeDefinitionId: shipDef.id, numberValue: String(it.shipLb) } }, + customAttributeValues: { + [SHIP_LB_KEY]: { customAttributeDefinitionId: attrs.shipLb.id, numberValue: String(it.shipLb) }, + [ITEM_LB_KEY]: { customAttributeDefinitionId: attrs.itemLb.id, numberValue: String(itemLb) }, + }, itemData: { name: it.name, description, diff --git a/scripts/ship-weight-attribute.mjs b/scripts/ship-weight-attribute.mjs index 541939f..033e6f2 100644 --- a/scripts/ship-weight-attribute.mjs +++ b/scripts/ship-weight-attribute.mjs @@ -1,6 +1,7 @@ -// Creates the "Ship weight (lb)" custom attribute on Square items, once per Square account. Shipping -// is priced from it (backend/src/shipping.mjs); fill it in for each item in Square Dashboard, or load -// items with scripts/load-items.mjs, which runs this first. +// Creates the "Ship weight (lb)" and "Item weight (lb)" custom attributes on Square items, once per +// Square account. Shipping is priced from ship_lb (backend/src/shipping.mjs) and OfferShippingDetails; +// item_lb is the unpacked scale weight for Google Merchant Center (Product.weight). Fill both in for +// each item in Square Dashboard, or load/update items with scripts/load-items.mjs / update-items.mjs. // node scripts/ship-weight-attribute.mjs production // node scripts/ship-weight-attribute.mjs --stage staging staging import { randomUUID } from "node:crypto"; @@ -9,37 +10,80 @@ import { currentStage } from "./stage.mjs"; import { squareClient, squareErrorMessage } from "./square-client.mjs"; export const SHIP_LB_KEY = "ship_lb"; // must match SHIP_LB_KEY in backend/src/catalog.mjs +export const ITEM_LB_KEY = "item_lb"; // must match ITEM_LB_KEY in backend/src/catalog.mjs -/** The definition's id, created if this Square account doesn't have it yet. */ -export async function ensureShipWeightAttribute(square, { dryRun = false } = {}) { - for await (const o of await square.catalog.list({ types: "CUSTOM_ATTRIBUTE_DEFINITION" })) - if (!o.isDeleted && o.customAttributeDefinitionData?.key === SHIP_LB_KEY) return { id: o.id, created: false }; +const DEFINITIONS = { + [SHIP_LB_KEY]: { + id: "#ship_lb", + name: "Ship weight (lb)", + description: "Billed weight of the packed box, from the pack-and-ship planner. Shipping is priced from it; empty = pickup only.", + precision: 1, + }, + [ITEM_LB_KEY]: { + id: "#item_lb", + name: "Item weight (lb)", + description: "Unpacked scale weight of the piece in pounds (e.g. 1.75), sent to Google Merchant Center as product_weight.", + precision: 2, + }, +}; + +async function existingAttrIds(square) { + const found = new Map(); + for await (const o of await square.catalog.list({ types: "CUSTOM_ATTRIBUTE_DEFINITION" })) { + if (!o.isDeleted && o.customAttributeDefinitionData?.key) found.set(o.customAttributeDefinitionData.key, o.id); + } + return found; +} + +async function ensureOne(square, found, key, { dryRun = false } = {}) { + if (!Object.hasOwn(DEFINITIONS, key)) throw new Error(`Unknown attribute key: ${key}`); + if (found.has(key)) return { id: found.get(key), created: false }; if (dryRun) return { id: null, created: true }; + const def = DEFINITIONS[key]; const { catalogObject } = await square.catalog.object.upsert({ idempotencyKey: randomUUID(), object: { type: "CUSTOM_ATTRIBUTE_DEFINITION", - id: "#ship_lb", + id: def.id, customAttributeDefinitionData: { type: "NUMBER", - name: "Ship weight (lb)", - description: "Billed weight of the packed box, from the pack-and-ship planner. Shipping is priced from it; empty = pickup only.", - key: SHIP_LB_KEY, + name: def.name, + description: def.description, + key, allowedObjectTypes: ["ITEM"], sellerVisibility: "SELLER_VISIBILITY_READ_WRITE_VALUES", appVisibility: "APP_VISIBILITY_READ_WRITE_VALUES", - numberConfig: { precision: 1 }, + numberConfig: { precision: def.precision }, }, }, }); return { id: catalogObject.id, created: true }; } +/** Ensures "Ship weight (lb)" exists in Square and returns { id, created }. */ +export async function ensureShipWeightAttribute(square, opts = {}) { + return ensureOne(square, await existingAttrIds(square), SHIP_LB_KEY, opts); +} + +/** Ensures both "Ship weight (lb)" and "Item weight (lb)" exist in Square. */ +export async function ensureCatalogAttributes(square, opts = {}) { + const found = await existingAttrIds(square); + return { + shipLb: await ensureOne(square, found, SHIP_LB_KEY, opts), + itemLb: await ensureOne(square, found, ITEM_LB_KEY, opts), + }; +} + if (import.meta.url === pathToFileURL(process.argv[1]).href) { const stage = currentStage(); try { - const { id, created } = await ensureShipWeightAttribute(await squareClient(stage)); - console.log(`${created ? "Created" : "Already there:"} "Ship weight (lb)" in Square ${stage.squareEnv} (${id}).`); + const attrs = await ensureCatalogAttributes(await squareClient(stage)); + for (const { key, res } of [ + { key: SHIP_LB_KEY, res: attrs.shipLb }, + { key: ITEM_LB_KEY, res: attrs.itemLb }, + ]) { + console.log(`${res.created ? "Created" : "Already there:"} "${DEFINITIONS[key].name}" in Square ${stage.squareEnv} (${res.id}).`); + } } catch (err) { console.error(squareErrorMessage(err)); process.exitCode = 1; diff --git a/scripts/update-items.mjs b/scripts/update-items.mjs index d6fd4bf..889ac1f 100644 --- a/scripts/update-items.mjs +++ b/scripts/update-items.mjs @@ -1,6 +1,6 @@ -// Updates the description (spec line + body copy) of pieces already in a stage's Square catalog -// from a batch file, preserving photos, stock counts, variations, categories and shipping weights. -// Without --go it only prints what would change. +// Syncs metadata (description + dimensions spec line, category, item weight, and shipping weight) of +// pieces already in a stage's Square catalog from a batch file, preserving photos, stock counts and prices. +// Without --go it only prints what would change (plus parsed 3D dimensions and Google taxonomy category). // node scripts/update-items.mjs scripts/items/2026-10-13.json --stage staging dry run // node scripts/update-items.mjs scripts/items/2026-10-13.json --stage staging --go update staging // node scripts/update-items.mjs scripts/items/2026-10-13.json --go update production @@ -9,7 +9,9 @@ import { readFileSync } from "node:fs"; import { randomUUID } from "node:crypto"; import { currentStage } from "./stage.mjs"; import { squareClient, squareErrorMessage } from "./square-client.mjs"; +import { ensureCatalogAttributes, SHIP_LB_KEY, ITEM_LB_KEY } from "./ship-weight-attribute.mjs"; import { submitIndexNow } from "./indexnow.mjs"; +import { parseDimensions, googleCategoryFor } from "../backend/src/piece-page.mjs"; const args = process.argv.slice(2); const opt = (name) => (args.includes(name) ? args[args.indexOf(name) + 1] : undefined); @@ -21,14 +23,41 @@ const batch = JSON.parse(readFileSync(file, "utf8")); const items = batch.items.filter((it) => !opt("--only") || it.name === opt("--only")); if (!items.length) throw new Error(`No item named "${opt("--only")}" in ${file}`); +const itemLbOf = (it) => (it.itemLb > 0 ? +Number(it.itemLb).toFixed(2) : it.itemOz > 0 ? +(Number(it.itemOz) / 16).toFixed(2) : null); +const attrVal = (obj, key) => { + const v = Object.values(obj.customAttributeValues ?? {}).find((x) => x?.key === key); + return v?.numberValue !== undefined ? Number(v.numberValue) : null; +}; + console.log( - `${GO ? "Updating" : "Dry run (add --go to update)"}: descriptions of ${items.length} items in Square ${stage.squareEnv} for stage "${stage.name}"`, + `${GO ? "Updating" : "Dry run (add --go to update)"}: metadata of ${items.length} items in Square ${stage.squareEnv} for stage "${stage.name}"`, ); const square = await squareClient(stage); try { const byName = new Map(); - for await (const o of await square.catalog.list({ types: "ITEM" })) if (!o.isDeleted) byName.set(o.itemData.name, o.id); + const categories = new Map(); + for await (const o of await square.catalog.list({ types: "ITEM,CATEGORY" })) { + if (o.isDeleted) continue; + if (o.type === "ITEM") byName.set(o.itemData.name, o.id); + else categories.set(o.categoryData.name, o.id); + } + + const attrs = await ensureCatalogAttributes(square, { dryRun: !GO }); + if (attrs.itemLb.created) console.log(`"Item weight (lb)" attribute: ${GO ? "created" : "would be created"}`); + if (attrs.shipLb.created) console.log(`"Ship weight (lb)" attribute: ${GO ? "created" : "would be created"}`); + + for (const name of new Set(items.map((i) => i.category).filter(Boolean))) { + if (categories.has(name)) continue; + console.log(`category ${name}: ${GO ? "created" : "would be created"}`); + if (!GO) continue; + const { catalogObject } = await square.catalog.object.upsert({ + idempotencyKey: randomUUID(), + object: { type: "CATEGORY", id: "#category", categoryData: { name } }, + }); + categories.set(name, catalogObject.id); + } + const updatedIds = []; for (const it of items) { @@ -39,16 +68,51 @@ try { } const spec = [it.clay ?? batch.clay, it.glaze ?? batch.glaze, it.size].filter(Boolean).join(" · "); const description = [spec, it.description ?? batch.description].filter(Boolean).join("\n"); + const itemLb = itemLbOf(it); + const shipLb = it.shipLb > 0 ? Number(it.shipLb) : null; + const dims = parseDimensions({ ...it, description }); + const gpc = googleCategoryFor({ ...it, description }); + const { object: current } = await square.catalog.object.get({ objectId: id }); - if (current.itemData.description === description) { - console.log(`same ${it.name}`); + const changes = []; + if ((current.itemData.description ?? "") !== description) changes.push(`description`); + const categoryId = it.category ? categories.get(it.category) : null; + const currentCatId = current.itemData.reportingCategory?.id ?? current.itemData.categories?.[0]?.id ?? null; + if (it.category && currentCatId !== categoryId) changes.push(`category -> ${it.category}`); + if (itemLb !== null && attrVal(current, ITEM_LB_KEY) !== itemLb) + changes.push(`itemLb: ${attrVal(current, ITEM_LB_KEY) ?? "none"} -> ${itemLb}`); + if (shipLb !== null && attrVal(current, SHIP_LB_KEY) !== shipLb) + changes.push(`shipLb: ${attrVal(current, SHIP_LB_KEY) ?? "none"} -> ${shipLb}`); + + const dimSummary = [dims.depth, dims.width, dims.height].filter(Boolean).join("×") + "″"; + const noteMissing = itemLb === null && attrVal(current, ITEM_LB_KEY) === null ? " [note: itemLb not set yet]" : ""; + if (!changes.length) { + console.log(`same ${it.name} [GPC ${gpc.codeValue}, dims ${dimSummary}]${noteMissing}`); continue; } - console.log(`${GO ? "update" : "would update"} ${it.name} (${id}):`); - console.log(` was: ${JSON.stringify(current.itemData.description ?? "")}`); - console.log(` now: ${JSON.stringify(description)}`); + console.log( + `${GO ? "update" : "would update"} ${it.name} (${id}) [${changes.join(", ")}] (GPC ${gpc.codeValue}, dims ${dimSummary})${noteMissing}`, + ); if (!GO) continue; + current.itemData.description = description; + if (categoryId) { + current.itemData.categories = [{ id: categoryId }]; + current.itemData.reportingCategory = { id: categoryId }; + } + current.customAttributeValues ??= {}; + if (shipLb !== null) { + current.customAttributeValues[SHIP_LB_KEY] = { + ...(current.customAttributeValues[SHIP_LB_KEY] ?? { customAttributeDefinitionId: attrs.shipLb.id }), + numberValue: String(shipLb), + }; + } + if (itemLb !== null) { + current.customAttributeValues[ITEM_LB_KEY] = { + ...(current.customAttributeValues[ITEM_LB_KEY] ?? { customAttributeDefinitionId: attrs.itemLb.id }), + numberValue: String(itemLb), + }; + } await square.catalog.object.upsert({ idempotencyKey: randomUUID(), object: current }); updatedIds.push(id); console.log(" done");