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>
362 lines
10 KiB
Go
362 lines
10 KiB
Go
package api
|
|
|
|
import (
|
|
"encoding/json"
|
|
"errors"
|
|
"log/slog"
|
|
"net/http"
|
|
"time"
|
|
|
|
"github.com/alchemistkay/guestguard/internal/audit"
|
|
"github.com/alchemistkay/guestguard/internal/domain"
|
|
"github.com/alchemistkay/guestguard/internal/flags"
|
|
"github.com/alchemistkay/guestguard/internal/storage"
|
|
)
|
|
|
|
// messageHandler is the host-facing surface for Tier 2 Block F:
|
|
// scheduled reminders + custom broadcasts. Editor+ for writes; viewer+
|
|
// for reads via the existing requireRole gate.
|
|
type messageHandler struct {
|
|
logger *slog.Logger
|
|
events *storage.EventRepo
|
|
collabs *storage.CollaboratorRepo
|
|
repo *storage.MessageRepo
|
|
audit *audit.Recorder
|
|
enforcer *tierEnforcer
|
|
flags *flags.Store
|
|
}
|
|
|
|
// --- response shapes ---
|
|
|
|
// messageView wraps the persisted row with a delivery summary. We don't
|
|
// inline the per-recipient rows here — the host expands a single message
|
|
// to drill into those — but the "X of Y delivered" rollup is useful in
|
|
// the list view.
|
|
type messageView struct {
|
|
*domain.ScheduledMessage
|
|
DeliveryStats storage.DeliveryStats `json:"delivery_stats"`
|
|
}
|
|
|
|
type listMessagesResponse struct {
|
|
Messages []messageView `json:"messages"`
|
|
}
|
|
|
|
// GET /events/{id}/messages — viewer+.
|
|
func (h *messageHandler) list(w http.ResponseWriter, r *http.Request) {
|
|
hostID, ok := hostFromContext(w, r)
|
|
if !ok {
|
|
return
|
|
}
|
|
eventID, ok := parseIDParam(w, r, "id")
|
|
if !ok {
|
|
return
|
|
}
|
|
if _, _, ok := requireRole(w, r, h.events, h.collabs, eventID, hostID, domain.RoleViewer); !ok {
|
|
return
|
|
}
|
|
msgs, err := h.repo.ListByEvent(r.Context(), eventID)
|
|
if err != nil {
|
|
writeError(w, http.StatusInternalServerError, "failed to list messages")
|
|
return
|
|
}
|
|
views := make([]messageView, 0, len(msgs))
|
|
for i := range msgs {
|
|
stats, _ := h.repo.DeliveryStats(r.Context(), msgs[i].ID)
|
|
views = append(views, messageView{
|
|
ScheduledMessage: &msgs[i],
|
|
DeliveryStats: stats,
|
|
})
|
|
}
|
|
writeJSON(w, http.StatusOK, listMessagesResponse{Messages: views})
|
|
}
|
|
|
|
// composeMessageRequest is what the Communications tab POSTs / PATCHes.
|
|
// SendAt is optional on create — omit it together with status="draft" to
|
|
// save a draft, or set it for scheduling. Channel defaults to email.
|
|
type composeMessageRequest struct {
|
|
SendAt *time.Time `json:"send_at"`
|
|
Audience domain.MessageAudience `json:"audience"`
|
|
Channel domain.MessageChannel `json:"channel"`
|
|
Subject string `json:"subject"`
|
|
Body string `json:"body"`
|
|
Draft bool `json:"draft"`
|
|
}
|
|
|
|
// recipientCountResponse is what the live "X guests will receive this"
|
|
// preview chip on the compose form fetches when the audience picker
|
|
// changes.
|
|
type recipientCountResponse struct {
|
|
Count int `json:"count"`
|
|
}
|
|
|
|
// GET /events/{id}/messages/recipient-count?audience=... — viewer+. Lets
|
|
// the compose form show a live count without needing to load the full
|
|
// guest list client-side.
|
|
func (h *messageHandler) recipientCount(w http.ResponseWriter, r *http.Request) {
|
|
hostID, ok := hostFromContext(w, r)
|
|
if !ok {
|
|
return
|
|
}
|
|
eventID, ok := parseIDParam(w, r, "id")
|
|
if !ok {
|
|
return
|
|
}
|
|
if _, _, ok := requireRole(w, r, h.events, h.collabs, eventID, hostID, domain.RoleViewer); !ok {
|
|
return
|
|
}
|
|
audience := domain.MessageAudience(r.URL.Query().Get("audience"))
|
|
if !audience.Valid() {
|
|
writeError(w, http.StatusBadRequest, "audience must be one of: all|attending|pending|declined|maybe")
|
|
return
|
|
}
|
|
n, err := h.repo.CountRecipients(r.Context(), eventID, audience)
|
|
if err != nil {
|
|
writeError(w, http.StatusInternalServerError, "failed to count recipients")
|
|
return
|
|
}
|
|
writeJSON(w, http.StatusOK, recipientCountResponse{Count: n})
|
|
}
|
|
|
|
// POST /events/{id}/messages — editor+.
|
|
//
|
|
// The host can save a draft (Draft=true, SendAt nil → status=draft) or
|
|
// schedule for later (SendAt set → status=scheduled). Send-immediately is
|
|
// just "schedule for now"; we expose a separate send-now route for the
|
|
// "send this draft right now" affordance below.
|
|
func (h *messageHandler) create(w http.ResponseWriter, r *http.Request) {
|
|
hostID, ok := hostFromContext(w, r)
|
|
if !ok {
|
|
return
|
|
}
|
|
eventID, ok := parseIDParam(w, r, "id")
|
|
if !ok {
|
|
return
|
|
}
|
|
if _, _, ok := requireRole(w, r, h.events, h.collabs, eventID, hostID, domain.RoleEditor); !ok {
|
|
return
|
|
}
|
|
// Kill switch — ops can disable broadcasts entirely without a
|
|
// redeploy if delivery upstream goes wobbly.
|
|
if !h.flags.Enabled("broadcasts", hostID) {
|
|
writeError(w, http.StatusServiceUnavailable, "broadcasts are temporarily disabled")
|
|
return
|
|
}
|
|
// Custom broadcasts are a Pro+ feature. Auto-reminders (which the
|
|
// system creates on event creation) are NOT gated — those run for
|
|
// every event regardless of tier so free users still get reminder
|
|
// emails before their event.
|
|
if !h.enforcer.allowFeature(w, r, hostID, "broadcasts",
|
|
"Custom broadcasts are a Pro feature. Auto-reminders still run on every plan.") {
|
|
return
|
|
}
|
|
var req composeMessageRequest
|
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
|
writeError(w, http.StatusBadRequest, "invalid json")
|
|
return
|
|
}
|
|
if !req.Audience.Valid() {
|
|
writeError(w, http.StatusBadRequest, "audience required (all|attending|pending|declined|maybe)")
|
|
return
|
|
}
|
|
if req.Channel == "" {
|
|
req.Channel = domain.ChannelEmail
|
|
}
|
|
if !req.Channel.Valid() {
|
|
writeError(w, http.StatusBadRequest, "channel must be one of: email|sms|both")
|
|
return
|
|
}
|
|
if req.Body == "" {
|
|
writeError(w, http.StatusBadRequest, "body is required")
|
|
return
|
|
}
|
|
|
|
// Pick the status from send_at + draft flag.
|
|
status := domain.StatusScheduled
|
|
sendAt := time.Now().UTC()
|
|
if req.Draft || req.SendAt == nil {
|
|
if req.Draft {
|
|
status = domain.StatusDraft
|
|
} else {
|
|
// No send_at given and not flagged as draft: send now.
|
|
status = domain.StatusScheduled
|
|
}
|
|
} else {
|
|
sendAt = req.SendAt.UTC()
|
|
}
|
|
|
|
subj := req.Subject
|
|
var subjPtr *string
|
|
if subj != "" {
|
|
subjPtr = &subj
|
|
}
|
|
|
|
m, err := h.repo.Create(r.Context(), storage.CreateMessageParams{
|
|
EventID: eventID,
|
|
SendAt: sendAt,
|
|
Audience: req.Audience,
|
|
Channel: req.Channel,
|
|
Subject: subjPtr,
|
|
Body: req.Body,
|
|
Status: status,
|
|
CreatedBy: &hostID,
|
|
})
|
|
if err != nil {
|
|
h.logger.Error("create message", "err", err)
|
|
writeError(w, http.StatusInternalServerError, "failed to create message")
|
|
return
|
|
}
|
|
h.audit.Record(r.Context(), audit.Params{
|
|
UserID: &hostID,
|
|
EventID: &eventID,
|
|
Action: "message.create",
|
|
EntityType: "message",
|
|
TargetID: &m.ID,
|
|
Metadata: map[string]any{
|
|
"audience": req.Audience,
|
|
"channel": req.Channel,
|
|
"status": status,
|
|
},
|
|
})
|
|
writeJSON(w, http.StatusCreated, m)
|
|
}
|
|
|
|
// PATCH /events/{id}/messages/{message_id} — editor+. Only legal while
|
|
// the message is still draft or scheduled (the storage layer enforces
|
|
// this with a row lock).
|
|
func (h *messageHandler) update(w http.ResponseWriter, r *http.Request) {
|
|
hostID, ok := hostFromContext(w, r)
|
|
if !ok {
|
|
return
|
|
}
|
|
eventID, ok := parseIDParam(w, r, "id")
|
|
if !ok {
|
|
return
|
|
}
|
|
if _, _, ok := requireRole(w, r, h.events, h.collabs, eventID, hostID, domain.RoleEditor); !ok {
|
|
return
|
|
}
|
|
msgID, ok := parseIDParam(w, r, "message_id")
|
|
if !ok {
|
|
return
|
|
}
|
|
var req composeMessageRequest
|
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
|
writeError(w, http.StatusBadRequest, "invalid json")
|
|
return
|
|
}
|
|
|
|
params := storage.UpdateMessageParams{}
|
|
if req.SendAt != nil {
|
|
t := req.SendAt.UTC()
|
|
params.SendAt = &t
|
|
}
|
|
if req.Audience != "" {
|
|
if !req.Audience.Valid() {
|
|
writeError(w, http.StatusBadRequest, "invalid audience")
|
|
return
|
|
}
|
|
params.Audience = &req.Audience
|
|
}
|
|
if req.Channel != "" {
|
|
if !req.Channel.Valid() {
|
|
writeError(w, http.StatusBadRequest, "invalid channel")
|
|
return
|
|
}
|
|
params.Channel = &req.Channel
|
|
}
|
|
if req.Subject != "" {
|
|
params.Subject = &req.Subject
|
|
}
|
|
if req.Body != "" {
|
|
params.Body = &req.Body
|
|
}
|
|
|
|
m, err := h.repo.Update(r.Context(), eventID, msgID, params)
|
|
if err != nil {
|
|
switch {
|
|
case errors.Is(err, domain.ErrMessageNotFound):
|
|
writeError(w, http.StatusNotFound, "message not found")
|
|
case errors.Is(err, domain.ErrMessageNotEditable):
|
|
writeError(w, http.StatusConflict, "message can only be edited while scheduled or draft")
|
|
default:
|
|
h.logger.Error("update message", "err", err)
|
|
writeError(w, http.StatusInternalServerError, "failed to update message")
|
|
}
|
|
return
|
|
}
|
|
writeJSON(w, http.StatusOK, m)
|
|
}
|
|
|
|
// POST /events/{id}/messages/{message_id}/send-now — editor+.
|
|
// Promotes a draft or future-scheduled message to send_at=now, so the
|
|
// next scheduler poll picks it up.
|
|
func (h *messageHandler) sendNow(w http.ResponseWriter, r *http.Request) {
|
|
hostID, ok := hostFromContext(w, r)
|
|
if !ok {
|
|
return
|
|
}
|
|
eventID, ok := parseIDParam(w, r, "id")
|
|
if !ok {
|
|
return
|
|
}
|
|
if _, _, ok := requireRole(w, r, h.events, h.collabs, eventID, hostID, domain.RoleEditor); !ok {
|
|
return
|
|
}
|
|
msgID, ok := parseIDParam(w, r, "message_id")
|
|
if !ok {
|
|
return
|
|
}
|
|
if err := h.repo.PromoteToScheduled(r.Context(), eventID, msgID); err != nil {
|
|
if errors.Is(err, domain.ErrMessageNotEditable) {
|
|
writeError(w, http.StatusConflict, "message has already been sent or cancelled")
|
|
return
|
|
}
|
|
writeError(w, http.StatusInternalServerError, "failed to schedule send")
|
|
return
|
|
}
|
|
h.audit.Record(r.Context(), audit.Params{
|
|
UserID: &hostID,
|
|
EventID: &eventID,
|
|
Action: "message.send_now",
|
|
EntityType: "message",
|
|
TargetID: &msgID,
|
|
})
|
|
w.WriteHeader(http.StatusAccepted)
|
|
}
|
|
|
|
// DELETE /events/{id}/messages/{message_id} — editor+. Cancels a
|
|
// scheduled / draft message. Sent or sending messages can't be deleted.
|
|
func (h *messageHandler) cancel(w http.ResponseWriter, r *http.Request) {
|
|
hostID, ok := hostFromContext(w, r)
|
|
if !ok {
|
|
return
|
|
}
|
|
eventID, ok := parseIDParam(w, r, "id")
|
|
if !ok {
|
|
return
|
|
}
|
|
if _, _, ok := requireRole(w, r, h.events, h.collabs, eventID, hostID, domain.RoleEditor); !ok {
|
|
return
|
|
}
|
|
msgID, ok := parseIDParam(w, r, "message_id")
|
|
if !ok {
|
|
return
|
|
}
|
|
if err := h.repo.Cancel(r.Context(), eventID, msgID); err != nil {
|
|
if errors.Is(err, domain.ErrMessageNotEditable) {
|
|
writeError(w, http.StatusConflict, "message has already been sent")
|
|
return
|
|
}
|
|
writeError(w, http.StatusInternalServerError, "failed to cancel message")
|
|
return
|
|
}
|
|
h.audit.Record(r.Context(), audit.Params{
|
|
UserID: &hostID,
|
|
EventID: &eventID,
|
|
Action: "message.cancel",
|
|
EntityType: "message",
|
|
TargetID: &msgID,
|
|
})
|
|
w.WriteHeader(http.StatusNoContent)
|
|
}
|