compose.yml backend service now reads the root ./.env (which README instructs users to create) instead of the nonexistent backend/.env. Promote R2_ACCESS_KEY/R2_SECRET_KEY/R2_BUCKET/R2_PUBLIC_URL to active vars (prod S3 reads all four via getEnv) and document the webhook URL/signature-key exact-match requirement with fail-closed (503/403) wording.
Crussell
Nail salon booking platform — Go 1.26.5 backend + SvelteKit 5 SPA + PostgreSQL 17 + Docker. Built for a UK sole-trader nail artist. UK-only (Cloudflare geo-block), UK phone format. All timestamps UTC-normalised — the backend's clock.Now() returns UTC, the DB connection uses timezone = "UTC", and the frontend converts between UTC and wall-clock time client-side. Single-employee business.
Features
Booking: Self-service (customer), walk-in (admin), call-in (admin). Slot reservations prevent double-booking (4 TTL types). Self-blocking prevention: excludeUserID parameter filters a user's own RESERVATION entries from time blocker overlap checks, allowing re-reservation and booking at overlapping slots. Explicit cancellation: DELETE /api/bookings/reserve releases a user reservation; DELETE /api/admin/bookings/reserve releases an admin walk-in/call-in reservation. Background cleanup: Centralised cron scheduler (backend/internal/jobs/) runs 22 maintenance jobs: reservation/deposit cleanup every 5min, hourly campaign transitions, daily unpaid-booking notifications, staged default hours auto-apply, GDPR anonymization, financial aggregation, and token/code cleanup. Guest accounts with GDPR-compliant anonymization (including RESERVATION:edit_request:% scrubbing). Service eligibility based on age + patch test validity. Overlap checks use FOR UPDATE row locks inside transactions. Closing-hours validation (closing_time.go) resolves both current and staged default hours.
Payments: Square Terminal (in-person, via CreateTerminalCheckout) + online card payments via saved cards or new cards tokenized through the Square Web Payments SDK (cnon: nonces — gated off in local dev until VITE_SQUARE_APPLICATION_ID/VITE_SQUARE_LOCATION_ID are set). The backend accepts only tokens, never raw PANs (PCI-DSS parity, mirrored in the dev mock). Cash with change calculation. Gift cards (12-digit code or account balance). Saved cards for faster checkout. Tips on completed bookings. Refunds with notice-period tiers and deposit protection (72h/24h thresholds). All payment types: deposit, full, partial, balance, tip. Payment >20% of total promotes pending_release bookings back to confirmed. Deposit paid is computed from payments on-the-fly. The first 50% of each payment is always carved out as deposit (via buildSplitRecords); any overflow beyond the booking total becomes a tip. A PostgreSQL pg_advisory_lock serializes payment attempts per-booking to prevent two-tab double-payment races. Gift card purchases insert a pending payment record with VAT before calling Square — the DB transaction commits first, so Square failures leave a retryable pending record (same-key retries reuse it). Two background sweeps close Square's ~24h idempotency-key retention window: sweep-pending-square-refunds reconciles/retries stuck refunds (with a 23h age guard), and sweep-stale-pending-payments fails stale pending payments/till-sales so a late retry cannot issue a second charge.
Gift Cards: Multi-method purchase (cash, card machine, online card, giveaway). Inventory cards for stock management. 24-month rolling expiry. Idle account cleanup (2yr/5yr thresholds). Expired balance recovery with admin audit trail. Transaction audit log. Idempotency keys for purchases.
Scheduling: Default weekly hours, holiday/exceptional groups, time blockers (one-off + recurring with cron), staged default hours changes (schedule future changes with effective date picker, conflict detection, and auto-apply at midnight). Lunch protection. Late-night lock (22:00–11:00). Admin schedule page (Google Calendar-style week view).
Custom Services: One-off or special-request services not in the permanent catalog. Admin management with create, edit, promote to permanent service (migrates booking references), and delete. Full CRUD API with search, popular sorting, and pagination. Can be added to any booking alongside regular services.
Admin: Today page with interactive calendar grid. Booking management (create, edit, reschedule, approve, cancel). User management with customer relationship data (spend, visits, top services). Custom services (one-off services with create/edit/promote/delete). Discount campaigns (time-based and milestone). Time blocker CRUD. Portfolio image upload with tag management. Gift card management. Business settings (VAT, gift card config). Notification queue with priority ordering.
Loyalty & Discounts: 1 stamp per paid appointment (max 1/day). 10 stamps → 10% off via opt-in checkbox at payment or till. Stamps refunded on cancellation. Campaigns auto-apply at both payment and completion: time-based, per-user milestone, global milestone (in-person only), anniversary. All discounts stack additively against original total. Discount payment records excluded from refund calculations.
Compliance: GDPR Article 15 data export (async, 12h cache, 23-section JSON + PDF — excludes verification codes as authentication tokens). Account deletion with external system scrubbing (S3, Square). Guest PII anonymized 6 months post-appointment. UK financial data retention (7 years). Gift card SPV/MPV VAT treatment configurable.
Frontend: Portfolio gallery with fuzzy tag search (relevance-sorted) and exact category filters (date-sorted), multi-format images (AVIF/WebP/JPEG/JXL with WASM client-side encoding), cursor-based pagination. MapLibre GL map on contact page. PhoneInput component with UK validation. CharCounter for long notes.
Infrastructure: Docker Compose (postgres, backend, sabredav, nginx). Dev mock for Square payments (//go:build dev) that mirrors production PCI-DSS behaviour (rejects raw PANs; accepts cnon:/ccof: tokens only). RustFS dev storage, Cloudflare R2 for prod. SabreDAV CardDAV sync for profile photos.
Middleware: JsonContentType sets Content-Type: application/json globally, replacing ~80+ individual w.Header().Set() calls. RespondJSON/RespondError helpers standardise API response format. Progressive rate limiting (dual-window) on login/register with account lockout.
Limitations
- Single employee — no multi-staff scheduling, no team management
- No email/SMS — SMTP integration not wired; booking reminders, password resets, and notifications are UI-only
- No production S3/R2 — prod storage stubs return "not implemented"
- No social auth — OAuth providers (Google, Microsoft, Facebook) not registered
- No dark mode, no PWA, no recurring bookings, no CSV export
- Password reset flow exists backend-only — no frontend link
- No error tracking/monitoring — Sentry not configured
Prerequisites
| Tool | Version |
|---|---|
| Docker & Docker Compose | >= 20.10 |
| Go | >= 1.22 |
| Node | >= 18 (npm) |
| tmux | >= 3.0 |
Getting Started
cp .env.example .env
# Edit .env — set POSTGRES_*, JWT_SECRET_KEY
docker compose up --build -d
| Service | URL |
|---|---|
| Frontend | http://localhost |
| API | http://localhost/api |
| SabreDAV | http://localhost/dav |
Local dev (tmux)
./local-dev-2.sh
Launches 4-pane tmux session: psql console, Go dev server, Svelte dev server, Rustfs logs. Seeds 20 users, 12 services, 43 bookings, guest accounts, time blockers, exceptional hours.
Default logins (password: password):
- Admin:
admin@example.com - User:
user@example.com
Building & Testing
cd backend && go build -o bin/backend ./main.go
cd frontend && npm ci && npm run build
cd backend && go test -tags "test,dev" -count=1 -parallel 8 ./... # 1,716 tests passed (4 skipped, ~13s)
cd backend && go test -tags "test,dev" -count=1 -race -timeout 480s ./... # race detector (all packages, ~4min)
cd backend && go test -tags "test,dev" -count=10 -parallel 8 ./... # thorough verification (~2-3min)
Pre-commit hooks
.githooks/pre-commit runs on every commit (configured via git config core.hooksPath .githooks):
- Frontend:
prettier --writeauto-format, theneslintall files - Backend (only if
backend/changed):go vet,golangci-lint(3m timeout),staticcheck,gosec,go mod tidycheck - Global:
gitleakssecret scan (skips gracefully if not installed)
To bypass: git commit --no-verify.
CI caching
CI caches Go modules (~/go/pkg/mod) and npm dependencies (~/.npm, node_modules) via actions/cache — keyed on go.sum and package-lock.json respectively. Cache is served by Gitea's built-in cache server at git.popertots.com. First run downloads everything (~3m35s), subsequent runs restore from cache in seconds.
Database migrations
The schema lives in init-scripts/init-script.sql and is applied automatically on a fresh volume via docker-entrypoint-initdb.d. Existing deployments must apply the payment-system delta manually (the schema is not migration-managed):
-- Refund system columns (refunds table)
ALTER TABLE refunds ADD COLUMN IF NOT EXISTS refund_attempts INT NOT NULL DEFAULT 0;
ALTER TABLE refunds ADD COLUMN IF NOT EXISTS origin VARCHAR(16) NOT NULL DEFAULT 'manual';
ALTER TABLE refunds ADD COLUMN IF NOT EXISTS idempotency_key VARCHAR(64) UNIQUE;
-- refund_failed notification reason (admin_notification_reason enum)
-- NOTE: ALTER TYPE ... ADD VALUE cannot run inside a transaction block; run on a connection with autocommit.
ALTER TYPE admin_notification_reason ADD VALUE IF NOT EXISTS 'refund_failed';
-- Refunds may now reference non-booking payments (gift-card purchase refunds)
ALTER TABLE refunds ALTER COLUMN booking_id DROP NOT NULL;
-- Terminal checkout in-flight guard + payment_type passthrough (terminal_checkouts table)
-- NOTE: CREATE TABLE is a fresh addition, not a column change. Apply before deploying
-- the terminal-payment changes or CreateTerminalPayment/GetCheckoutStatus fail at runtime.
CREATE TABLE IF NOT EXISTS terminal_checkouts (
checkout_id VARCHAR(64) PRIMARY KEY,
booking_id CHAR(12) NOT NULL REFERENCES bookings(id) ON DELETE CASCADE,
payment_type payment_type NOT NULL DEFAULT 'full',
status VARCHAR(20) NOT NULL DEFAULT 'PENDING',
amount NUMERIC(10,2) NOT NULL DEFAULT 0,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE INDEX IF NOT EXISTS idx_terminal_checkouts_booking ON terminal_checkouts(booking_id, status);
CREATE INDEX IF NOT EXISTS idx_terminal_checkouts_status ON terminal_checkouts(status);
The sweep job (internal/jobs/cleanup.go) and refunds.go cast 'refund_failed'::admin_notification_reason, so an un-migrated DB fails at runtime — apply these before deploying the payment changes.
Saved-card per-user uniqueness + Square customer provisioning (P14)
The user_saved_cards.square_card_id UNIQUE constraint is now scoped per user (UNIQUE (user_id, square_card_id)), so the same physical card saved by two users produces two independent rows instead of user B mutating user A's saved-card row. Existing deployments must swap the constraint (the auto-generated constraint name is user_saved_cards_square_card_id_key):
ALTER TABLE user_saved_cards DROP CONSTRAINT user_saved_cards_square_card_id_key;
ALTER TABLE user_saved_cards ADD CONSTRAINT user_saved_cards_user_id_square_card_id_key UNIQUE (user_id, square_card_id);
square_customer_id TEXT (nullable) was also added to user_saved_cards — populated the first time a user saves a card (Square customer provisioning, P14) and reused thereafter:
ALTER TABLE user_saved_cards ADD COLUMN IF NOT EXISTS square_customer_id TEXT;
Full Documentation
Detailed architecture, schema, admin workflows, user journeys, and backlog in obsidian/Crussell/.