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
37 changes: 37 additions & 0 deletions backend/migrations/20260922120000-resort-variants-by-size.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
'use strict';

/**
* Recomputes `variants.sort_order` from each variant's size.
*
* The original backfill ranked sizes with `SIZE_ORDER.indexOf(size)`, and the
* admin routes defaulted a new variant's sort_order to 0. Both put any size
* outside the XS..XXXL list (a "5X", say) ahead of Small — which is how the
* Hydraulic Jeff shirt ended up listing 5X first.
*
* Size-less variants (CDs, patches, …) stay at 0; they're alone on their
* product, so their sort_order never matters.
*/

const { sizeRank } = require('../utils/sizeRank');

module.exports = {
up: async (queryInterface, Sequelize) => {
const { QueryTypes } = Sequelize;

const variants = await queryInterface.sequelize.query(
'SELECT id, size FROM variants',
{ type: QueryTypes.SELECT }
);

for (const variant of variants) {
const sortOrder = variant.size ? sizeRank(variant.size) : 0;
await queryInterface.sequelize.query(
'UPDATE variants SET sort_order = :sortOrder, "updatedAt" = NOW() WHERE id = :id',
{ replacements: { sortOrder, id: variant.id }, type: QueryTypes.UPDATE }
);
}
},

// Ordering is derived from size, so there's no prior state worth restoring.
down: async () => {}
};
20 changes: 17 additions & 3 deletions backend/routes/admin.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
const express = require('express');
const { Product, Variant } = require('../models');
const { sizeRank } = require('../utils/sizeRank');
const { requireAuth } = require('../middleware/auth');
const router = express.Router();

Expand Down Expand Up @@ -34,6 +35,14 @@ function parsePrice(value) {
return n;
}

// A variant's sort_order defaults to its size's position (XS -> 5XL) rather
// than 0, so a size added later slots in where it belongs instead of jumping
// to the front of the list. An explicit sort_order from the caller still wins.
function resolveSortOrder(sort_order, size) {
if (Number.isInteger(sort_order)) return sort_order;
return size ? sizeRank(size) : 0;
}

