feat: build core API, fraud engine, notifier, and frontend
Phase 1 — Core API (Go): - Events, guests, tokens, RSVPs CRUD on PostgreSQL via pgx/v5 - HMAC-signed per-guest tokens with format validation - Health endpoint with DB ping, slog JSON logging, graceful shutdown Phase 2 — NATS + Fraud Engine: - NATS JetStream pub/sub with explicit-ack consumers - Python/FastAPI fraud engine with heuristic risk scoring (fingerprint mismatch, IP change, missing signals, repeated access) - gRPC sync scoring with 250ms fail-open timeout - Per-guest baseline tracking; risk bands low/medium/high/block Phase 3 — Notifications + Frontend: - Notification worker scaffolding (Twilio/SES stubs, retry/backoff) - Nuxt 3 frontend with Tailwind dark theme + brand green - Live monitor via WebSocket with auto-reconnect - Activity history endpoint backfills monitor with RSVPs + scored access checks (including blocked attempts) UX polish: - Marketing-friendly landing page (hero mockup, how-it-works, features, use cases, testimonials, FAQ, final CTA) - Animated layered card mockups on landing + new-event page - Plus-ones stepper, RSVP status badges, filter buttons - Friendly access-check labels (Verified/Review/Suspicious/Blocked) - Dashboard hydration fix via ClientOnly wrapper Infrastructure: - docker-compose for full local dev (postgres, nats, api, fraud-engine, notifier, frontend) - Multi-stage Dockerfiles, non-root UID 1000 - Integration tests with testcontainers-go Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,127 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
type AccessLogRepo struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewAccessLogRepo(db *DB) *AccessLogRepo {
|
||||
return &AccessLogRepo{pool: db.Pool}
|
||||
}
|
||||
|
||||
type CreateAccessLogParams struct {
|
||||
GuestID uuid.UUID
|
||||
TokenID uuid.UUID
|
||||
Fingerprint map[string]any
|
||||
IPAddress string
|
||||
}
|
||||
|
||||
func (r *AccessLogRepo) Create(ctx context.Context, p CreateAccessLogParams) (uuid.UUID, error) {
|
||||
var fpJSON []byte
|
||||
if p.Fingerprint != nil {
|
||||
b, err := json.Marshal(p.Fingerprint)
|
||||
if err != nil {
|
||||
return uuid.Nil, fmt.Errorf("marshal fingerprint: %w", err)
|
||||
}
|
||||
fpJSON = b
|
||||
}
|
||||
|
||||
var ip *string
|
||||
if p.IPAddress != "" {
|
||||
ip = &p.IPAddress
|
||||
}
|
||||
|
||||
const q = `
|
||||
INSERT INTO access_logs (guest_id, token_id, fingerprint, ip_address)
|
||||
VALUES ($1, $2, $3, $4::inet)
|
||||
RETURNING id
|
||||
`
|
||||
var id uuid.UUID
|
||||
err := r.pool.QueryRow(ctx, q, p.GuestID, p.TokenID, fpJSON, ip).Scan(&id)
|
||||
return id, err
|
||||
}
|
||||
|
||||
type ApplyScoreParams struct {
|
||||
AccessLogID uuid.UUID
|
||||
Score int
|
||||
Reasons []string
|
||||
Flagged bool
|
||||
}
|
||||
|
||||
// AccessCheckActivity is a scored access-log entry joined with the guest's
|
||||
// name. Used by the activity-history endpoint so dashboards can show
|
||||
// historical security checks (including blocked attempts) even when nobody
|
||||
// was watching the live monitor at the time.
|
||||
type AccessCheckActivity struct {
|
||||
GuestID uuid.UUID
|
||||
GuestName string
|
||||
Score int
|
||||
Reasons []string
|
||||
Flagged bool
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
// ListRecentScoredByEvent returns scored access-log entries for an event,
|
||||
// newest first. Unscored entries (someone opened the page but the fraud
|
||||
// engine hasn't replied yet) are excluded — they'd be noise on the feed.
|
||||
func (r *AccessLogRepo) ListRecentScoredByEvent(ctx context.Context, eventID uuid.UUID, limit int) ([]AccessCheckActivity, error) {
|
||||
if limit <= 0 || limit > 200 {
|
||||
limit = 50
|
||||
}
|
||||
const q = `
|
||||
SELECT a.guest_id, g.name, a.risk_score, a.risk_reasons, a.flagged, a.created_at
|
||||
FROM access_logs a
|
||||
JOIN guests g ON g.id = a.guest_id
|
||||
WHERE g.event_id = $1 AND a.risk_score IS NOT NULL
|
||||
ORDER BY a.created_at DESC
|
||||
LIMIT $2
|
||||
`
|
||||
rows, err := r.pool.Query(ctx, q, eventID, limit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var out []AccessCheckActivity
|
||||
for rows.Next() {
|
||||
var (
|
||||
a AccessCheckActivity
|
||||
reasons []string
|
||||
score int16
|
||||
)
|
||||
if err := rows.Scan(&a.GuestID, &a.GuestName, &score, &reasons, &a.Flagged, &a.CreatedAt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
a.Score = int(score)
|
||||
a.Reasons = reasons
|
||||
out = append(out, a)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
func (r *AccessLogRepo) ApplyScore(ctx context.Context, p ApplyScoreParams) error {
|
||||
const q = `
|
||||
UPDATE access_logs
|
||||
SET risk_score = $2, risk_reasons = $3, flagged = $4
|
||||
WHERE id = $1
|
||||
`
|
||||
tag, err := r.pool.Exec(ctx, q, p.AccessLogID, p.Score, p.Reasons, p.Flagged)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if tag.RowsAffected() == 0 {
|
||||
return errors.New("access_log not found")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,211 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"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"
|
||||
)
|
||||
|
||||
type EventRepo struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewEventRepo(db *DB) *EventRepo {
|
||||
return &EventRepo{pool: db.Pool}
|
||||
}
|
||||
|
||||
type CreateEventParams struct {
|
||||
HostID uuid.UUID
|
||||
Name string
|
||||
Slug string
|
||||
EventDate time.Time
|
||||
Venue string
|
||||
MaxCapacity int
|
||||
Settings map[string]any
|
||||
Status domain.EventStatus
|
||||
}
|
||||
|
||||
func (r *EventRepo) Create(ctx context.Context, p CreateEventParams) (*domain.Event, error) {
|
||||
settings := p.Settings
|
||||
if settings == nil {
|
||||
settings = map[string]any{}
|
||||
}
|
||||
settingsJSON, err := json.Marshal(settings)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("marshal settings: %w", err)
|
||||
}
|
||||
|
||||
const q = `
|
||||
INSERT INTO events (host_id, name, slug, event_date, venue, max_capacity, settings, status)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
|
||||
RETURNING id, host_id, name, slug, event_date, venue, max_capacity, settings, status, created_at, updated_at
|
||||
`
|
||||
row := r.pool.QueryRow(ctx, q,
|
||||
p.HostID, p.Name, p.Slug, p.EventDate, p.Venue, p.MaxCapacity, settingsJSON, p.Status,
|
||||
)
|
||||
ev, err := scanEvent(row)
|
||||
if err != nil {
|
||||
var pgErr *pgconn.PgError
|
||||
if errors.As(err, &pgErr) && pgErr.Code == "23505" {
|
||||
return nil, domain.ErrSlugTaken
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return ev, nil
|
||||
}
|
||||
|
||||
func (r *EventRepo) Get(ctx context.Context, id uuid.UUID) (*domain.Event, error) {
|
||||
const q = `
|
||||
SELECT id, host_id, name, slug, event_date, venue, max_capacity, settings, status, created_at, updated_at
|
||||
FROM events WHERE id = $1
|
||||
`
|
||||
ev, err := scanEvent(r.pool.QueryRow(ctx, q, id))
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, domain.ErrEventNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return ev, nil
|
||||
}
|
||||
|
||||
func (r *EventRepo) List(ctx context.Context, hostID uuid.UUID, limit, offset int) ([]*domain.Event, error) {
|
||||
if limit <= 0 || limit > 200 {
|
||||
limit = 50
|
||||
}
|
||||
if offset < 0 {
|
||||
offset = 0
|
||||
}
|
||||
|
||||
var (
|
||||
rows pgx.Rows
|
||||
err error
|
||||
)
|
||||
if hostID == uuid.Nil {
|
||||
rows, err = r.pool.Query(ctx, `
|
||||
SELECT id, host_id, name, slug, event_date, venue, max_capacity, settings, status, created_at, updated_at
|
||||
FROM events
|
||||
ORDER BY created_at DESC
|
||||
LIMIT $1 OFFSET $2
|
||||
`, limit, offset)
|
||||
} else {
|
||||
rows, err = r.pool.Query(ctx, `
|
||||
SELECT id, host_id, name, slug, event_date, venue, max_capacity, settings, status, created_at, updated_at
|
||||
FROM events
|
||||
WHERE host_id = $1
|
||||
ORDER BY created_at DESC
|
||||
LIMIT $2 OFFSET $3
|
||||
`, hostID, limit, offset)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var out []*domain.Event
|
||||
for rows.Next() {
|
||||
ev, err := scanEvent(rows)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, ev)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
type UpdateEventParams struct {
|
||||
Name *string
|
||||
Slug *string
|
||||
EventDate *time.Time
|
||||
Venue *string
|
||||
MaxCapacity *int
|
||||
Settings *map[string]any
|
||||
Status *domain.EventStatus
|
||||
}
|
||||
|
||||
func (r *EventRepo) Update(ctx context.Context, id uuid.UUID, p UpdateEventParams) (*domain.Event, error) {
|
||||
const q = `
|
||||
UPDATE events SET
|
||||
name = COALESCE($2, name),
|
||||
slug = COALESCE($3, slug),
|
||||
event_date = COALESCE($4, event_date),
|
||||
venue = COALESCE($5, venue),
|
||||
max_capacity = COALESCE($6, max_capacity),
|
||||
settings = COALESCE($7, settings),
|
||||
status = COALESCE($8, status),
|
||||
updated_at = now()
|
||||
WHERE id = $1
|
||||
RETURNING id, host_id, name, slug, event_date, venue, max_capacity, settings, status, created_at, updated_at
|
||||
`
|
||||
|
||||
var settingsJSON []byte
|
||||
if p.Settings != nil {
|
||||
b, err := json.Marshal(*p.Settings)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("marshal settings: %w", err)
|
||||
}
|
||||
settingsJSON = b
|
||||
}
|
||||
|
||||
row := r.pool.QueryRow(ctx, q, id,
|
||||
p.Name, p.Slug, p.EventDate, p.Venue, p.MaxCapacity, settingsJSON, p.Status,
|
||||
)
|
||||
ev, err := scanEvent(row)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, domain.ErrEventNotFound
|
||||
}
|
||||
var pgErr *pgconn.PgError
|
||||
if errors.As(err, &pgErr) && pgErr.Code == "23505" {
|
||||
return nil, domain.ErrSlugTaken
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return ev, nil
|
||||
}
|
||||
|
||||
func (r *EventRepo) Delete(ctx context.Context, id uuid.UUID) error {
|
||||
tag, err := r.pool.Exec(ctx, `DELETE FROM events WHERE id = $1`, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if tag.RowsAffected() == 0 {
|
||||
return domain.ErrEventNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type rowScanner interface {
|
||||
Scan(dest ...any) error
|
||||
}
|
||||
|
||||
func scanEvent(s rowScanner) (*domain.Event, error) {
|
||||
var (
|
||||
ev domain.Event
|
||||
settingsJSON []byte
|
||||
)
|
||||
err := s.Scan(
|
||||
&ev.ID, &ev.HostID, &ev.Name, &ev.Slug, &ev.EventDate, &ev.Venue,
|
||||
&ev.MaxCapacity, &settingsJSON, &ev.Status, &ev.CreatedAt, &ev.UpdatedAt,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(settingsJSON) > 0 {
|
||||
if err := json.Unmarshal(settingsJSON, &ev.Settings); err != nil {
|
||||
return nil, fmt.Errorf("unmarshal settings: %w", err)
|
||||
}
|
||||
} else {
|
||||
ev.Settings = map[string]any{}
|
||||
}
|
||||
return &ev, nil
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"github.com/alchemistkay/guestguard/internal/domain"
|
||||
)
|
||||
|
||||
type GuestRepo struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewGuestRepo(db *DB) *GuestRepo {
|
||||
return &GuestRepo{pool: db.Pool}
|
||||
}
|
||||
|
||||
type CreateGuestParams struct {
|
||||
EventID uuid.UUID
|
||||
Name string
|
||||
Email *string
|
||||
Phone *string
|
||||
PlusOnes int
|
||||
DietaryNotes *string
|
||||
TableNumber *int
|
||||
}
|
||||
|
||||
func (r *GuestRepo) Create(ctx context.Context, p CreateGuestParams) (*domain.Guest, error) {
|
||||
const q = `
|
||||
INSERT INTO guests (event_id, name, email, phone, plus_ones, dietary_notes, table_number)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7)
|
||||
RETURNING id, event_id, name, email, phone, plus_ones, dietary_notes, table_number, created_at
|
||||
`
|
||||
row := r.pool.QueryRow(ctx, q,
|
||||
p.EventID, p.Name, p.Email, p.Phone, p.PlusOnes, p.DietaryNotes, p.TableNumber,
|
||||
)
|
||||
return scanGuest(row)
|
||||
}
|
||||
|
||||
func (r *GuestRepo) Get(ctx context.Context, id uuid.UUID) (*domain.Guest, error) {
|
||||
const q = `
|
||||
SELECT id, event_id, name, email, phone, plus_ones, dietary_notes, table_number, created_at
|
||||
FROM guests WHERE id = $1
|
||||
`
|
||||
g, err := scanGuest(r.pool.QueryRow(ctx, q, id))
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, domain.ErrGuestNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return g, nil
|
||||
}
|
||||
|
||||
func (r *GuestRepo) ListByEvent(ctx context.Context, eventID uuid.UUID, limit, offset int) ([]*domain.Guest, error) {
|
||||
if limit <= 0 || limit > 500 {
|
||||
limit = 100
|
||||
}
|
||||
if offset < 0 {
|
||||
offset = 0
|
||||
}
|
||||
const q = `
|
||||
SELECT id, event_id, name, email, phone, plus_ones, dietary_notes, table_number, created_at
|
||||
FROM guests
|
||||
WHERE event_id = $1
|
||||
ORDER BY created_at DESC
|
||||
LIMIT $2 OFFSET $3
|
||||
`
|
||||
rows, err := r.pool.Query(ctx, q, eventID, limit, offset)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var out []*domain.Guest
|
||||
for rows.Next() {
|
||||
g, err := scanGuest(rows)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, g)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
func scanGuest(s rowScanner) (*domain.Guest, error) {
|
||||
var g domain.Guest
|
||||
err := s.Scan(
|
||||
&g.ID, &g.EventID, &g.Name, &g.Email, &g.Phone,
|
||||
&g.PlusOnes, &g.DietaryNotes, &g.TableNumber, &g.CreatedAt,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &g, nil
|
||||
}
|
||||
|
||||
// GuestWithRSVP is the dashboard view: a guest plus the RSVP submitted
|
||||
// against their token, if any. RSVP fields are nil when no response yet.
|
||||
type GuestWithRSVP struct {
|
||||
*domain.Guest
|
||||
RSVPResponse *string `json:"rsvp_response,omitempty"`
|
||||
RSVPPlusOnes *int `json:"rsvp_plus_ones,omitempty"`
|
||||
RSVPRiskScore *int `json:"rsvp_risk_score,omitempty"`
|
||||
RSVPSubmittedAt *time.Time `json:"rsvp_submitted_at,omitempty"`
|
||||
HasToken bool `json:"has_token"`
|
||||
}
|
||||
|
||||
func (r *GuestRepo) ListByEventWithRSVP(ctx context.Context, eventID uuid.UUID, limit, offset int) ([]*GuestWithRSVP, error) {
|
||||
if limit <= 0 || limit > 500 {
|
||||
limit = 100
|
||||
}
|
||||
if offset < 0 {
|
||||
offset = 0
|
||||
}
|
||||
const q = `
|
||||
SELECT
|
||||
g.id, g.event_id, g.name, g.email, g.phone, g.plus_ones,
|
||||
g.dietary_notes, g.table_number, g.created_at,
|
||||
r.response, r.plus_ones, r.risk_score, r.submitted_at,
|
||||
t.id IS NOT NULL AS has_token
|
||||
FROM guests g
|
||||
LEFT JOIN rsvps r ON r.guest_id = g.id
|
||||
LEFT JOIN tokens t ON t.guest_id = g.id
|
||||
WHERE g.event_id = $1
|
||||
ORDER BY g.created_at DESC
|
||||
LIMIT $2 OFFSET $3
|
||||
`
|
||||
rows, err := r.pool.Query(ctx, q, eventID, limit, offset)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var out []*GuestWithRSVP
|
||||
for rows.Next() {
|
||||
var (
|
||||
g domain.Guest
|
||||
response *string
|
||||
rsvpPlusOnes *int
|
||||
riskScore *int
|
||||
submittedAt *time.Time
|
||||
hasToken bool
|
||||
)
|
||||
if err := rows.Scan(
|
||||
&g.ID, &g.EventID, &g.Name, &g.Email, &g.Phone, &g.PlusOnes,
|
||||
&g.DietaryNotes, &g.TableNumber, &g.CreatedAt,
|
||||
&response, &rsvpPlusOnes, &riskScore, &submittedAt,
|
||||
&hasToken,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, &GuestWithRSVP{
|
||||
Guest: &g,
|
||||
RSVPResponse: response,
|
||||
RSVPPlusOnes: rsvpPlusOnes,
|
||||
RSVPRiskScore: riskScore,
|
||||
RSVPSubmittedAt: submittedAt,
|
||||
HasToken: hasToken,
|
||||
})
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
DROP TABLE IF EXISTS notifications;
|
||||
DROP TABLE IF EXISTS access_logs;
|
||||
DROP TABLE IF EXISTS rsvps;
|
||||
DROP TABLE IF EXISTS tokens;
|
||||
DROP TABLE IF EXISTS guests;
|
||||
DROP TABLE IF EXISTS events;
|
||||
DROP TABLE IF EXISTS users;
|
||||
|
||||
DROP TYPE IF EXISTS delivery_status;
|
||||
DROP TYPE IF EXISTS notification_type;
|
||||
DROP TYPE IF EXISTS notification_channel;
|
||||
DROP TYPE IF EXISTS rsvp_response;
|
||||
DROP TYPE IF EXISTS token_status;
|
||||
DROP TYPE IF EXISTS event_status;
|
||||
@@ -0,0 +1,122 @@
|
||||
CREATE EXTENSION IF NOT EXISTS "pgcrypto";
|
||||
|
||||
DO $$ BEGIN
|
||||
CREATE TYPE event_status AS ENUM ('draft', 'published', 'closed', 'archived');
|
||||
EXCEPTION WHEN duplicate_object THEN NULL; END $$;
|
||||
|
||||
DO $$ BEGIN
|
||||
CREATE TYPE token_status AS ENUM ('active', 'used', 'revoked', 'expired');
|
||||
EXCEPTION WHEN duplicate_object THEN NULL; END $$;
|
||||
|
||||
DO $$ BEGIN
|
||||
CREATE TYPE rsvp_response AS ENUM ('attending', 'declined', 'maybe');
|
||||
EXCEPTION WHEN duplicate_object THEN NULL; END $$;
|
||||
|
||||
DO $$ BEGIN
|
||||
CREATE TYPE notification_channel AS ENUM ('sms', 'email');
|
||||
EXCEPTION WHEN duplicate_object THEN NULL; END $$;
|
||||
|
||||
DO $$ BEGIN
|
||||
CREATE TYPE notification_type AS ENUM ('invitation', 'verification', 'confirmation', 'reminder');
|
||||
EXCEPTION WHEN duplicate_object THEN NULL; END $$;
|
||||
|
||||
DO $$ BEGIN
|
||||
CREATE TYPE delivery_status AS ENUM ('queued', 'sent', 'delivered', 'failed', 'bounced');
|
||||
EXCEPTION WHEN duplicate_object THEN NULL; END $$;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
email VARCHAR(255) UNIQUE NOT NULL,
|
||||
name VARCHAR(255) NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS events (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
host_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
name VARCHAR(255) NOT NULL,
|
||||
slug VARCHAR(100) UNIQUE NOT NULL,
|
||||
event_date TIMESTAMPTZ NOT NULL,
|
||||
venue TEXT NOT NULL DEFAULT '',
|
||||
max_capacity INTEGER NOT NULL DEFAULT 0,
|
||||
settings JSONB NOT NULL DEFAULT '{}'::jsonb,
|
||||
status event_status NOT NULL DEFAULT 'draft',
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_events_host ON events(host_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_events_status ON events(status);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS guests (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
event_id UUID NOT NULL REFERENCES events(id) ON DELETE CASCADE,
|
||||
name VARCHAR(255) NOT NULL,
|
||||
email VARCHAR(255),
|
||||
phone VARCHAR(20),
|
||||
plus_ones INTEGER NOT NULL DEFAULT 0,
|
||||
dietary_notes TEXT,
|
||||
table_number INTEGER,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_guests_event ON guests(event_id);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS tokens (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
guest_id UUID NOT NULL UNIQUE REFERENCES guests(id) ON DELETE CASCADE,
|
||||
token_hash VARCHAR(64) NOT NULL,
|
||||
expires_at TIMESTAMPTZ NOT NULL,
|
||||
status token_status NOT NULL DEFAULT 'active',
|
||||
used_at TIMESTAMPTZ,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_tokens_hash ON tokens(token_hash) WHERE status = 'active';
|
||||
|
||||
CREATE TABLE IF NOT EXISTS rsvps (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
guest_id UUID NOT NULL UNIQUE REFERENCES guests(id) ON DELETE CASCADE,
|
||||
response rsvp_response NOT NULL,
|
||||
plus_ones INTEGER NOT NULL DEFAULT 0,
|
||||
dietary_notes TEXT,
|
||||
submitted_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
device_fingerprint JSONB,
|
||||
ip_address INET,
|
||||
risk_score SMALLINT
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_rsvps_guest ON rsvps(guest_id);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS access_logs (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
guest_id UUID NOT NULL REFERENCES guests(id) ON DELETE CASCADE,
|
||||
token_id UUID REFERENCES tokens(id) ON DELETE SET NULL,
|
||||
fingerprint JSONB,
|
||||
ip_address INET,
|
||||
geo_location JSONB,
|
||||
risk_score SMALLINT,
|
||||
risk_reasons TEXT[],
|
||||
flagged BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_access_logs_guest ON access_logs(guest_id, created_at DESC);
|
||||
CREATE INDEX IF NOT EXISTS idx_access_logs_flagged ON access_logs(flagged) WHERE flagged = TRUE;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS notifications (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
guest_id UUID NOT NULL REFERENCES guests(id) ON DELETE CASCADE,
|
||||
channel notification_channel NOT NULL,
|
||||
type notification_type NOT NULL,
|
||||
status delivery_status NOT NULL DEFAULT 'queued',
|
||||
provider_id VARCHAR(100),
|
||||
attempts SMALLINT NOT NULL DEFAULT 0,
|
||||
last_attempt TIMESTAMPTZ,
|
||||
delivered_at TIMESTAMPTZ,
|
||||
error TEXT,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_notifications_status ON notifications(status) WHERE status IN ('queued', 'failed');
|
||||
@@ -0,0 +1 @@
|
||||
DROP INDEX IF EXISTS idx_rsvps_submitted_at;
|
||||
@@ -0,0 +1,6 @@
|
||||
-- This migration adjusts RSVP recording to align with synchronous fraud scoring.
|
||||
-- The base table already exists; this is a no-op placeholder so future schema
|
||||
-- changes have a slot. We add an index that helps the dashboard query rsvps
|
||||
-- joined with guests by event.
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_rsvps_submitted_at ON rsvps (submitted_at DESC);
|
||||
@@ -0,0 +1,115 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"embed"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
//go:embed migrations/*.sql
|
||||
var migrationsFS embed.FS
|
||||
|
||||
type DB struct {
|
||||
Pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewDB(ctx context.Context, dsn string) (*DB, error) {
|
||||
cfg, err := pgxpool.ParseConfig(dsn)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parse dsn: %w", err)
|
||||
}
|
||||
cfg.MaxConnLifetime = 30 * time.Minute
|
||||
cfg.MaxConns = 10
|
||||
|
||||
pool, err := pgxpool.NewWithConfig(ctx, cfg)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("connect pool: %w", err)
|
||||
}
|
||||
|
||||
pingCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
||||
defer cancel()
|
||||
if err := pool.Ping(pingCtx); err != nil {
|
||||
pool.Close()
|
||||
return nil, fmt.Errorf("ping db: %w", err)
|
||||
}
|
||||
|
||||
return &DB{Pool: pool}, nil
|
||||
}
|
||||
|
||||
func (db *DB) Close() {
|
||||
db.Pool.Close()
|
||||
}
|
||||
|
||||
func (db *DB) Migrate(ctx context.Context) error {
|
||||
_, err := db.Pool.Exec(ctx, `
|
||||
CREATE TABLE IF NOT EXISTS schema_migrations (
|
||||
version VARCHAR(255) PRIMARY KEY,
|
||||
applied_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
)
|
||||
`)
|
||||
if err != nil {
|
||||
return fmt.Errorf("create migrations table: %w", err)
|
||||
}
|
||||
|
||||
entries, err := fs.ReadDir(migrationsFS, "migrations")
|
||||
if err != nil {
|
||||
return fmt.Errorf("read migrations: %w", err)
|
||||
}
|
||||
|
||||
type migration struct {
|
||||
version string
|
||||
path string
|
||||
}
|
||||
var ups []migration
|
||||
for _, e := range entries {
|
||||
name := e.Name()
|
||||
if !strings.HasSuffix(name, ".up.sql") {
|
||||
continue
|
||||
}
|
||||
version := strings.TrimSuffix(name, ".up.sql")
|
||||
ups = append(ups, migration{version: version, path: "migrations/" + name})
|
||||
}
|
||||
sort.Slice(ups, func(i, j int) bool { return ups[i].version < ups[j].version })
|
||||
|
||||
for _, m := range ups {
|
||||
var exists bool
|
||||
err := db.Pool.QueryRow(ctx,
|
||||
"SELECT EXISTS(SELECT 1 FROM schema_migrations WHERE version=$1)",
|
||||
m.version,
|
||||
).Scan(&exists)
|
||||
if err != nil {
|
||||
return fmt.Errorf("check migration %s: %w", m.version, err)
|
||||
}
|
||||
if exists {
|
||||
continue
|
||||
}
|
||||
|
||||
sqlBytes, err := migrationsFS.ReadFile(m.path)
|
||||
if err != nil {
|
||||
return fmt.Errorf("read %s: %w", m.path, err)
|
||||
}
|
||||
tx, err := db.Pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("begin tx for %s: %w", m.version, err)
|
||||
}
|
||||
if _, err := tx.Exec(ctx, string(sqlBytes)); err != nil {
|
||||
_ = tx.Rollback(ctx)
|
||||
return fmt.Errorf("apply %s: %w", m.version, err)
|
||||
}
|
||||
if _, err := tx.Exec(ctx, "INSERT INTO schema_migrations(version) VALUES($1)", m.version); err != nil {
|
||||
_ = tx.Rollback(ctx)
|
||||
return fmt.Errorf("record %s: %w", m.version, err)
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return fmt.Errorf("commit %s: %w", m.version, err)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"github.com/alchemistkay/guestguard/internal/domain"
|
||||
)
|
||||
|
||||
type RSVPRepo struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewRSVPRepo(db *DB) *RSVPRepo {
|
||||
return &RSVPRepo{pool: db.Pool}
|
||||
}
|
||||
|
||||
type CreateRSVPParams struct {
|
||||
GuestID uuid.UUID
|
||||
Response domain.RSVPResponse
|
||||
PlusOnes int
|
||||
DietaryNotes *string
|
||||
DeviceFingerprint map[string]any
|
||||
IPAddress string
|
||||
RiskScore *int
|
||||
}
|
||||
|
||||
func (r *RSVPRepo) Create(ctx context.Context, p CreateRSVPParams) (*domain.RSVP, error) {
|
||||
var fpJSON []byte
|
||||
if p.DeviceFingerprint != nil {
|
||||
b, err := json.Marshal(p.DeviceFingerprint)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("marshal fingerprint: %w", err)
|
||||
}
|
||||
fpJSON = b
|
||||
}
|
||||
|
||||
var ip *string
|
||||
if p.IPAddress != "" {
|
||||
ip = &p.IPAddress
|
||||
}
|
||||
|
||||
const q = `
|
||||
INSERT INTO rsvps (guest_id, response, plus_ones, dietary_notes,
|
||||
device_fingerprint, ip_address, risk_score)
|
||||
VALUES ($1, $2, $3, $4, $5, $6::inet, $7)
|
||||
RETURNING id, guest_id, response, plus_ones, dietary_notes,
|
||||
submitted_at, device_fingerprint, ip_address::text, risk_score
|
||||
`
|
||||
|
||||
row := r.pool.QueryRow(ctx, q,
|
||||
p.GuestID, p.Response, p.PlusOnes, p.DietaryNotes,
|
||||
fpJSON, ip, p.RiskScore,
|
||||
)
|
||||
|
||||
rs, err := scanRSVP(row)
|
||||
if err != nil {
|
||||
var pgErr *pgconn.PgError
|
||||
if errors.As(err, &pgErr) && pgErr.Code == "23505" {
|
||||
return nil, domain.ErrRSVPAlreadySubmitted
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return rs, nil
|
||||
}
|
||||
|
||||
// RSVPActivity is a denormalised RSVP entry for the activity feed —
|
||||
// includes the guest's name so the API can hand it to the frontend
|
||||
// without a separate lookup.
|
||||
type RSVPActivity struct {
|
||||
GuestID uuid.UUID
|
||||
GuestName string
|
||||
Response string
|
||||
PlusOnes int
|
||||
SubmittedAt time.Time
|
||||
}
|
||||
|
||||
// ListRecentByEvent returns the most recent RSVPs for an event, newest first.
|
||||
func (r *RSVPRepo) ListRecentByEvent(ctx context.Context, eventID uuid.UUID, limit int) ([]RSVPActivity, error) {
|
||||
if limit <= 0 || limit > 200 {
|
||||
limit = 50
|
||||
}
|
||||
const q = `
|
||||
SELECT r.guest_id, g.name, r.response, r.plus_ones, r.submitted_at
|
||||
FROM rsvps r
|
||||
JOIN guests g ON g.id = r.guest_id
|
||||
WHERE g.event_id = $1
|
||||
ORDER BY r.submitted_at DESC
|
||||
LIMIT $2
|
||||
`
|
||||
rows, err := r.pool.Query(ctx, q, eventID, limit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var out []RSVPActivity
|
||||
for rows.Next() {
|
||||
var a RSVPActivity
|
||||
if err := rows.Scan(&a.GuestID, &a.GuestName, &a.Response, &a.PlusOnes, &a.SubmittedAt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, a)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
func scanRSVP(s rowScanner) (*domain.RSVP, error) {
|
||||
var (
|
||||
rs domain.RSVP
|
||||
fpJSON []byte
|
||||
ip *string
|
||||
)
|
||||
err := s.Scan(
|
||||
&rs.ID, &rs.GuestID, &rs.Response, &rs.PlusOnes, &rs.DietaryNotes,
|
||||
&rs.SubmittedAt, &fpJSON, &ip, &rs.RiskScore,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(fpJSON) > 0 {
|
||||
_ = json.Unmarshal(fpJSON, &rs.DeviceFingerprint)
|
||||
}
|
||||
if ip != nil {
|
||||
rs.IPAddress = ip
|
||||
}
|
||||
return &rs, nil
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"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"
|
||||
)
|
||||
|
||||
type TokenRepo struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewTokenRepo(db *DB) *TokenRepo {
|
||||
return &TokenRepo{pool: db.Pool}
|
||||
}
|
||||
|
||||
type CreateTokenParams struct {
|
||||
GuestID uuid.UUID
|
||||
TokenHash string
|
||||
ExpiresAt time.Time
|
||||
}
|
||||
|
||||
func (r *TokenRepo) Create(ctx context.Context, p CreateTokenParams) (*domain.Token, error) {
|
||||
const q = `
|
||||
INSERT INTO tokens (guest_id, token_hash, expires_at, status)
|
||||
VALUES ($1, $2, $3, 'active')
|
||||
RETURNING id, guest_id, token_hash, expires_at, status, used_at, created_at
|
||||
`
|
||||
row := r.pool.QueryRow(ctx, q, p.GuestID, p.TokenHash, p.ExpiresAt)
|
||||
tk, err := scanToken(row)
|
||||
if err != nil {
|
||||
var pgErr *pgconn.PgError
|
||||
if errors.As(err, &pgErr) && pgErr.Code == "23505" {
|
||||
return nil, errors.New("guest already has a token")
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return tk, nil
|
||||
}
|
||||
|
||||
func (r *TokenRepo) GetByHash(ctx context.Context, hash string) (*domain.Token, error) {
|
||||
const q = `
|
||||
SELECT id, guest_id, token_hash, expires_at, status, used_at, created_at
|
||||
FROM tokens WHERE token_hash = $1
|
||||
`
|
||||
tk, err := scanToken(r.pool.QueryRow(ctx, q, hash))
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, domain.ErrTokenNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return tk, nil
|
||||
}
|
||||
|
||||
func (r *TokenRepo) MarkUsed(ctx context.Context, id uuid.UUID) error {
|
||||
tag, err := r.pool.Exec(ctx, `
|
||||
UPDATE tokens SET status = 'used', used_at = now()
|
||||
WHERE id = $1 AND status = 'active'
|
||||
`, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if tag.RowsAffected() == 0 {
|
||||
return domain.ErrTokenNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func scanToken(s rowScanner) (*domain.Token, error) {
|
||||
var tk domain.Token
|
||||
err := s.Scan(
|
||||
&tk.ID, &tk.GuestID, &tk.TokenHash, &tk.ExpiresAt,
|
||||
&tk.Status, &tk.UsedAt, &tk.CreatedAt,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &tk, nil
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"github.com/alchemistkay/guestguard/internal/domain"
|
||||
)
|
||||
|
||||
type UserRepo struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewUserRepo(db *DB) *UserRepo {
|
||||
return &UserRepo{pool: db.Pool}
|
||||
}
|
||||
|
||||
func (r *UserRepo) Create(ctx context.Context, email, name string) (*domain.User, error) {
|
||||
const q = `
|
||||
INSERT INTO users (email, name) VALUES ($1, $2)
|
||||
RETURNING id, email, name, created_at, updated_at
|
||||
`
|
||||
row := r.pool.QueryRow(ctx, q, strings.ToLower(strings.TrimSpace(email)), strings.TrimSpace(name))
|
||||
u, err := scanUser(row)
|
||||
if err != nil {
|
||||
var pgErr *pgconn.PgError
|
||||
if errors.As(err, &pgErr) && pgErr.Code == "23505" {
|
||||
return nil, domain.ErrEmailTaken
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return u, nil
|
||||
}
|
||||
|
||||
func (r *UserRepo) GetByEmail(ctx context.Context, email string) (*domain.User, error) {
|
||||
const q = `SELECT id, email, name, created_at, updated_at FROM users WHERE email = $1`
|
||||
u, err := scanUser(r.pool.QueryRow(ctx, q, strings.ToLower(strings.TrimSpace(email))))
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, domain.ErrUserNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return u, nil
|
||||
}
|
||||
|
||||
func scanUser(s rowScanner) (*domain.User, error) {
|
||||
var u domain.User
|
||||
if err := s.Scan(&u.ID, &u.Email, &u.Name, &u.CreatedAt, &u.UpdatedAt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &u, nil
|
||||
}
|
||||
Reference in New Issue
Block a user