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
53 changes: 21 additions & 32 deletions src/features/api/payment-processing/create.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,8 @@ import type {
BookingIntent,
PaymentResult,
} from "#routes/api/webhook-types.ts";
import { bookingDateFields } from "#routes/public/ticket-payment.ts";
import {
soleParentPackageIds,
stampChildRowPackages,
} from "#shared/booking/page-packages.ts";
import { lineGroupId } from "#shared/booking/signed-metadata.ts";
import { orderBookings } from "#shared/booking-lines.ts";
import { capacityErrorFormatter } from "#shared/capacity-error.ts";
import { bookingBatchPlan } from "#shared/checkout-complete.ts";
import type {
Expand All @@ -31,13 +27,11 @@ import type {
import { formatCurrency } from "#shared/currency.ts";
import { logActivity } from "#shared/db/activityLog.ts";
import { getPublicStatusId } from "#shared/db/attendee-statuses.ts";
import type { ListingBooking } from "#shared/db/attendee-types.ts";
import {
type createAttendeeAtomic,
createBookingAtomic,
} from "#shared/db/attendees/api.ts";
import { ensureAllBookings } from "#shared/db/attendees/create.ts";
import { expandChildAllocations } from "#shared/db/attendees/order-parents.ts";
import {
decryptSessionTokens,
type ProcessedPayment,
Expand Down Expand Up @@ -261,33 +255,28 @@ export const createAttendeeForSession = async (
// Per-LINE paid amounts: a listing booked through two paths is two lines
// with their own prices, and each becomes its own booking row. The priced
// order's lines reference the pricing intent's item objects, which pair
// 1:1 by index with validatedItems.
// 1:1 by index with validatedItems. `paidByIntentItem.get(...)` is always
// defined for a priced item (every intent item produces a priced line), so
// the raw value flows straight through — a genuine `0` (a free line that
// was still signed) stays `0`. The conditional spread is for
// `exactOptionalPropertyTypes`: an explicit `undefined` cannot be assigned
// to an optional `number`, so `pricePaid` is omitted when absent (the DB
// layer then coerces it to `0` at insert, matching the prior `?? 0`).
const paidByIntentItem = paidByItem(pricedOrder);
const rawBookings: ListingBooking[] = validatedItems.map(
({ item, listing }, index) => ({
...bookingSlot(item),
pricePaid: paidByIntentItem.get(pricingIntent.items[index]!) ?? 0,
quantity: item.q,
...bookingDateFields(listing, intent.date, intent.dayCount),
const bookings = orderBookings({
allocations: intent.allocations,
date: intent.date,
dayCount: intent.dayCount,
lines: validatedItems.map(({ item, listing }, index) => {
const pricePaid = paidByIntentItem.get(pricingIntent.items[index]!);
return {
...bookingSlot(item),
listing,
...(pricePaid !== undefined ? { pricePaid } : {}),
quantity: item.q,
};
}),
);
// Expand summed child bookings into per-parent rows when allocations were
// carried through the signed metadata (paid-path provenance): each
// allocation becomes its own listing_attendees row with the correct
// parentListingId and proportional pricePaid, mirroring the free-path
// behaviour in createFreeReservation. Each child row is then stamped with
// its parent's package when the parent books through exactly one path.
const bookings = stampChildRowPackages(
intent.allocations && intent.allocations.length > 0
? expandChildAllocations(rawBookings, intent.allocations)
: rawBookings,
soleParentPackageIds(
intent.items.map((item) => ({
listingId: item.e,
packageGroupId: lineGroupId(item),
})),
),
);
});
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
const fullTotal = pricedOrder.fullSubtotal;
const depositTotal = orderLineTotal(pricedOrder);
const remainingBalance =
Expand Down
2 changes: 1 addition & 1 deletion src/features/api/payment-processing/store-refund.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ import type {
PaymentFailureResult,
PaymentResult,
} from "#routes/api/webhook-types.ts";
import { bookingDateFields } from "#routes/public/ticket-payment.ts";
import { bookingDateFields } from "#shared/booking-date-fields.ts";
import { logActivity } from "#shared/db/activityLog.ts";
import { createAttendeeAtomic } from "#shared/db/attendees/api.ts";
import { settleAttendeeBalance } from "#shared/db/attendees/balance.ts";
Expand Down
24 changes: 1 addition & 23 deletions src/features/public/ticket-payment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ import {
stampChildRowPackages,
} from "#shared/booking/page-packages.ts";
import type { BookingTree } from "#shared/booking/tree.ts";
import { capacityDateFor } from "#shared/capacity-rules.ts";
import { bookingDateFields } from "#shared/booking-date-fields.ts";
import { bookingBatchPlan } from "#shared/checkout-complete.ts";
import type { PricedOrder } from "#shared/checkout-pricing.ts";
import { getBookableStartDates, isBookingRangeValid } from "#shared/dates.ts";
Expand Down Expand Up @@ -97,7 +97,6 @@ import {
type Group,
type Holiday,
type ListingWithCount,
normalizeDurationDays,
} from "#shared/types.ts";
import { parsePositiveInt } from "#shared/validation/number.ts";
/* jscpd:ignore-start */
Expand Down Expand Up @@ -201,27 +200,6 @@ export const checkAvailability = (
date,
);

/**
* Shared booking-date fields (date + durationDays), keeping the payment and
* webhook flows aligned. Span: customisable listings use the chosen `dayCount`;
* daily listings use their fixed `duration_days`; standard listings span 1 day.
*/
export const bookingDateFields = (
listing: Pick<
TicketListing["listing"],
"listing_type" | "duration_days" | "customisable_days"
>,
date: string | null,
dayCount = 1,
): { date: string | null; durationDays: number } => ({
date: capacityDateFor(listing.listing_type, date),
durationDays: listing.customisable_days
? normalizeDurationDays(dayCount)
: listing.listing_type === "daily"
? normalizeDurationDays(listing.duration_days)
: 1,
});

/** Load one group's package pricing and shape it into the {@link PagePackage}
* the booking flow carries — the group's display fields plus its member
* quantity/price maps, scoped to the members actually on the page. */
Expand Down
52 changes: 52 additions & 0 deletions src/shared/booking-date-fields.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
/**
* Shared booking date and duration rules — the single definition of how a
* booking row's `date` and `durationDays` are derived from a listing's type
* and the buyer's chosen span. Both the payment flows (paid webhook,
* store-and-refund placeholder) and the public availability/free-booking
* paths route through here so a listing's range policy can never drift between
* them.
*
* This module is pure: callers pass the listing facts and the chosen date/day
* count, it returns the two fields. No database, no settings.
*/

import { capacityDateFor } from "#shared/capacity-rules.ts";
import type { ListingWithCount } from "#shared/types.ts";
import { normalizeDurationDays } from "#shared/types.ts";

/** The listing facts the row builder reads to derive a booking's date and
* duration. Narrower than the full listing so the helper stays pure over the
* fields it actually consumes. */
export type BookingDateSource = Pick<
ListingWithCount,
"listing_type" | "duration_days" | "customisable_days"
>;

/**
* Shared booking-date fields (date + durationDays).
*
* Span rules, one declaration:
* - A `customisable_days` listing spans the chosen `dayCount`.
* - A non-customisable `daily` listing spans its fixed `duration_days`.
* - A `standard` listing spans one dateless day (no range column).
*
* `dayCount` defaults to `1`, and {@link normalizeDurationDays} clamps
* non-finite input back to `1`, so a genuinely optional `dayCount` (a legacy
* signed session without `day_count`, modelled as `undefined` on
* `BookingIntent`) flows through that default unchanged — missing day count
* still means one day. `capacityDateFor` drops the date for date-less
* (standard) listings whose own cap is a running total, never a per-date
* count.
*/
export const bookingDateFields = (
listing: BookingDateSource,
date: string | null,
dayCount = 1,
): { date: string | null; durationDays: number } => ({
date: capacityDateFor(listing.listing_type, date),
durationDays: listing.customisable_days
? normalizeDurationDays(dayCount)
: listing.listing_type === "daily"
? normalizeDurationDays(listing.duration_days)
: 1,
});
109 changes: 109 additions & 0 deletions src/shared/booking-lines.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
/**
* The canonical signed paid booking rows — one representation of what a
* completed, correctly-priced order writes to `listing_attendees`, shared by
* ordinary payment completion. The later staged-checkout runtime will reach
* the same rows through the same builder, which is why the builder is pure
* over its inputs (the only impurity is the single order-token UUID the
* expansion mints, mirroring the in-memory token main's rows already share).
*
* Behaviour kept identical to main's paid webhook path:
* - one row per signed line, carrying listing, quantity, date, duration,
* package path, and paid price, in input order;
* - child allocations expand into one row per (child, parent), preserving
* total quantity and exact total paid price (the last split row absorbs
* the rounding residue) and sharing one order token;
* - a folded child is stamped with its parent's package ONLY when that parent
* books through exactly one path — mixed and standalone parent paths do
* not falsely stamp children;
* - a genuine `pricePaid: 0` (a free line that was still signed) is kept
* distinct from an omitted price, so the ledger never confuses "free"
* with "unpriced".
*/

import {
soleParentPackageIds,
stampChildRowPackages,
} from "#shared/booking/page-packages.ts";
import {
type BookingDateSource,
bookingDateFields,
} from "#shared/booking-date-fields.ts";
import type {
ChildAllocation,
ListingBooking,
} from "#shared/db/attendee-types.ts";
import { expandChildAllocations } from "#shared/db/attendees/order-parents.ts";

/** One signed paid line: the booking slot (listing id + package path), the
* quantity, the listing's date/duration facts, and the line's charged
* amount — everything {@link orderBookings} needs to build one canonical
* {@link ListingBooking} row before child-allocation expansion.
*
* The slot's `packageGroupId` is `0` for a standalone line and the package's
* group id for a line booked through a package — the same `packageGroupId 0`
* contract the existing writers expect. `pricePaid` carries the distinction
* the ledger depends on: a genuine `0` stays `0`; an `undefined` line
* carries no price and is written to no row's `pricePaid`. */
export type SignedPaidLine = {
listingId: number;
packageGroupId: number;
quantity: number;
/** The listing facts that derive the row's `date`/`durationDays`. */
listing: BookingDateSource;
/** The line's charged amount in minor units, or `undefined` when the line
* carries no price. */
pricePaid?: number;
};

/** Input to {@link orderBookings}: the signed paid lines plus the order's
* shared date, day count, and per-(child, parent) allocations. */
export type OrderBookingsInput = {
lines: SignedPaidLine[];
date: string | null;
/** Visitor-chosen day count for "customisable days" listings. Absent or 1
* when no selected listing is customisable — modelled as optional to
* mirror the genuinely optional `BookingIntent.dayCount` (a legacy session
* without `day_count` still means one day via {@link bookingDateFields}'s
* default). Typed `number | undefined` (not bare `?: number`) so an
* intent's `dayCount` can be passed through directly under
* `exactOptionalPropertyTypes`. */
dayCount?: number | undefined;
/** Per-(child, parent) allocations from the fold, carried through the signed
* metadata. Absent or empty for legacy/no-parent orders. Typed
* `ChildAllocation[] | undefined` so an intent's `allocations` can be
* passed through directly under `exactOptionalPropertyTypes`. */
allocations?: ChildAllocation[] | undefined;
};

/**
* Build the canonical signed paid booking rows from a validated, priced order.
*
* Each line becomes one row carrying its listing, quantity, date, duration,
* package path, and paid price; child lines expand into per-parent rows when
* allocations are present; each folded child is stamped with its parent's
* package only when that parent books through exactly one path (see
* {@link soleParentPackageIds}). Preserves input order, exact total paid price
* (the last split row absorbs the rounding residue), the `pricePaid: 0`
* versus omitted distinction, and one shared order token across every
* expanded row.
*/
export const orderBookings = (input: OrderBookingsInput): ListingBooking[] => {
const { lines, date, dayCount, allocations } = input;
const rawBookings: ListingBooking[] = lines.map((line) => ({
listingId: line.listingId,
packageGroupId: line.packageGroupId,
quantity: line.quantity,
...bookingDateFields(line.listing, date, dayCount),
...(line.pricePaid !== undefined ? { pricePaid: line.pricePaid } : {}),
}));
return stampChildRowPackages(
allocations && allocations.length > 0
? expandChildAllocations(rawBookings, allocations)
: rawBookings,
// soleParentPackageIds reads each line's package path; a SignedPaidLine
// already carries packageGroupId (0 = standalone, dropped; N = a sole
// package, kept), so the lines can be passed directly — matching main's
// per-line package-group derivation.
soleParentPackageIds(lines),
);
};
34 changes: 22 additions & 12 deletions src/shared/db/attendees/order-parents.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,15 +108,23 @@ const splitPricePaid = (
};

/** Expand one booking into its rows: one per `(child, parent)` allocation
* (carrying that parent), plus — for any units the allocations don't cover — a
* single parent-less remainder row. A booking with no allocation stays one
* standalone row. `pricePaid` is split across the rows by {@link splitPricePaid}. */
const expandBooking = (
booking: ListingBooking,
* (carrying that parent), plus — for any units the allocations don't cover — a
* single parent-less remainder row. A booking with no allocation stays one
* standalone row. `pricePaid` is split across the rows by {@link splitPricePaid}.
*
* Generic over `T extends ListingBooking` so a caller that carries extra
* required row fields through the booking keeps them on every expanded row —
* the spread copies all of `booking`'s own properties and only overrides the
* `ListingBooking`-compatible members (parent, quantity, price, token). The
* cast is the standard workaround for TypeScript's inability to prove a
* generic object spread is assignable back to its parameter; the spread
* structurally preserves `T`, so the assertion is sound. */
const expandBooking = <T extends ListingBooking>(
booking: T,
childAllocs: readonly { parentId: number; qty: number }[] | undefined,
orderToken: string,
): ListingBooking[] => {
if (!childAllocs) return [{ ...booking, orderToken }];
): T[] => {
if (!childAllocs) return [{ ...booking, orderToken }] as T[];
const totalQty = booking.quantity ?? 1;
const allocatedQty = childAllocs.reduce((sum, a) => sum + a.qty, 0);
const remainderQty = totalQty - allocatedQty;
Expand All @@ -135,7 +143,7 @@ const expandBooking = (
quantity: row.qty,
...(row.parentId !== undefined ? { parentListingId: row.parentId } : {}),
...(prices[i] !== undefined ? { pricePaid: prices[i] } : {}),
}));
})) as T[];
};

/**
Expand All @@ -152,12 +160,14 @@ const expandBooking = (
* the latter recomputes parentListingId as "first in-order parent" (lossy for
* multi-parent), this function uses the allocation list to record the exact
* parent for each unit. Used by both the free path and the paid webhook path,
* which thread the allocation through the round-trip.
* which thread the allocation through the round-trip. Generic over
* `T extends ListingBooking` so any required row fields a caller carries on
* each booking survive the expansion.
*/
export const expandChildAllocations = (
bookings: ListingBooking[],
export const expandChildAllocations = <T extends ListingBooking>(
bookings: T[],
allocations: ChildAllocation[],
): ListingBooking[] => {
): T[] => {
const orderToken = crypto.randomUUID();
const allocByChild = new Map<number, { parentId: number; qty: number }[]>();
for (const alloc of allocations) {
Expand Down
Loading