Skip to content
TomkooooPublic

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

tbook

Standalone rebuild of the multi-tenant event/tournament booking platform (previously a plugin inside webshop-engine). See /Users/tomko/.claude/plans/giggly-discovering-elephant.md for the full architecture and phased rollout plan this scaffold implements.

Layout

apps/web/           Next.js app (App Router): storefront + admin route groups, api/v1 + api/v2
packages/schemas/    Zod schemas — single source of truth for entity + API shapes
packages/db/         Mongoose connection + models + repositories
packages/domain/     Pure business logic (pricing, eligibility, VAT, wizard-flow)
packages/services/   Orchestration: booking, checkout, voucher, invoice, org/RBAC, tDarts sync
packages/actions/    Request-layer: auth/permission checks, input validation, error mapping

Request layering: route.ts → actions/* → services/* → domain/* + db/repositories/* → db/models/*.

Requirements

  • Node >= 20
  • A MongoDB instance. Production must point DATABASE_URL at the existing tbook-admin database to stay backwards compatible.

Development

npm install --legacy-peer-deps  # vitest's peer graph trips an npm/arborist bug without this
cp apps/web/.env.example apps/web/.env.local   # fill in DATABASE_URL etc.
npm run dev

Scripts

  • npm run lint / npm run typecheck / npm run build
  • npm run test:unit — unit + component tests (Vitest, no external services)
  • npm run test:integration — API/DB tests against mongodb-memory-server
  • npm run test:concurrency — race-condition tests (e.g. booking capacity)

A Husky pre-push hook runs lint + typecheck + unit tests + build before anything reaches the remote.

Managing production data from the CLI

scripts/tbook-cli replaces hand-editing production documents (the kind of incident backups/tdarts-fix-* and backups/tdarts-rebuild-* recorded) with a scoped, audited tool. It never touches Mongoose or the database directly — every read and write goes through @tbook/services (catalog-admin-service, booking-admin-service), the same functions the admin console calls, so organization scoping and business invariants (capacity floors, day-pass rules, …) are enforced exactly as they are there.

npm run tbook-cli -- event list --org horror-weeks
npm run tbook-cli -- event show --org horror-weeks --id <eventId>
npm run tbook-cli -- event edit --org horror-weeks --id <eventId> --set capacity=300
npm run tbook-cli -- booking resend-voucher --org horror-weeks --id <bookingId>

event create/event edit also take --day-pass-json <file>: the day-pass event's whole dayPass config (prices, schedule, discount codes — the full shape in @tbook/schemas' dayPassConfigSchema) as one JSON file, since a day-pass event is unusable without it. group list/group edit cover an event group's own scalar fields (e.g. --set status=active to publish a draft group — a group must be active for its API key to authenticate v1 requests). group keys shows the API key hint and the dev preview key (--reveal-preview), and issues new keys (--rotate-preview, --rotate-api-key; printed once, --confirm ROTATE). The API key is stored only as a hash, so it can't be shown again. setup apply --update brings an existing event's module grants, module settings and emails in line with its plan file without touching the event's own fields (--confirm UPDATE). booking purge-test --event <id> deletes an event's test data (v1 X-TBook-Test bookings, their tickets and ID claims, test waitlist entries, test survey answers, email log rows); dry run lists it, --apply --prod-ack --confirm PURGE deletes, sends no email and leaves live counters alone.

data list | rows | append | delete-row manage data lists (employee rosters, VIP name lists): data append --list <id|name> --file <x.xlsx|csv> [--sheet <name>] [--map <column>=<A|1>]... [--from-row n] [--update] adds rows from a spreadsheet without replacing the list (the dry run shows each row as ADD / already in list / repeated), data delete-row --key <key> --confirm DELETE removes one.

Safety model, enforced the same way for every command and every entity added later:

  • Dry run by default. Omitting --apply only prints the plan (for an edit: the before/after of each field) and writes nothing.
  • This CLI always treats the connected database as production — regardless of its name. Writing requires both --apply and --prod-ack.
  • No "yes to all." Every changed field is confirmed on its own — interactively, one prompt per field, or, off a TTY, by passing --confirm-field <name> once for each field that actually changed. archive (the soft-delete — there is no hard delete) additionally requires typing the record's own name back via --confirm-name.
  • Every write leaves a restore point under backups/cli/<entity>- <action>-<id>-<timestamp>/ (gitignored, like the rest of backups/): the affected document(s) before and after, and an audit entry (who, from --operator, TBOOK_CLI_OPERATOR, or the local git identity; when; what changed). event undo --dir <that path> reverses it by replaying the "before" state through the same service calls — undoing a create archives the record, since there is still no hard delete.
  • Always scoped to one --org (id or slug) — there is no cross-org or "all organizations" mode.

Structured sub-fields (an event's pricingRules, attendeeFieldSchema, eligibility rules) aren't editable from the CLI yet — use the admin console for those. dayPass is the exception: --day-pass-json <file> above. Sending a voucher email (booking resend-voucher) can't be undone by anything; the CLI says so and asks for a typed RESEND instead of a field diff.

Refreshing a dev database from production

node scripts/migrate/clone-database.mjs --uri mongodb://host:27017/ \
  --from tbook-admin --to tbook-dev            # dry run: prints the plan
node scripts/migrate/clone-database.mjs --uri mongodb://host:27017/ \
  --from tbook-admin --to tbook-dev --yes      # perform the copy

# REQUIRED before exercising any payment flow against the copy:
node scripts/migrate/sanitize-dev-database.mjs --uri mongodb://host:27017/ --db tbook-dev

DATABASE_URL=mongodb://host:27017/tbook-dev npm run backfill:capacity

Sanitize before testing. A faithful clone carries every organization's real credentials — the Számlázz.hu agent key, the SMTP password, the Stripe secret key, the tDarts partner secret. Marking one booking paid in such a database runs the full after-payment pipeline, which would issue a real invoice, email a real customer and enrol someone into a real tournament roster. sanitize-dev-database.mjs disables those integrations and clears any configured webhook endpoints; pass --redirect-email you@example.com to also point every customer address at yourself so voucher delivery can be exercised safely.

Note that a faithful copy carries real customer names, emails and phone numbers into the dev database — treat it accordingly.

Launching against the legacy database

soldGuestCount on tbookevents is authoritative in this rebuild — eventRepository.reserveCapacity guards capacity with it to close the legacy oversell race — but it was vestigial in the legacy plugin, which re-aggregated bookings on every check. So before pointing this app at a real tbook-admin database, reconcile the counter or every event will read as fully available:

DATABASE_URL=mongodb://host/tbook-admin npm run backfill:capacity -- --dry-run
DATABASE_URL=mongodb://host/tbook-admin npm run backfill:capacity

It is idempotent and safe to re-run (and should be re-run after any out-of-band booking edit made directly in the database). Pass --all-events to also reconcile events with no capacity cap, or --event=<id> --dry-run to compare one event's counters with its real guest count without writing anything.

The counters count guests, not bookings: a booking of 3 guests holds 3 places. soldGuestCount = live (pending, checkout_started, paid, confirmed), non-test bookings' guests minus their VIP guests, plus the places held for open waitlist offers. vipSoldCount = their VIP guests. The app keeps soldGuestCount even for an event without a cap, and recounts it when a cap is first set.

Managing registrations

The admin console covers the cases the storefront cannot:

  • Register by hand (/admin/events/[eventId]/bookings/new) — individual or team/pair entries. The event's own registrationUnit / playersPerTicket / teamMemberFieldSchema drive the form, so a pairs event asks for both players and a 5-a-side team asks for its roster. Four rules can be knowingly overridden (closed sales window, inactive event, over capacity, eligibility), each off by default.
  • Record a payment taken outside the platform — bank transfer, cash, or a comped entry, with a reference and note, attributed to the manager who recorded it. This runs the same after-payment pipeline a Stripe webhook does, so entries, the invoice and the integrations all happen as normal.
  • Edit contact details and attendee/roster data — renaming an attendee re-points their entry ticket. Entries already checked in are left alone (they record who was admitted) and reported as skipped.
  • Attach an invoice number and PDF issued from another system, for an org that invoices from its own accounting software or whose automatic Számlázz.hu issue failed.

tDarts: enrolment happens automatically on payment. Correcting a name or withdrawing a cancelled entry is not yet possible — the tDarts partner API is create-only. The console surfaces a warning when an edit leaves the tournament roster stale; see docs/tdarts-partner-api-requirements.md for the two endpoints that would close this.

Integrations (outbound webhooks)

Wiring tBook to another system (Zapier/Make/n8n, a CRM, a Slack relay, your own service) is configuration, not a code change: add an endpoint under Admin → Integrations (or POST /api/v2/admin/webhooks) and subscribe it to booking.paid, booking.cancelled and/or voucher.checked_in.

Each delivery is a POST carrying X-TBook-Event, X-TBook-Delivery and X-TBook-Signature: sha256=<hex HMAC-SHA256 of the raw body> — the same scheme Stripe and GitHub use. Verify against the raw body before parsing, and compare in constant time. The signing secret is shown once at creation and is unrecoverable afterwards.

Deliveries are best-effort and not retried: a failing endpoint must never block a booking from being paid or cancelled. Each endpoint's last status is recorded and shown in the console, so a broken integration is visible without log access.

For integrations that need to run inside the app rather than over HTTP, the extension point is AFTER_BOOKING_PAID_HOOKS in packages/services/src/checkout-service.ts — invoicing, tDarts sync, voucher delivery and webhook dispatch all register into it the same way.

Day-pass events

An event with kind: "day_pass" sells passes for individual days of a long run (say a month), at a weekday or weekend price, with a capacity per day. Backwards compatible: every existing event is kind: "standard" and behaves exactly as before.

On the public API, GET /api/v1/events returns kind and, for a day-pass event, dayPass.days[] — { date, weekend, unitPriceGrossHuf, remaining, closed, bookable } per day (sold counts are never exposed). The buyer's basket travels in selections:

POST /api/v1/quote   (and POST /api/v1/bookings)
{ "eventId": "…", "guests": 1, "customer": { … },
  "selections": { "dayPasses": { "2026-07-04": 2, "2026-07-05": 1 } } }

guests is ignored for a day-pass event — the size of the basket decides it. Reserving the basket is all-or-nothing: every day's counter lives on the event document, so one atomic update checks and increments them all (eventRepository.reserveDayCapacity). Each ticket becomes a voucher dated to its day; the door scanner answers wrong_day outside that date (the venue's time zone is Europe/Budapest).

A day-pass event can also carry dayPass.weekdaySchedule / weekendSchedule ({ openTime, closeTime }, display only — not enforced against bookability) and dayPass.discountCodes[] ({ code, label, percentOff, enabled }): a percent-off a buyer enters at checkout (discountCode on /quote//bookings, see docs/storefront-api.md) or a seller picks from a dropdown at Point of sale. All editable from the console (event → Tickets → Day pass pricing) or the CLI via event create/event edit --day-pass-json <file> (see below).

Check-in display (kivetítő)

A projector screen at the entrance (module checkin-display): the number of guests checked in and a greeting for each guest as they are checked in at the door (scanner or roster). What it says is module config, set in the event's Modules card — no code change: greeting / subGreeting templates ({{name}}, {{firstName}}, {{lastName}}, {{field.<key>}}), name order, counter label and total (registered or a number), theme, colours, logo URL, animation, greeting length.

At the venue: Event → Display → Create display link, open the link (or scan the QR) on the computer connected to the projector, press Teljes képernyő. Send a test greeting shows a sample on the open screens before doors open (no guest, counter unchanged). The screen polls every 2 s, keeps its last state through network blips, and only rendered greeting text leaves the server. A new link switches the old one off; switching the module off closes the screen.

Name cloud (nameCloud, on by default): after its turn each big name flies small into a cloud of everyone already in; an idle screen shows the headline and the cloud. A (re)opened screen fills the cloud from the feed (?cloud=1, re-read every 5 min), so a reload doesn't empty it. One font size for all names, as large as fits; below a readable minimum only the newest names are shown and older ones fade (lib/display-cloud.ts). With the cloud on the feed also carries each guest's full name (the cloud shows it); with it off only the rendered greeting text leaves the server.

Entrances (gates, e.g. A, B): each door device picks its Bejárat on the Check-in page (kept in that browser's localStorage per event); scans and roster check-ins store it on the voucher (checkedInGate, cleared on undo, also in the arrivals export and v2 POST /api/v2/admin/vouchers/scan gate). A display opened with ?gate=A shows only entrance A's arrivals and cloud, plus check-ins without an entrance; without ?gate (or with an unknown one) it shows every entrance, as before. The screen's hidden controls also offer the entrance buttons. Counter: every entrance (default) or counterScope: gate. Create display link also shows one link + QR per entrance.

Own design: Event → Display → Background picture uploads a picture (sharp → ≤3840×2160 WebP, blob kind display-background, kept in the event's module config as backgroundImage: /media/<hash>.webp; the blob sweep keeps it), served to the screen token-gated at /api/display/[token]/background. backgroundImage may also be an https link. Cover-fit, so 16:9 fills a 4K and a 1080p TV. nameColor (solid colour instead of the shine), headlineColor, cloudColor; headline takes | for a line break; hide the counter with showCounter: no, the logo by leaving logoUrl empty.

Point of sale

/admin/sales lists today's events first; /admin/events/[eventId]/sales is the seller screen (for a day-pass event, pick the days), take cash or card, enter the customer and billing details. The sale is recorded as paid (source: "pos"), the ticket PDF is emailed, the Számlázz.hu invoice is issued with the real payment method and its PDF is emailed too. A seller needs the sale:create permission; booking:manage also works, so existing Owner roles can sell without a role edit. A seller can never override capacity or the sales window.

Products and shared stock

Merchandise lives in tBook (Products in the console): products with options like size and colour, a SKU and stock per variant, and a log of every stock change. The counter sells it under Point of sale → Merch (cash or a card on the myPOS terminal, then a printed Számlázz.hu receipt). The webshop sells the same stock through the inventory API: it reserves stock at checkout, commits when the order is paid, and releases it if abandoned. Invoicing, orders and shipping for web orders stay in the webshop. Contract: docs/inventory-api.md; building a site on it: docs/site-integration-guide.md.

Files and storage

tBook writes no files to disk. Everything lives in MongoDB, so one database backup covers it all:

What Where
Product images, ticket pictures, manually attached invoice PDFs tbookblobs: content-addressed (id = SHA-256), deduplicated, with owner organization and kind. Served publicly only for product images (/media/<hash>.webp)
Ticket (voucher) PDFs Not stored: rendered on demand from the booking. Only the QR token matters at the door
Számlázz.hu invoice and receipt PDFs Not stored: downloaded from Számlázz.hu when needed (the just-issued one is used directly)

Unreferenced blobs are removed automatically: the app collects every reference (products, ticket layouts, header images, bookings) and deletes blobs nothing points at once they are over 7 days old.

No volume is needed for the app container.

Backwards compatibility

  • Same MongoDB collections/fields as the legacy plugin (see scripts/migration-fixtures/ for real anonymized legacy documents used in the compatibility test suite).
  • The legacy public API path /api/plugins/t-book/* is rewritten to /api/v1/* (see apps/web/next.config.ts) so the still-running Sörfeszt and World Darts Festival storefronts need no changes.
  • /api/v2/* is the new contract for this rebuild's own frontend.

Deployment

Dockerfile builds a standalone Next.js image (multi-stage, non-root user). portainer.stack.tbook.example.yml is the deployment template — copy it to a gitignored portainer.stack.tbook.yml, fill in secrets, and deploy via Portainer. Never commit the filled-in file.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages