Skip to content
14 changes: 3 additions & 11 deletions TODO.md
Original file line number Diff line number Diff line change
Expand Up @@ -128,17 +128,9 @@ decision, not a patch. Starting points: the dates.ts restructure in this PR;
`scripts/mutation/execution.ts` for the test stage the decision would live in.

The follow-up sweep bounded the freeze-capable loops across the rest of `src/`
(`range`/`entries`/`chunk`/`reduce` shapes; see the `#fp` `range` helper). Two
files were left out because they have **no mirror direct test suite at all**, so
the mutation gate cannot even start on them — each needs its suite built first,
then the same bounded-loop treatment:

- `src/features/admin/listings-form.ts` — `parseDayPricesFromForm`'s
`for (let n = 1; n <= maxDays; n++)` spins forever under `n++ → n--` (blank
day-price reads skip without ever ending the loop).
- `src/shared/seeds.ts` — the unique-slug count loop and the chunked attendee
loop both spin or grow without bound under a step-neutralising mutant
(`i++ → i--`, `offset += CHUNK_SIZE → /=`).
(`range`/`entries`/`chunk`/`reduce` shapes; see the `#fp` `range` helper),
including the two files that first needed mirror direct suites built
(`src/features/admin/listings-form.ts`, `src/shared/seeds.ts`).

---

Expand Down
3 changes: 2 additions & 1 deletion src/features/admin/listings-form.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
*/

