98678ff5a3
Three threads of work land here together to close out Tier 2.
### Block H follow-ups — day-of check-in
- Scanner is now an "open on your phone" magic-link flow. Hosts on
desktop mint a scoped JWT via POST /events/{id}/scanner-ticket and
render its URL into a QR; phone scans it and lands on /scanner with
the ticket as bearer. The ticket carries Audience=scanner so it can
never substitute for a session token.
- Plus-one confirmation at the door: scan → POST /check-in/preview to
fetch guest + expected party size → confirm buttons ("Just them",
"Party of N", custom) → POST /check-in. No more silent arrival_count=1.
- Offline scan queue: failed POSTs go into an IndexedDB store and drain
on the 'online' event with poison-message protection.
- Day-of arrivals headline widget on the event overview, gated to the
host's local calendar date so it doesn't dominate the page weeks out.
- Tab nav restyled with inline heroicons + scrollable segmented control;
Check-in moves to the rightmost slot.
- PWA: manifest + service worker scoped to /scanner, generated 192/512
icons (Go scripted renderer in scripts/gen-scanner-icons.go).
- Confirmation email QR was rendering broken because html/template
rewrites data: URLs to #ZgotmplZ; mark the value as template.URL.
- Email "open your invitation" link 404'd because we had no token to
put after /rsvp/. Threaded AccessLink through the RSVPConfirmed NATS
event from the API at submit time.
### Block G remainder — geolocation + threshold preview
- Pluggable GeoResolver in the fraud engine (NullResolver, IPApiResolver
for the free ip-api.com fallback, MaxMindResolver behind GG_GEOIP_DB_PATH).
Wrapped in a Redis cache (30d TTL). Geo flows through both gRPC and
NATS scoring paths.
- geo_jump scoring feature: >500km in <1h flags ("accessed from Lagos
and Paris within 12 minutes"); >500km in <6h is a softer signal. The
existing single-signal cap keeps a lone geo_jump in MEDIUM.
- FraudScored event carries geo_country/city/lat/lon; ApplyScore uses
COALESCE so a later re-score without geo doesn't wipe earlier data.
- Threshold-slider live preview: GET /events/{id}/security/thresholds/preview
returns band counts the host's existing access events would have
fallen into under the proposed thresholds. Debounced (250ms) widget
under the Advanced sliders so the host gets concrete feedback instead
of guessing.
### Cross-cutting — audit, tier-gating, feature flags
- audit_log table + internal/audit.Recorder (async fire-and-forget on
detached context so an audit blip never fails the real action). Wired
into branding update, thresholds update, allowlist add/remove,
collaborator invite/role-change/remove, message create/send-now/cancel.
- Tier-gating: extended billing.Limits with MaxCollaborators,
CustomBranding, Scanner, Broadcasts. Free = none; Pro = 5 + all;
Business = unlimited. Gates the scanner-ticket, message create,
branding put, and collaborator invite endpoints with 402 +
structured upgrade payload. Auto-reminders, fraud detection, and
analytics deliberately stay on every tier — those are safety + visibility
features, not upsell levers.
- Feature flags: feature_flags table + internal/flags.Store with 30s
in-memory refresh, stable sha256(key + user_id) percent bucketing,
unknown-key-defaults-on. Six Tier 2 flags pre-seeded. Three handlers
(branding, broadcasts, scanner) check the kill switch ahead of the
tier gate so ops can pull a feature back without a redeploy.
### Verified
- go test ./... + fraud-engine pytest (12/12 incl. 3 new geo_jump tests + 5
new flags tests).
- docker compose build + up across api, fraud-engine, notifier, frontend.
- /health endpoints 200; migrations 0014 + 0015 applied; 6 flags
seeded; audit_log table + partial indexes confirmed.
- Fraud-engine logs confirm geo resolver kind=CachedGeoResolver provider=auto.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
136 lines
4.5 KiB
Go
136 lines
4.5 KiB
Go
package storage
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
|
|
"github.com/google/uuid"
|
|
"github.com/jackc/pgx/v5"
|
|
"github.com/jackc/pgx/v5/pgconn"
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
|
|
"github.com/alchemistkay/guestguard/internal/domain"
|
|
)
|
|
|
|
// CheckInRepo holds the check_ins table. Tier 2 Block H.
|
|
type CheckInRepo struct {
|
|
pool *pgxpool.Pool
|
|
}
|
|
|
|
func NewCheckInRepo(db *DB) *CheckInRepo {
|
|
return &CheckInRepo{pool: db.Pool}
|
|
}
|
|
|
|
type RecordCheckInParams struct {
|
|
GuestID uuid.UUID
|
|
CheckedInBy uuid.UUID
|
|
ArrivalCount int
|
|
Notes string
|
|
WalkIn bool
|
|
}
|
|
|
|
// Record inserts a check-in. The UNIQUE on guest_id surfaces a
|
|
// double-check-in as domain.ErrAlreadyCheckedIn so the scanner UI can
|
|
// show a clear "already in" message instead of a generic 500.
|
|
func (r *CheckInRepo) Record(ctx context.Context, p RecordCheckInParams) (*domain.CheckIn, error) {
|
|
if p.ArrivalCount <= 0 {
|
|
p.ArrivalCount = 1
|
|
}
|
|
const q = `
|
|
INSERT INTO check_ins (guest_id, checked_in_by, arrival_count, notes, walk_in)
|
|
VALUES ($1, $2, $3, NULLIF($4, ''), $5)
|
|
RETURNING id, guest_id, checked_in_at, checked_in_by, arrival_count, notes, walk_in
|
|
`
|
|
var c domain.CheckIn
|
|
err := r.pool.QueryRow(ctx, q,
|
|
p.GuestID, p.CheckedInBy, p.ArrivalCount, p.Notes, p.WalkIn,
|
|
).Scan(&c.ID, &c.GuestID, &c.CheckedInAt, &c.CheckedInBy, &c.ArrivalCount, &c.Notes, &c.WalkIn)
|
|
if err != nil {
|
|
var pgErr *pgconn.PgError
|
|
if errors.As(err, &pgErr) && pgErr.Code == "23505" {
|
|
return nil, domain.ErrAlreadyCheckedIn
|
|
}
|
|
return nil, fmt.Errorf("record check-in: %w", err)
|
|
}
|
|
return &c, nil
|
|
}
|
|
|
|
// ListByEvent returns every check-in on an event, newest first. Powers
|
|
// the live arrivals list on the dashboard.
|
|
func (r *CheckInRepo) ListByEvent(ctx context.Context, eventID uuid.UUID) ([]domain.CheckIn, error) {
|
|
rows, err := r.pool.Query(ctx, `
|
|
SELECT c.id, c.guest_id, c.checked_in_at, c.checked_in_by,
|
|
c.arrival_count, c.notes, c.walk_in
|
|
FROM check_ins c
|
|
JOIN guests g ON g.id = c.guest_id
|
|
WHERE g.event_id = $1
|
|
ORDER BY c.checked_in_at DESC
|
|
`, eventID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
out := []domain.CheckIn{}
|
|
for rows.Next() {
|
|
var c domain.CheckIn
|
|
if err := rows.Scan(&c.ID, &c.GuestID, &c.CheckedInAt, &c.CheckedInBy,
|
|
&c.ArrivalCount, &c.Notes, &c.WalkIn); err != nil {
|
|
return nil, err
|
|
}
|
|
out = append(out, c)
|
|
}
|
|
return out, rows.Err()
|
|
}
|
|
|
|
// Summary returns the headcount totals: how many people walked in, and
|
|
// how many were expected (sum of attending RSVPs + their plus_ones).
|
|
func (r *CheckInRepo) Summary(ctx context.Context, eventID uuid.UUID) (domain.CheckInSummary, error) {
|
|
var s domain.CheckInSummary
|
|
err := r.pool.QueryRow(ctx, `
|
|
SELECT
|
|
COALESCE(SUM(c.arrival_count), 0) AS arrived_headcount,
|
|
(
|
|
SELECT COALESCE(SUM(1 + r.plus_ones), 0)
|
|
FROM rsvps r
|
|
JOIN guests g ON g.id = r.guest_id
|
|
WHERE g.event_id = $1 AND r.response = 'attending'
|
|
) AS expected_headcount,
|
|
COUNT(c.id) AS guests_checked_in
|
|
FROM check_ins c
|
|
JOIN guests g ON g.id = c.guest_id
|
|
WHERE g.event_id = $1
|
|
`, eventID).Scan(&s.ArrivedHeadcount, &s.ExpectedHeadcount, &s.GuestsCheckedIn)
|
|
return s, err
|
|
}
|
|
|
|
// GetByGuest returns the existing check-in for a guest, or nil if none.
|
|
// Used by the scanner's preview endpoint to surface "already in" before
|
|
// the volunteer picks a party size.
|
|
func (r *CheckInRepo) GetByGuest(ctx context.Context, guestID uuid.UUID) (*domain.CheckIn, error) {
|
|
var c domain.CheckIn
|
|
err := r.pool.QueryRow(ctx, `
|
|
SELECT id, guest_id, checked_in_at, checked_in_by, arrival_count, notes, walk_in
|
|
FROM check_ins WHERE guest_id = $1
|
|
`, guestID).Scan(&c.ID, &c.GuestID, &c.CheckedInAt, &c.CheckedInBy, &c.ArrivalCount, &c.Notes, &c.WalkIn)
|
|
if err != nil {
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return nil, nil
|
|
}
|
|
return nil, err
|
|
}
|
|
return &c, nil
|
|
}
|
|
|
|
// GuestBelongsToEvent confirms a guest is on the event before we record
|
|
// their check-in. Belt-and-braces guard against a forged JWT pointing
|
|
// at a guest from a different event — the JWT layer already binds
|
|
// (event_id, guest_id) but a DB-level check is cheap insurance.
|
|
func (r *CheckInRepo) GuestBelongsToEvent(ctx context.Context, guestID, eventID uuid.UUID) (bool, error) {
|
|
var ok bool
|
|
err := r.pool.QueryRow(ctx,
|
|
`SELECT EXISTS (SELECT 1 FROM guests WHERE id = $1 AND event_id = $2)`,
|
|
guestID, eventID).Scan(&ok)
|
|
return ok, err
|
|
}
|