Skip to Content
Meubles Morinière

The projectSkills and evidence4 min read

Full-stack

Features that go from the database to the screen, in two applications: a rule written once, a payment that matches the page, stock that doesn’t sell twice, a cache that follows the ERP.

Each promise below is made to the customer or to the team. For each one, I show the code that keeps it and the test that checks it. The excerpts are read from the repository at build time (How to read these pages).

A rule written once serves both the storefront and the workshop

Before payment, the storefront promises a date. After it, the workshop follows a deadline. Both have to come out of the same calculation. With two copies, one miscounted public holiday would be enough for them to drift apart, and the customer would see the delay before the team did.

So the calculation is written only once, in packages/domain. It counts in working days, with the store’s closures and the Paris time zone. Both applications import it from that package. The storefront goes through a one-line relay (apps/site/shared/lib/workshop-due-date.ts). And if a copy comes back, the twin check rejects it (Architecture).

workshopDueDatepackages/domain/src/workshop-due-date.ts · lines 21–34
export function workshopDueDate(
	paidAt: Date,
	closures: readonly ClosurePeriodLike[],
	leadTimeWeeks: LeadTimeWeeks = REFERENCE_LEAD_TIME_WEEKS,
	timeZone: string = STORE_TIME_ZONE,
): Date {
	const paidDay = toIsoDateIn(paidAt, timeZone);
	const day = addWorkshopBusinessDays(
		paidDay,
		workshopShippingBusinessDays(leadTimeWeeks),
		closures,
	) as CivilDay;
	return new Date(zonedMidnight(day, timeZone).getTime() + localTimeOfDayMs(paidAt, timeZone));
}

Further reading: Lead times and promised dates, ADR 0005.

Customers pay what the page showed them

Between the moment the cart is displayed and the click on “Pay”, a price can change, a discount can expire, a piece can be sold in the store. If you charge an amount other than the one displayed, you mislead the customer. But if the page already showed the new price and you refuse the order, you annoy them for nothing.

So the checkout page sends the lines it displayed, and the server reads the prices and stock again from the database to compare. If the page already showed the current state, the order goes through. If not, the server refuses and names the piece concerned (the first one, if several prices changed), and the cart updates. The customer can check before trying again.

reconcileCartWithCatalogueapps/site/modules/checkout/services/checkout.service.ts · lines 88–207
/**
 * Le panier du cookie relu en base, ligne par ligne, avant toute écriture de commande. `email` :
 * l'adresse saisie, dont les paiements en attente ne retiennent pas les pièces contre elle.
 *
 * `shown` : les lignes que la page de commande a montrées (`expectedLines`). Quand elles disent
 * exactement ce qui sera débité, la cliente a déjà lu l'état présent — pièces retirées annoncées
 * hors de la commande, nouveau prix affiché : le panier se met à jour sans refus, et la commande
 * part. Quand elles diffèrent, ou sans elles (une page d'avant ce champ), chaque écart se dit par
 * un refus, et la page relue montre l'état présent. Jamais un montant que la page n'a pas affiché.
 */