// --- List all products (incl. inactive) with all variants, for the admin ---
router.get('/products', async (req, res) => {
try {
Expand Down Expand Up @@ -89,7 +98,7 @@ router.post('/products', async (req, res) => {
price,
stock: Number.isInteger(v.stock) ? v.stock : 0,
active: v.active !== undefined ? !!v.active : true,
sort_order: Number.isInteger(v.sort_order) ? v.sort_order : 0
sort_order: resolveSortOrder(v.sort_order, v.size)
});
}
}
Expand Down Expand Up @@ -175,7 +184,7 @@ router.post('/products/:id/variants', async (req, res) => {
price: parsedPrice,
stock: Number.isInteger(stock) ? stock : 0,
active: active !== undefined ? !!active : true,
sort_order: Number.isInteger(sort_order) ? sort_order : 0
sort_order: resolveSortOrder(sort_order, size)
});

res.status(201).json(variant);
Expand All @@ -202,7 +211,12 @@ router.put('/variants/:id', async (req, res) => {
}
variant.price = parsedPrice;
}
if (size !== undefined) variant.size = size || null;
if (size !== undefined) {
variant.size = size || null;
// Re-slot the variant when its size changes (unless the caller
// pinned an explicit sort_order below).
variant.sort_order = variant.size ? sizeRank(variant.size) : 0;
}
if (stock !== undefined && Number.isInteger(stock)) variant.stock = stock;
if (active !== undefined) variant.active = !!active;
if (sort_order !== undefined && Number.isInteger(sort_order)) variant.sort_order = sort_order;
Expand Down
64 changes: 64 additions & 0 deletions backend/scripts/prod-resort-variants-by-size.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
-- Resort variants by size — manual SQL equivalent of migration
-- 20260922120000-resort-variants-by-size.
--
-- Use this ONLY if applying the change by hand (e.g. in Postico) instead of
-- running `npx sequelize-cli db:migrate`. It records the migration in
-- SequelizeMeta so a later `db:migrate` correctly treats it as applied.
--
-- OPTIONAL: the storefront dropdown sorts sizes client-side and is already
-- correct without this. This only fixes the row order in the Manage Store
-- admin table (and the raw /api/products variant order), which still reflects
-- the old sort_order values.
--
-- Prerequisites / notes:
-- * Confirm you are connected to the intended database before running.
-- * Wrapped in a transaction: any error rolls the whole thing back.
-- * Run the SELECT preview and check it before you COMMIT.

BEGIN;

-- Ranking, kept in step with backend/utils/sizeRank.js:
-- XS=0 S=1 M=2 L=3 XL=4 XXL/2X=5 XXXL/3X=6 4X=7 5X=8
-- unrecognized label = 999 (sorts last), size-less variant = 0
WITH normalized AS (
SELECT id,
upper(regexp_replace(COALESCE(size, ''), '[[:space:]._-]', '', 'g')) AS n
FROM variants
), scored AS (
SELECT id,
CASE
WHEN n = '' THEN 0
WHEN n IN ('XS', 'XSMALL', 'EXTRASMALL') THEN 0
WHEN n IN ('S', 'SMALL') THEN 1
WHEN n IN ('M', 'MEDIUM', 'MED') THEN 2
WHEN n IN ('L', 'LARGE') THEN 3
WHEN n IN ('XLARGE', 'EXTRALARGE') THEN 4
-- "XL", "XXL", "XXXL", ... -> the X count is the multiplier
WHEN n ~ '^X+L$' THEN 3 + (length(n) - 1)
-- "2X", "2XL", "5X", "5XL", ... -> leading number is the multiplier
WHEN n ~ '^[0-9]+XL?$' THEN 3 + (regexp_replace(n, '[^0-9]', '', 'g'))::INTEGER
ELSE 999
END AS rank
FROM normalized
)
UPDATE variants v
SET sort_order = s.rank,
"updatedAt" = NOW()
FROM scored s
WHERE v.id = s.id
AND v.sort_order IS DISTINCT FROM s.rank;

-- Preview: every product's sizes in their new order. Sanity-check this
-- (smallest -> largest, no 5X leading) before committing.
SELECT p.name,
string_agg(COALESCE(v.size, '(one size)'), ', ' ORDER BY v.sort_order, v.id) AS sizes_in_order
FROM products p
JOIN variants v ON v.product_id = p.id
GROUP BY p.id, p.name, p.sort_order
ORDER BY p.sort_order, p.id;

INSERT INTO "SequelizeMeta" ("name")
VALUES ('20260922120000-resort-variants-by-size.js')
ON CONFLICT DO NOTHING;

COMMIT;
32 changes: 32 additions & 0 deletions backend/utils/sizeRank.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
// Rank a size label so variants sort smallest -> largest.
//
// `size` is a free-text field in the admin panel, so this has to cope with
// every way a 5XL might get typed ("5X", "5XL", "XXXXXL") rather than matching
// a fixed list. Kept in step with the frontend's sizeRank in
// frontend/src/components/Pages/Merch/useProductPurchase.js.

const BASE_RANK = { XS: 0, S: 1, M: 2, L: 3 };
const WORD_ALIASES = {
EXTRASMALL: 'XS', XSMALL: 'XS', SMALL: 'S',
MEDIUM: 'M', MED: 'M', LARGE: 'L',
EXTRALARGE: 'XL', XLARGE: 'XL',
};

// Unknown labels sort after every recognized size, but stay well inside a
// 32-bit int so they're safe to store in variants.sort_order.
const UNKNOWN_RANK = 999;

function sizeRank(size) {
const key = String(size || '').toUpperCase().replace(/[\s._-]/g, '');
const alias = WORD_ALIASES[key] || key;
if (alias in BASE_RANK) return BASE_RANK[alias];
// "XL", "XXL", "XXXL", ... -> the X count is the multiplier
const repeated = alias.match(/^(X+)L$/);
if (repeated) return BASE_RANK.L + repeated[1].length;
// "2X", "2XL", "5X", "5XL", ... -> the leading number is the multiplier
const numeric = alias.match(/^(\d+)XL?$/);
if (numeric) return BASE_RANK.L + Number(numeric[1]);
return UNKNOWN_RANK;
}

module.exports = { sizeRank, UNKNOWN_RANK };
31 changes: 27 additions & 4 deletions frontend/src/components/Pages/Merch/useProductPurchase.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,29 @@
import { useState } from "react";
import { useMerchCart } from "../../../context/MerchCartContext";

export const SIZE_ORDER = ['XS', 'S', 'M', 'L', 'XL', 'XXL', 'XXXL'];
const BASE_RANK = { XS: 0, S: 1, M: 2, L: 3 };
const WORD_ALIASES = {
EXTRASMALL: 'XS', XSMALL: 'XS', SMALL: 'S',
MEDIUM: 'M', MED: 'M', LARGE: 'L',
EXTRALARGE: 'XL', XLARGE: 'XL',
};

// Rank a size label so anything we sell sorts smallest -> largest. Sizes are a
// free-text field in the admin panel, so this has to cope with every way a
// 5XL might get typed ("5X", "5XL", "XXXXXL") instead of matching a fixed
// list — an unrecognized label used to rank -1 and jump to the front.
export function sizeRank(size) {
const key = String(size || '').toUpperCase().replace(/[\s._-]/g, '');
const alias = WORD_ALIASES[key] || key;
if (alias in BASE_RANK) return BASE_RANK[alias];
// "XL", "XXL", "XXXL", ... -> the X count is the multiplier
const repeated = alias.match(/^(X+)L$/);
if (repeated) return BASE_RANK.L + repeated[1].length;
// "2X", "2XL", "5X", "5XL", ... -> the leading number is the multiplier
const numeric = alias.match(/^(\d+)XL?$/);
if (numeric) return BASE_RANK.L + Number(numeric[1]);
return Number.MAX_SAFE_INTEGER; // truly unknown labels go last, not first
}

// Shared size/stock/add-to-cart logic for a single product, used by both the
// grid StoreItem and the 3D booth's ProductDetail. Keeps one source of truth so
Expand All @@ -25,9 +47,10 @@ export function useProductPurchase(product) {
return sizes;
}, {});

const sortedSizes = Object.keys(availableSizes).sort(
(a, b) => SIZE_ORDER.indexOf(a) - SIZE_ORDER.indexOf(b)
);
const sortedSizes = Object.keys(availableSizes).sort((a, b) => {
const byRank = sizeRank(a) - sizeRank(b);
return byRank !== 0 ? byRank : a.localeCompare(b);
});

// Whole product is sold out when every variant has no stock.
const isSoldOut = variants.length === 0 || variants.every(v => v.stock === 0);
Expand Down
Loading