Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions backend/src/catalog.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ export async function loadCatalog() {
const here = d.locationOverrides?.find((x) => x.locationId === SQUARE_LOCATION_ID);
const name = o.itemData.variations.length > 1 ? `${o.itemData.name} (${d.name})` : o.itemData.name;
info.set(v.id, {
itemId: o.id,
name,
tracked: Boolean(here?.trackInventory ?? d.trackInventory),
soldOut: Boolean(here?.soldOut),
Expand Down Expand Up @@ -113,3 +114,9 @@ export async function shipWeights(lines) {
}
return { weights, missing };
}

// Square ITEM ids for the variations in a cart, for clearing /p/<id> caches and IndexNow after a sale.
export async function itemIdsFor(lines) {
await loadCatalog();
return [...new Set(lines.map((l) => cache.info.get(l.variationId)?.itemId).filter(Boolean))];
}
5 changes: 4 additions & 1 deletion backend/src/checkout.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,10 @@
import { randomUUID } from "node:crypto";
import { SQUARE_LOCATION_ID, square } from "./config.mjs";
import { respond, EMAIL_RE } from "./http.mjs";
import { checkStock, shipWeights, unknownLines } from "./catalog.mjs";
import { checkStock, itemIdsFor, shipWeights, unknownLines } from "./catalog.mjs";
import { shippingCents } from "./shipping.mjs";
import { recordSale } from "./stock.mjs";
import { afterSale } from "./notify-sale.mjs";

const MAX_LINES = 20;
const MAX_QTY = 10;
Expand Down Expand Up @@ -262,12 +263,14 @@ export async function checkout(b) {
const saleAt = Date.now();
const { payment } = await square().payments.complete({ paymentId: auth.id });
recordSale(b.lines, saleAt);
await afterSale(await itemIdsFor(b.lines));
return respond(200, { orderId: order.id, total, status: payment.status, receiptUrl: payment.receiptUrl });
} catch (err) {
// The charge may have gone through even though the call failed (e.g. a timeout on the reply).
const status = await paymentStatus(auth.id);
if (status?.status === "COMPLETED") {
recordSale(b.lines, Date.now());
await afterSale(await itemIdsFor(b.lines));
return respond(200, { orderId: order.id, total, status: status.status, receiptUrl: status.receiptUrl });
}
console.error("CHECKOUT_FAILED after authorising; releasing the hold", order.id, err?.message);
Expand Down
8 changes: 5 additions & 3 deletions backend/src/handler.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,17 @@
// POST /api/checkout -> order + authorise + stock re-check + charge (checkout.mjs)
// POST /api/subscribe -> email signup into the Square customer directory (subscribe.mjs)
// GET /p/<item id> -> the page for one piece, in the site's own shell (piece.mjs)
// GET /p/sitemap.xml -> every piece's address, for search engines (piece.mjs)
// GET /p/feed.xml -> Atom feed of available pieces, for RSS and Pinterest (piece.mjs)
// GET /p/sitemap.xml -> every piece's address, for search engines (piece.mjs)
// GET /p/feed.xml -> Atom feed of available pieces, for RSS readers (piece.mjs)
// GET /p/merchant.xml -> RSS 2.0 product feed for Google Merchant Center and Pinterest Catalogs (piece.mjs)
// Each function serves only the routes in ROUTES (the template gives checkout its own function).
import { SquareError } from "square";
import { respond, clientIp } from "./http.mjs";
import { loadCatalog } from "./catalog.mjs";
import { quote, checkout, declineMessage } from "./checkout.mjs";
import { subscribe, _resetLimits as resetSubscribeLimits } from "./subscribe.mjs";
import { _resetSales } from "./stock.mjs";
import { piece, sitemap, feed } from "./piece.mjs";
import { piece, sitemap, feed, merchantFeed } from "./piece.mjs";

const routes = new Set((process.env.ROUTES ?? "catalog,quote,subscribe,checkout,piece").split(",").map((r) => r.trim()));
const posts = { "/api/quote": quote, "/api/checkout": checkout, "/api/subscribe": subscribe };
Expand Down Expand Up @@ -42,6 +43,7 @@ export async function handler(event) {
// decoded, since a malformed escape like /p/%E0 would throw and be answered as an unhandled error.
if (method === "GET" && routes.has("piece") && path === "/p/sitemap.xml") return await sitemap();
if (method === "GET" && routes.has("piece") && path === "/p/feed.xml") return await feed();
if (method === "GET" && routes.has("piece") && path === "/p/merchant.xml") return await merchantFeed();
if (method === "GET" && routes.has("piece") && path?.startsWith("/p/")) return await piece(path.slice(3));
if (method === "POST" && posts[path]) {
const body = readBody(event);
Expand Down
84 changes: 84 additions & 0 deletions backend/src/notify-sale.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
// Best-effort post-sale refresh: clears CloudFront's 5-minute /p/* cache for sold pieces and their
// feeds, and notifies IndexNow on production. Never throws, so a CDN or IndexNow hiccup cannot affect
// an already-completed payment response.
const INDEXNOW_KEY = "b8f4c2e9a1d740639e5c82b1f7a3d904";

let cfClientPromise;
function cloudFrontInvalidate(distributionId, paths) {
cfClientPromise ??= (async () => {
const pkg = "@aws-sdk/client-cloudfront";
const { CloudFrontClient, CreateInvalidationCommand } = await import(pkg);
const client = new CloudFrontClient({ region: "us-east-1" });
return (distId, items) =>
client.send(
new CreateInvalidationCommand({
DistributionId: distId,
InvalidationBatch: {
CallerReference: `sale-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
Paths: { Quantity: items.length, Items: items },
},
}),
{ abortSignal: AbortSignal.timeout(3_000) },
);
})().catch((err) => {
cfClientPromise = undefined;
throw err;
});
return cfClientPromise.then((send) => send(distributionId, paths));
}

let customInvalidator = null;
/** @param {((distId: string, paths: string[]) => Promise<unknown>) | null} fn */
export function _setInvalidator(fn) {
customInvalidator = fn;
}

/**
* Clears cached piece pages/feeds and pings IndexNow after a completed checkout.
* @param {string[]} itemIds Square catalog ITEM ids included in the completed order
*/
export async function afterSale(itemIds) {
const ids = [...new Set(itemIds.filter(Boolean))];
if (!ids.length) return;

const distId = (process.env.DISTRIBUTION_ID ?? "").trim();
const origin = (process.env.ALLOWED_ORIGIN ?? "").replace(/\/$/, "");
const prod = process.env.SQUARE_ENV === "production" && /^https:\/\/[^/]+$/.test(origin);

const tasks = [];
if (distId) {
const paths = [...ids.map((id) => `/p/${encodeURIComponent(id)}`), "/p/sitemap.xml", "/p/feed.xml", "/p/merchant.xml"];
const run = customInvalidator ?? cloudFrontInvalidate;
tasks.push(
run(distId, paths).catch((err) => {
console.error("SALE_INVALIDATE_FAILED", err?.message ?? err);
}),
);
}

if (prod) {
const host = new URL(origin).host;
const urlList = [`${origin}/`, `${origin}/shop.html`, ...ids.map((id) => `${origin}/p/${encodeURIComponent(id)}`)];
tasks.push(
fetch("https://api.indexnow.org/indexnow", {
method: "POST",
headers: { "content-type": "application/json; charset=utf-8" },
body: JSON.stringify({
host,
key: INDEXNOW_KEY,
keyLocation: `${origin}/${INDEXNOW_KEY}.txt`,
urlList,
}),
signal: AbortSignal.timeout(3_000),
})
.then((res) => {
if (res.status >= 400) console.error("SALE_INDEXNOW_FAILED", `HTTP ${res.status}`);
})
.catch((err) => {
console.error("SALE_INDEXNOW_FAILED", err?.message ?? err);
}),
);
}

if (tasks.length) await Promise.allSettled(tasks);
}
88 changes: 80 additions & 8 deletions backend/src/piece-page.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -210,6 +210,19 @@ export function parseDimensions(item) {
return base;
}

/** WA Zone 3 and US Zone 8 label ceilings in whole dollars for one packed parcel, or null when unshippable. */
function shippingRatesFor(shipLb) {
if (!(shipLb > 0)) return null;
const maxForZone = (zone) => {
const ups = labelDollars("ups", zone, shipLb);
if (ups === null) return null;
return Math.ceil(Math.max(ups, labelDollars("usps", zone, shipLb) ?? 0));
};
const wa = maxForZone(3);
const us = maxForZone(8);
return wa === null || us === null ? null : { wa, us };
}

/** OfferShippingDetails for one parcel (WA Zone 3 + US Zone 8 ceiling + packed weight), or doesNotShip when pickup-only. */
function shippingDetailsFor(shipLb) {
if (!(shipLb > 0)) {
Expand All @@ -219,14 +232,9 @@ function shippingDetailsFor(shipLb) {
shippingDestination: { "@type": "DefinedRegion", addressCountry: "US" },
};
}
const maxForZone = (zone) => {
const ups = labelDollars("ups", zone, shipLb);
if (ups === null) return null;
return Math.ceil(Math.max(ups, labelDollars("usps", zone, shipLb) ?? 0));
};
const wa = maxForZone(3);
const us = maxForZone(8);
if (wa === null || us === null) return null;
const rates = shippingRatesFor(shipLb);
if (!rates) return null;
const { wa, us } = rates;
const handlingTime = { "@type": "QuantitativeValue", minValue: 1, maxValue: 2, unitCode: "DAY" };
const weight = qvLb(shipLb);
return [
Expand Down Expand Up @@ -488,3 +496,67 @@ export function piecesFeed(items, site) {
`</feed>\n`
);
}

/**
* Google Merchant Center + Pinterest Catalogs RSS 2.0 XML product feed (/p/merchant.xml).
* Lists every unarchived piece with live availability (in_stock / out_of_stock), explicit
* identifier_exists=no for one-of-a-kind handmade work, Google Product Taxonomy ID, 3D dimensions,
* item + shipping weights, and WA / US Ground shipping rates.
*/
export function piecesMerchantFeed(items, site) {
const entries = items.flatMap((item) => {
const many = item.variations.length > 1;
const url = `${site}/p/${item.id}`;
const photos = photosOf(item);
const dims = parseDimensions(item);
const gpc = googleCategoryFor(item);
const rates = shippingRatesFor(item.shipLb);
const desc = item.description?.trim() || metaDescription(item);
return item.variations.map((v) => {
const id = many ? `${item.id}-${v.id}` : item.id;
const title = many ? `${item.name} (${v.name})` : item.name;
const fields = [
`<g:id>${esc(id)}</g:id>`,
...(many ? [`<g:item_group_id>${esc(item.id)}</g:item_group_id>`] : []),
`<title>${esc(title)}</title>`,
`<description>${esc(desc)}</description>`,
`<link>${esc(url)}</link>`,
...(photos[0] ? [`<g:image_link>${esc(site + sized(photos[0], 1200, "jpeg"))}</g:image_link>`] : []),
...photos.slice(1, 11).map((p) => `<g:additional_image_link>${esc(site + sized(p, 1200, "jpeg"))}</g:additional_image_link>`),
`<g:availability>${isOpen(v) ? "in_stock" : "out_of_stock"}</g:availability>`,
`<g:price>${(v.price / 100).toFixed(2)} ${esc(v.currency ?? "USD")}</g:price>`,
`<g:condition>new</g:condition>`,
`<g:brand>${SITE_NAME}</g:brand>`,
`<g:identifier_exists>no</g:identifier_exists>`,
`<g:google_product_category>${esc(gpc.codeValue)}</g:google_product_category>`,
...(item.category ? [`<g:product_type>${esc(item.category)}</g:product_type>`] : []),
`<g:material>${esc(materialOf(item))}</g:material>`,
...(dims.depth ? [`<g:product_length>${+dims.depth.toFixed(3)} in</g:product_length>`] : []),
...(dims.width ? [`<g:product_width>${+dims.width.toFixed(3)} in</g:product_width>`] : []),
...(dims.height ? [`<g:product_height>${+dims.height.toFixed(3)} in</g:product_height>`] : []),
...(item.itemLb > 0 ? [`<g:product_weight>${+Number(item.itemLb).toFixed(2)} lb</g:product_weight>`] : []),
...(item.shipLb > 0 ? [`<g:shipping_weight>${+Number(item.shipLb).toFixed(2)} lb</g:shipping_weight>`] : []),
...(rates
? [
`<g:min_handling_time>1</g:min_handling_time>`,
`<g:max_handling_time>2</g:max_handling_time>`,
`<g:shipping><g:country>US</g:country><g:region>WA</g:region><g:service>Ground</g:service><g:price>${rates.wa.toFixed(2)} USD</g:price><g:min_transit_time>1</g:min_transit_time><g:max_transit_time>3</g:max_transit_time></g:shipping>`,
`<g:shipping><g:country>US</g:country><g:service>Ground</g:service><g:price>${rates.us.toFixed(2)} USD</g:price><g:min_transit_time>1</g:min_transit_time><g:max_transit_time>6</g:max_transit_time></g:shipping>`,
]
: []),
];
return ` <item>\n ${fields.join("\n ")}\n </item>`;
});
});
return (
`<?xml version="1.0" encoding="UTF-8"?>\n` +
`<rss version="2.0" xmlns:g="http://base.google.com/ns/1.0">\n` +
` <channel>\n` +
` <title>${SITE_NAME}</title>\n` +
` <link>${esc(`${site}/shop.html`)}</link>\n` +
` <description>One-of-a-kind handmade porcelain and stoneware pottery fired in Tacoma, Washington.</description>\n` +
`${entries.join("\n")}\n` +
` </channel>\n` +
`</rss>\n`
);
}
6 changes: 5 additions & 1 deletion backend/src/piece.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
// under /p/ may only list pages under /p/, which is all it needs, and the /p/* route is already here.
import { ALLOWED_ORIGIN } from "./config.mjs";
import { loadCatalog } from "./catalog.mjs";
import { renderPiece, gonePage, piecesSitemap, piecesFeed } from "./piece-page.mjs";
import { renderPiece, gonePage, piecesSitemap, piecesFeed, piecesMerchantFeed } from "./piece-page.mjs";

const site = () => (ALLOWED_ORIGIN === "*" ? "" : ALLOWED_ORIGIN);
const reply = (status, type, body, cache, extra = {}) => ({
Expand Down Expand Up @@ -63,3 +63,7 @@ export async function sitemap() {
export async function feed() {
return reply(200, "application/atom+xml", piecesFeed(await loadCatalog(), site()), "public, max-age=300");
}

export async function merchantFeed() {
return reply(200, "application/xml", piecesMerchantFeed(await loadCatalog(), site()), "public, max-age=300");
}
12 changes: 11 additions & 1 deletion backend/template.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@ Description: >
Square catalog + checkout API for Updraft Pottery Studio (one stack per stage: updraft-api,
updraft-staging-api). Deployed by scripts/deploy-api.mjs from deploy/stages.json.

Metadata:
AWSToolsMetrics:
AWSAgentToolkit: aws-cloudformation@3

Parameters:
SquareTokenParam: { Type: String, Description: "SSM SecureString holding the Square access token, e.g. /updraft/prod/square-access-token" }
SquareLocationId: { Type: String }
Expand All @@ -17,6 +21,10 @@ Parameters:
Default: arn:aws:iam::724654236968:policy/updraft-lambda-ssm-read
Description: Admin-created managed policy allowing ssm:GetParameter on /updraft/*
AlertEmail: { Type: String, Default: "", Description: "Where alarms are emailed (SNS asks to confirm once). Empty = no alarms." }
DistributionId:
Type: String
Default: ""
Description: "Optional CloudFront distribution ID so completed checkouts immediately invalidate /p/* caches"

Conditions:
CapConcurrency: !Not [!Equals [!Ref ApiConcurrency, 0]]
Expand Down Expand Up @@ -74,7 +82,9 @@ Resources:
Timeout: 30
LoggingConfig: { LogGroup: !Ref CheckoutLogs }
Environment:
Variables: { ROUTES: checkout } # merged with Globals
Variables:
ROUTES: checkout # merged with Globals
DISTRIBUTION_ID: !Ref DistributionId
FunctionUrlConfig:
AuthType: AWS_IAM # see Api

Expand Down
57 changes: 57 additions & 0 deletions backend/test/checkout-flow.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -280,3 +280,60 @@ test("a shipping quote needs the destination before it has a total", async () =>
const pickup = await post({ lines, fulfillment: "pickup" }, "/api/quote");
assert.deepEqual([pickup.body.shipping, pickup.body.total], [0, 5000]);
});

import { _setInvalidator } from "../src/notify-sale.mjs";
test("a completed sale clears /p/* caches and pings IndexNow on production without ever failing checkout", async (t) => {
const prev = {
dist: process.env.DISTRIBUTION_ID,
env: process.env.SQUARE_ENV,
origin: process.env.ALLOWED_ORIGIN,
};
t.after(() => {
_setInvalidator(null);
for (const [k, v] of [
["DISTRIBUTION_ID", prev.dist],
["SQUARE_ENV", prev.env],
["ALLOWED_ORIGIN", prev.origin],
]) {
if (v === undefined) delete process.env[k];
else process.env[k] = v;
}
});

const invalidations = [];
const indexNowBodies = [];
_setInvalidator(async (distId, paths) => {
invalidations.push([distId, paths]);
});
t.mock.method(globalThis, "fetch", async (url, init) => {
if (url === "https://api.indexnow.org/indexnow") {
indexNowBodies.push(JSON.parse(String(init?.body)));
return new Response("", { status: 202 });
}
throw new Error(`unexpected fetch: ${url}`);
});

process.env.DISTRIBUTION_ID = "EDIST123";
process.env.SQUARE_ENV = "production";
process.env.ALLOWED_ORIGIN = "https://updraftpotterystudio.com";

fresh();
assert.equal((await post(body("sale-1"))).status, 200);
assert.deepEqual(invalidations, [["EDIST123", ["/p/I1", "/p/sitemap.xml", "/p/feed.xml", "/p/merchant.xml"]]]);
assert.equal(indexNowBodies.length, 1);
assert.deepEqual(indexNowBodies[0].urlList, [
"https://updraftpotterystudio.com/",
"https://updraftpotterystudio.com/shop.html",
"https://updraftpotterystudio.com/p/I1",
]);

// Even if both invalidation and IndexNow throw, checkout still returns 200.
_setInvalidator(async () => {
throw new Error("cdn down");
});
t.mock.method(globalThis, "fetch", async () => {
throw new Error("indexnow down");
});
fresh();
assert.equal((await post(body("sale-2"))).status, 200);
});
Loading
Loading