/* jscpd:ignore-start */
import { range } from "#fp";
import { projectCatalogFields } from "#shared/catalog-fields/definition.ts";
import {
type ListingInput,
Expand Down Expand Up @@ -107,7 +108,7 @@ const parseDayPricesFromForm = (
maxDays: number,
): DayPrices => {
const result: DayPrices = {};
for (let n = 1; n <= maxDays; n++) {
for (const n of range(1, maxDays + 1)) {
// Optional per-day price: blank ⇒ skip (that day isn't offered). A non-blank
// value that fails to parse is caught by validateDayPricesFromForm before
// the save, so here a null result is only ever a blank.
Expand Down
15 changes: 7 additions & 8 deletions src/shared/seeds.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
* Uses batch writes for efficient database operations.
*/

import { map, sum } from "#fp";
import { chunk, map, range, sum } from "#fp";
import { encrypt } from "#shared/crypto/encryption.ts";
import { hmacHash } from "#shared/crypto/hashing.ts";
import { generateTicketToken } from "#shared/crypto/utils.ts";
Expand Down Expand Up @@ -37,14 +37,15 @@ export const SEED_MAX_ATTENDEES = 100_000;
/** Pick a random ticket quantity (1-4) */
const randomQuantity = (): number => 1 + Math.floor(Math.random() * 4);

/** Sample unit prices in minor units (e.g. pence/cents) for paid listings */
const DEMO_UNIT_PRICES = [500, 1000, 1500, 2000, 2500, 3000, 5000];
/** Sample unit prices in minor units (e.g. pence/cents) for paid listings.
* Exported so the seeds suite can pin the exact set a paid listing draws from. */
export const DEMO_UNIT_PRICES = [500, 1000, 1500, 2000, 2500, 3000, 5000];

/** Generate slugs that are unique within the batch */
const generateUniqueSlugs = async (count: number): Promise<SlugWithIndex[]> => {
const usedSlugs = new Set<string>();
const results: SlugWithIndex[] = [];
for (let i = 0; i < count; i++) {
for (const _slot of range(0, count)) {
const result = await generateUniqueSlug(hmacHash, (slug) =>
Promise.resolve(usedSlugs.has(slug)),
);
Expand Down Expand Up @@ -232,17 +233,15 @@ export const createSeeds = async (
for (const [e, listingId] of listingIds.entries()) {
const { quantities, unitPrice } = listingData[e]!;

for (let offset = 0; offset < attendeesPerListing; offset += CHUNK_SIZE) {
const batchSize = Math.min(CHUNK_SIZE, attendeesPerListing - offset);
const chunkQuantities = quantities.slice(offset, offset + batchSize);
for (const chunkQuantities of chunk(CHUNK_SIZE)(quantities)) {
const statementPairs = await Promise.all(
map((q: number) => prepareAttendee(listingId, q, unitPrice))(
chunkQuantities,
),
);
// Each booking locates its attendee by the caller-supplied stable token.
await executeBatch(statementPairs.flat());
totalAttendees += batchSize;
totalAttendees += chunkQuantities.length;
}
}

Expand Down
201 changes: 201 additions & 0 deletions test/features/admin/listings-form.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,201 @@
import { expect } from "@std/expect";
import { describe, it as test } from "@std/testing/bdd";
import {
buildCreateListingResource,
buildUpdateListingResource,
extractListingAggregateValues,
parseGroupIds,
} from "#routes/admin/listings-form.ts";
import { VALID_DAY_NAMES } from "#shared/day-names.ts";
import { getDb } from "#shared/db/client.ts";
import { getListingDayPrices } from "#shared/db/listing-prices.ts";
import { computeSlugIndex } from "#shared/db/listings/table.ts";
import type { Listing } from "#shared/types.ts";
import { describeWithEnv } from "#test-utils/db.ts";
import { createTestGroup } from "#test-utils/db-helpers/groups.ts";
import {
type TestFormValues,
testFormParams,
} from "#test-utils/form-values.ts";
import { featureSetting, withSetting } from "#test-utils/settings.ts";

const listingForm = (extra: TestFormValues = {}) =>
testFormParams({
max_attendees: "50",
max_quantity: "5",
name: "Parsed listing",
...extra,
});

const createListing = async (extra: TestFormValues = {}): Promise<Listing> => {
const form = listingForm(extra);
const result = await buildCreateListingResource(form).create(form);
if (!result.ok) throw new Error(`create failed: ${result.error}`);
return result.row;
};

const updateListing = async (
id: number,
extra: TestFormValues = {},
): Promise<Listing> => {
const form = listingForm({ slug: "kept-slug", ...extra });
const result = await buildUpdateListingResource(form).update(id, form);
if (!result.ok) throw new Error(`update failed: ${result.error}`);
return result.row;
};

describeWithEnv("listings form", { db: true }, () => {
describe("parseGroupIds", () => {
test("keeps only positive whole group ids", () => {
const form = testFormParams({ group_ids: ["3", "0", "-2", "abc", "7"] });
expect(parseGroupIds(form)).toEqual([3, 7]);
Comment thread
stefan-burke marked this conversation as resolved.
Resolved
});

test("is empty when no group is ticked", () => {
expect(parseGroupIds(testFormParams({}))).toEqual([]);
});
});

describe("extractListingAggregateValues", () => {
test("keeps exactly the two aggregate columns", () => {
expect(
extractListingAggregateValues({
booked_quantity: 7,
tickets_count: 3,
}),
).toEqual({ booked_quantity: 7, tickets_count: 3 });
});
});

describe("create", () => {
test("a minimal form makes a free standard listing open on every day", () =>
(async () => {
const row = await createListing();
expect(row.name).toBe("Parsed listing");
expect(row.listing_type).toBe("standard");
expect(row.unit_price).toBe(0);
expect(row.max_attendees).toBe(50);
expect(row.max_quantity).toBe(5);
expect(row.bookable_days).toEqual([...VALID_DAY_NAMES]);
expect(row.closes_at).toBeNull();
})());

test("a zero unit price stays an explicit zero", async () => {
const row = await createListing({ unit_price: "0" });
expect(row.unit_price).toBe(0);
});

test("a priced form stores the currency's minor units", async () => {
const row = await createListing({
max_price: "12.5",
unit_price: "12.34",
});
expect(row.unit_price).toBe(1234);
expect(row.max_price).toBe(1250);
});

test("datetimes normalize to UTC, and blanks stay blank", async () => {
const dated = await createListing({
closes_at_date: "2026-06-15",
closes_at_time: "14:30",
date_date: "2026-03-01",
date_time: "09:05",
});
expect(dated.closes_at).toBe("2026-06-15T14:30:00.000Z");
expect(dated.date).toBe("2026-03-01T09:05:00.000Z");

const blank = await createListing({ name: "Undated" });
expect(blank.closes_at).toBeNull();
expect(blank.date).toBe("");
});

test("chosen bookable days are kept as chosen", async () => {
const row = await createListing({
bookable_days: ["Monday", "Thursday"],
});
expect(row.bookable_days).toEqual(["Monday", "Thursday"]);
});

test("day prices are read for days one up to the duration only", async () => {
const row = await createListing({
day_price_1: "10",
day_price_2: "",
day_price_3: "30",
day_price_4: "40",
duration_days: "3",
});
expect(await getListingDayPrices(row.id)).toEqual({ 1: 1000, 3: 3000 });
});

test("without a duration, only the single-day price is read", async () => {
const row = await createListing({
day_price_1: "15",
day_price_2: "20",
});
expect(await getListingDayPrices(row.id)).toEqual({ 1: 1500 });
});

test("an unreadable day price rejects the save with a plain message", async () => {
const form = listingForm({ day_price_1: "abc", duration_days: "2" });
const result = await buildCreateListingResource(form).create(form);
expect(result).toEqual({
error: "Enter a valid day price for each duration, or leave it blank.",
ok: false,
});
});

test("ticked groups are saved; unticked junk ids are not", async () => {
const group = await createTestGroup({ name: "Form group" });
const row = await createListing({
group_ids: [String(group.id), "0", "-4"],
});
const links = await getDb().execute({
args: [row.id],
sql: "SELECT group_id FROM group_listings WHERE listing_id = ?",
});
Comment thread
stefan-burke marked this conversation as resolved.
Resolved
expect(links.rows.map((r) => r.group_id)).toEqual([group.id]);
});

test("builder and logistics choices stay off while their features are off", async () => {
const row = await createListing({
assign_built_site: "1",
uses_logistics: "1",
});
expect(row.assign_built_site).toBe(false);
expect(row.uses_logistics).toBe(false);
});

test("a logistics choice is kept when the feature is on", () =>
withSetting(featureSetting("logistics"), async () => {
const on = await createListing({ uses_logistics: "1" });
expect(on.uses_logistics).toBe(true);
// An unticked checkbox never reaches the form at all.
const off = await createListing({ name: "No logistics" });
expect(off.uses_logistics).toBe(false);
}));
});

describe("update", () => {
test("the slug is normalized and its lookup code recomputed", async () => {
const created = await createListing();
const row = await updateListing(created.id, { slug: " New-Slug " });
expect(row.slug).toBe("new-slug");
expect(row.slug_index).toBe(await computeSlugIndex("new-slug"));
});

test("a daily listing keeps an emptied day selection empty", async () => {
// A create with no days ticked opens every day by default...
const created = await createListing({ listing_type: "daily" });
expect(created.bookable_days).toEqual([...VALID_DAY_NAMES]);
// ...but a daily update with none ticked means "no days", and stays so.
const row = await updateListing(created.id, { listing_type: "daily" });
expect(row.bookable_days).toEqual([]);
});

test("a standard listing's emptied day selection reopens every day", async () => {
const created = await createListing({ bookable_days: ["Monday"] });
const row = await updateListing(created.id, {});
expect(row.bookable_days).toEqual([...VALID_DAY_NAMES]);
});
});
});
34 changes: 2 additions & 32 deletions test/integration/server/seeds.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,8 @@ import { describe, it as test } from "@std/testing/bdd";
import { handleRequest } from "#routes";
import { decryptAttendees } from "#shared/db/attendees/pii.ts";
import { getAttendeesRaw } from "#shared/db/attendees/queries.ts";
import { getDb } from "#shared/db/client.ts";
import { getAllListings } from "#shared/db/listings/records.ts";
import { settings } from "#shared/db/settings.ts";
import { DEMO_NAMES } from "#shared/demo/samples.ts";
import { createSeeds } from "#shared/seeds.ts";
import {
assertAdminHtml,
expectFlashRedirect,
Expand Down Expand Up @@ -150,35 +147,8 @@ describeWithEnv("server (admin seeds)", { db: true }, () => {
expect(listings[0]!.max_attendees).toBe(0);
});

test("seeds a customisable-days listing with day prices", async () => {
await createSeeds(1, 0);
const { getListingDayPrices } = await import(
"#shared/db/listing-prices.ts"
);
const listings = await getAllListings();
const customisable = listings.find((l) => l.customisable_days);
expect(customisable).toBeDefined();
// The demo day prices are 1/2/3-day counts (day prices are no longer a
// listings column — they are seeded as day_count rows in listing_prices).
const dayPrices = customisable!.day_prices;
expect(
Object.keys(dayPrices)
.map(Number)
.sort((x, y) => x - y),
).toEqual([1, 2, 3]);
// The projected value matches the stored day_count rows exactly.
expect(await getListingDayPrices(customisable!.id)).toEqual(dayPrices);
});

test("throws when public key is not configured", async () => {
// Remove public key to cause createSeeds to throw
await getDb().execute("DELETE FROM settings WHERE key = 'public_key'");
settings.invalidateCache();

await expect(createSeeds(1, 0)).rejects.toThrow(
"Public key not configured",
);
});
// The direct createSeeds contracts (day prices, price alternation, the
// missing-public-key throw) live in test/shared/seeds.test.ts.

test("can seed multiple times additively", async () => {
// First seed
Expand Down
Loading