export async function reconcileCartWithCatalogue(
	shown?: readonly ShownLine[],
	email?: string,
): Promise<CheckoutLineInput[]> {
	const cart = await readCartCookie();
	if (cart.items.length === 0) throw new BusinessError(CHECKOUT_ERROR_MESSAGES.EMPTY_CART);

	const rows = await prisma.productVariant.findMany({
		where: { id: { in: cart.items.map((item) => item.variantId) } },
		select: RECONCILE_SELECT,
	});
	const nowMs = wallClockMs();
	const variants = rows.map((row) => settleEndedDiscount(row, nowMs));
	const byId = new Map(variants.map((variant) => [variant.id, variant]));
	// Le stock libre, comme le panier et la page de commande (`withFreeStock`) : une pièce qu'un autre
	// paiement tient en entier reste au panier, hors de cette commande, sans refus. Ce que la même
	// adresse paie déjà ailleurs (un autre appareil) ne compte pas contre elle, comme au paiement
	// (`findTrackedStockShortage`).
	const free = await withFreeStock(rows, cart.pendingOrderId ?? null, email ?? null);
	const heldIds = new Set(
		free.flatMap((variant) =>
			variant.inventoryPolicy === InventoryPolicy.TRACKED &&
			variant.heldElsewhere > 0 &&
			variant.stock <= 0
				? [variant.id]
				: [],
		),
	);

	const resolved = cart.items.map((item) => ({ item, variant: byId.get(item.variantId) }));

	const withdrawn = resolved.filter(({ variant }) => isWithdrawn(variant));
	const sellable = resolved.flatMap(({ item, variant }) =>
		variant === undefined || isWithdrawn(variant) || heldIds.has(variant.id)
			? []
			: [{ item, variant, unitPriceCents: announcedPriceCents(variant) }],
	);
	const priced = new Map(
		sellable.map(({ item, unitPriceCents }) => [item.variantId, unitPriceCents]),
	);
	const keptItems = (reprice: boolean) =>
		cart.items.flatMap((item) => {
			if (heldIds.has(item.variantId)) return [item];
			const unitPriceCents = priced.get(item.variantId);
			if (unitPriceCents === undefined) return [];
			return [reprice ? { ...item, priceAtAddCents: unitPriceCents } : item];
		});
	const repriced = sellable.filter(
		({ item, unitPriceCents }) => unitPriceCents !== item.priceAtAddCents,
	);
	const isAsShown =
		shown !== undefined &&
		sellable.length > 0 &&
		sameShownLines(
			shown,
			sellable.map(({ item, unitPriceCents }) => ({
				variantId: item.variantId,
				quantity: item.quantity,
				unitPriceCents,
			})),
		);

	if (isAsShown && (withdrawn.length > 0 || repriced.length > 0)) {
		await writeCartCookie({ items: keptItems(true) });
	}

	if (!isAsShown && withdrawn.length > 0) {
		const kept = keptItems(false);
		await writeCartCookie({ items: kept });
		throw new CartPiecesRemovedError(withdrawalMessage(withdrawn.map(({ variant }) => variant)), {
			variantIds: withdrawn.map(({ item }) => item.variantId),
			// Rien de commandable ne reste : le panier est vide, ou ne garde que des pièces qu'un autre
			// paiement tient. La page relue n'aurait plus de formulaire pour dire ce refus.
			nothingLeftToOrder: kept.every((item) => heldIds.has(item.variantId)),
		});
	}

	for (const { item, variant } of sellable) {
		if (variant.inventoryPolicy === InventoryPolicy.TRACKED && variant.stock < item.quantity) {
			throw new BusinessError(CHECKOUT_ERROR_MESSAGES.INSUFFICIENT_STOCK(variant.product.name));
		}
	}

	if (!isAsShown) {
		const first = repriced[0];
		if (first !== undefined) {
			await writeCartCookie({ items: keptItems(true) });
			throw new BusinessError(CHECKOUT_ERROR_MESSAGES.PRICE_CHANGED(first.variant.product.name));
		}
		// La page a montré un autre panier (un autre onglet l'a changé, ou elle date d'avant une
		// baisse de prix) : rien à corriger dans le cookie, mais la cliente doit relire le dû.
		if (shown !== undefined) throw new BusinessError(CHECKOUT_ERROR_MESSAGES.CART_CHANGED);
	}

	return sellable.map<CheckoutLineInput>(({ item, variant }) => ({
		variantId: variant.id,
		quantity: item.quantity,
		unitPriceCents: variant.priceCents,
		ecoContributionUnitCents: variant.ecoContributionCents,
		vatRateBps: STANDARD_VAT_RATE_BPS,
		kind: LineKind.GOODS,
		unitCostCents: null,
		nameSnapshot: variant.product.name,
		variantSnapshot: variant.label,
		referenceSnapshot: variant.reference,
		gtinSnapshot: variant.gtin,
		madeToOrderSnapshot: variant.inventoryPolicy === InventoryPolicy.MADE_TO_ORDER,
		weightG: variant.weightG,
	}));
}

Further reading: Cart and checkout.

The last unit sells only once, even when it is paid for twice in the same second

The store and the storefront sell the same stock. If two payments are confirmed at the same moment for the last piece, it mustn’t be sold twice. And neither of the two orders should be left without an explanation.

Stock is decremented by a conditional update, inside the payment transaction. So the database only removes the piece if there’s one left. The order that comes second is flagged as oversold, and the team deals with it. On top of that, beneath the code, a database constraint forbids negative stock, whatever the application does.

decrementPaidStockapps/erp/modules/payments/services/paid-stock.ts · lines 32–66
export async function decrementPaidStock(
	tx: Prisma.TransactionClient,
	order: { id: string; items: readonly PaidOrderLine[] },
): Promise<PaidStockOutcome> {
	const oversold: OversoldItem[] = [];
	const decremented = new Set<string>();
	let decrementedCount = 0;

	const tracked = order.items.filter(isStockTracked);
	const applied = await changeOrderStock(
		tx,
		order.id,
		tracked.map((item) => ({
			variantId: item.variantId,
			by: -item.quantity,
			reason: StockMovementReason.SALE,
			where: { inventoryPolicy: InventoryPolicy.TRACKED, stock: { gte: item.quantity } },
		})),
	);
	for (const [index, item] of tracked.entries()) {
		if (applied[index] !== true) {
			oversold.push({ variantId: item.variantId, quantity: item.quantity });
			await tx.orderItem.updateMany({
				where: { id: item.id, orderId: order.id, backorderedAt: null },
				data: { backorderedAt: wallClock() },
			});
			continue;
		}
		decrementedCount += 1;
		const slug = item.variant?.product.slug;
		if (slug !== undefined) decremented.add(slug);
	}

	return { oversold, decrementedCount, decrementedSlugs: [...decremented] };
}

Further reading: Stock, Data.

What you change in the ERP shows up on the storefront right away, without bringing it down

The storefront serves its pages from a cache. After an in-store sale or a price cut, it has to stop showing the old price or stock that’s already sold. Except that if you invalidate the whole cache on every stock movement, every page gets rebuilt while the visitor waits. And if the database is slow at that moment, the whole storefront goes down.

So after each write, the ERP sends the storefront the affected tags, over an authenticated channel. The storefront expires right away whatever contains a price, a stock level or a date. For the taxonomy, it serves the old version while it rebuilds it.

SWR_TAGSapps/site/app/api/revalidate/route.ts · lines 19–41
/**
 * Les tags de pure taxonomie : quelles pièces, catégories et collections les listes et la barre
 * nomment. Ils passent en stale-while-revalidate (`"max"`) : la page suivante sert la dernière copie
 * et se refait en arrière-plan — et garde cette copie si la base flanche à ce moment-là.
 *
 * Tous les autres expirent IMMÉDIATEMENT (`expire: 0`) : prix et stock (`variants`, `product:<slug>`),
 * port (`shipping`), dates promises (`closures`, `workshop`), ouverture du magasin
 * (`store-settings`). Chaque lecture qui montre un prix, un stock ou un délai porte `variants`, et
 * l'ERP l'envoie avec `products` dès qu'une écriture peut les changer (`revalidateCatalogue`). Une
 * retouche photo ne les change pas : elle n'envoie que `products` et la fiche
 * (`revalidateProductPhotos`).
 *
 * Sans cette part, chaque mouvement de stock expirait sans repli les lectures de la barre et du pied
 * (catégories, collections), présentes sur toutes les pages : la visite suivante de chaque adresse
 * refaisait tout en bloquant, et une base lente à cet instant faisait tomber le site entier.
 */
const SWR_TAGS: ReadonlySet<string> = new Set([
	PRODUCTS_CACHE_TAG,
	CATEGORIES_CACHE_TAG,
	COLLECTIONS_CACHE_TAG,
	COLORS_CACHE_TAG,
	MATERIALS_CACHE_TAG,
]);

On the ERP side, a test sorts every server action in the repository. The ones that change what the storefront displays have to invalidate its cache. The others must not. And a new action has to go into one of the two lists (Quality).

Further reading: Exchanges between the applications, ADR 0007.

On this page