Repository navigation
Expand file tree
/
Copy pathquestion_handler.go
More file actions
586 lines (543 loc) · 19.4 KB
/
Copy pathquestion_handler.go
File metadata and controls
586 lines (543 loc) · 19.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
package handler
import (
"context"
"database/sql"
"encoding/json"
"errors"
"fmt"
"net/http"
"strings"
"github.com/calnode/calnode/internal/booking"
"github.com/calnode/calnode/internal/i18n"
"github.com/calnode/calnode/internal/uid"
)
// questionJSON is the API representation of an event-type intake question.
type questionJSON struct {
ID string `json:"id"`
EventTypeID string `json:"event_type_id"`
Label string `json:"label"`
Type string `json:"type"`
Options []string `json:"options,omitempty"`
Required bool `json:"required"`
Position int `json:"position"`
}
// answerJSON is the API representation of a booking answer.
type answerJSON struct {
QuestionID string `json:"question_id"`
Label string `json:"label"`
Type string `json:"type"`
Value string `json:"value"`
}
// ListQuestions handles GET /v1/event-types/{slug}/questions (public).
// Returns questions ordered by position for the booking form.
// Only returns questions for active, public event types.
func (h *Handler) ListQuestions(w http.ResponseWriter, r *http.Request) {
slug := r.PathValue("slug")
var etID string
err := h.db.QueryRowContext(r.Context(),
`SELECT id FROM event_types WHERE slug = ? AND is_active = 1 AND is_public = 1`, slug).Scan(&etID)
if errors.Is(err, sql.ErrNoRows) {
h.writeError(w, http.StatusNotFound, "event type not found")
return
}
if err != nil {
h.logger.ErrorContext(r.Context(), "list questions: lookup", "error", err)
h.writeError(w, http.StatusInternalServerError, "internal error")
return
}
rows, err := h.db.QueryContext(r.Context(), `
SELECT id, event_type_id, label, type, options, required, position
FROM event_type_questions
WHERE event_type_id = ?
ORDER BY position, id`, etID)
if err != nil {
h.logger.ErrorContext(r.Context(), "list questions: query", "error", err)
h.writeError(w, http.StatusInternalServerError, "internal error")
return
}
defer rows.Close()
items := []questionJSON{}
for rows.Next() {
q, err := scanQuestion(rows)
if err != nil {
h.logger.ErrorContext(r.Context(), "list questions: scan", "error", err)
h.writeError(w, http.StatusInternalServerError, "internal error")
return
}
items = append(items, *q)
}
if err := rows.Err(); err != nil {
h.logger.ErrorContext(r.Context(), "list questions: rows", "error", err)
h.writeError(w, http.StatusInternalServerError, "internal error")
return
}
h.writeJSON(w, http.StatusOK, map[string]any{"items": items})
}
// ListQuestionsAdmin handles GET /v1/event-types/{slug}/questions/admin (auth required).
// Like ListQuestions but skips is_active/is_public checks so admins can manage
// questions on inactive or private event types.
func (h *Handler) ListQuestionsAdmin(w http.ResponseWriter, r *http.Request) {
user, _ := userFromContext(r.Context())
slug := r.PathValue("slug")
var etID string
err := h.db.QueryRowContext(r.Context(),
`SELECT id FROM event_types WHERE slug = ? AND user_id = ?`, slug, user.ID).Scan(&etID)
if errors.Is(err, sql.ErrNoRows) {
h.writeError(w, http.StatusNotFound, "event type not found")
return
}
if err != nil {
h.logger.ErrorContext(r.Context(), "list questions admin: lookup", "error", err)
h.writeError(w, http.StatusInternalServerError, "internal error")
return
}
rows, err := h.db.QueryContext(r.Context(), `
SELECT id, event_type_id, label, type, options, required, position
FROM event_type_questions
WHERE event_type_id = ?
ORDER BY position, id`, etID)
if err != nil {
h.logger.ErrorContext(r.Context(), "list questions admin: query", "error", err)
h.writeError(w, http.StatusInternalServerError, "internal error")
return
}
defer rows.Close()
items := []questionJSON{}
for rows.Next() {
q, err := scanQuestion(rows)
if err != nil {
h.logger.ErrorContext(r.Context(), "list questions admin: scan", "error", err)
h.writeError(w, http.StatusInternalServerError, "internal error")
return
}
items = append(items, *q)
}
if err := rows.Err(); err != nil {
h.logger.ErrorContext(r.Context(), "list questions admin: rows", "error", err)
h.writeError(w, http.StatusInternalServerError, "internal error")
return
}
h.writeJSON(w, http.StatusOK, map[string]any{"items": items})
}
// CreateQuestion handles POST /v1/event-types/{slug}/questions (admin).
func (h *Handler) CreateQuestion(w http.ResponseWriter, r *http.Request) {
user, _ := userFromContext(r.Context())
slug := r.PathValue("slug")
r.Body = http.MaxBytesReader(w, r.Body, 32<<10)
var req struct {
Label string `json:"label"`
Type string `json:"type"`
Options []string `json:"options"`
Required bool `json:"required"`
Position *int `json:"position"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
h.writeError(w, http.StatusBadRequest, "invalid JSON")
return
}
req.Label = strings.TrimSpace(req.Label)
req.Type = strings.TrimSpace(req.Type)
if req.Label == "" {
h.writeError(w, http.StatusBadRequest, "label is required")
return
}
switch req.Type {
case "text", "checkbox":
case "select":
if len(req.Options) == 0 {
h.writeError(w, http.StatusBadRequest, "options is required for type 'select'")
return
}
default:
h.writeError(w, http.StatusBadRequest, "type must be one of: text, select, checkbox")
return
}
// Verify caller owns this event type.
var etID string
err := h.db.QueryRowContext(r.Context(),
`SELECT id FROM event_types WHERE slug = ? AND user_id = ?`, slug, user.ID).Scan(&etID)
if errors.Is(err, sql.ErrNoRows) {
h.writeError(w, http.StatusNotFound, "event type not found")
return
}
if err != nil {
h.logger.ErrorContext(r.Context(), "create question: lookup", "error", err)
h.writeError(w, http.StatusInternalServerError, "internal error")
return
}
// Serialise options for select type.
var optJSON *string
if req.Type == "select" {
b, _ := json.Marshal(req.Options)
s := string(b)
optJSON = &s
}
id := uid.New()
requiredInt := 0
if req.Required {
requiredInt = 1
}
var position int
if req.Position != nil {
position = *req.Position
if _, err := h.db.ExecContext(r.Context(), `
INSERT INTO event_type_questions (id, event_type_id, label, type, options, required, position)
VALUES (?, ?, ?, ?, ?, ?, ?)`,
id, etID, req.Label, req.Type, optJSON, requiredInt, position); err != nil {
h.logger.ErrorContext(r.Context(), "create question: insert", "error", err)
h.writeError(w, http.StatusInternalServerError, "internal error")
return
}
} else {
// Compute position atomically in the INSERT to avoid a SELECT+INSERT race
// when two requests arrive concurrently for the same event type.
row := h.db.QueryRowContext(r.Context(), `
INSERT INTO event_type_questions (id, event_type_id, label, type, options, required, position)
VALUES (?, ?, ?, ?, ?, ?,
(SELECT COALESCE(MAX(position)+1, 0) FROM event_type_questions WHERE event_type_id = ?))
RETURNING position`,
id, etID, req.Label, req.Type, optJSON, requiredInt, etID)
if err := row.Scan(&position); err != nil {
h.logger.ErrorContext(r.Context(), "create question: insert", "error", err)
h.writeError(w, http.StatusInternalServerError, "internal error")
return
}
}
q := &questionJSON{
ID: id,
EventTypeID: etID,
Label: req.Label,
Type: req.Type,
Options: req.Options,
Required: req.Required,
Position: position,
}
h.writeJSON(w, http.StatusCreated, q)
}
// UpdateQuestion handles PATCH /v1/event-types/{slug}/questions/{id} (admin).
func (h *Handler) UpdateQuestion(w http.ResponseWriter, r *http.Request) {
user, _ := userFromContext(r.Context())
slug := r.PathValue("slug")
qID := r.PathValue("id")
r.Body = http.MaxBytesReader(w, r.Body, 32<<10)
var req struct {
Label *string `json:"label"`
Type *string `json:"type"`
Options []string `json:"options"`
Required *bool `json:"required"`
Position *int `json:"position"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
h.writeError(w, http.StatusBadRequest, "invalid JSON")
return
}
// Load current question verifying ownership via event_types.user_id.
var current questionJSON
var optRaw sql.NullString
var requiredInt int
err := h.db.QueryRowContext(r.Context(), `
SELECT q.id, q.event_type_id, q.label, q.type, q.options, q.required, q.position
FROM event_type_questions q
JOIN event_types et ON et.id = q.event_type_id
WHERE q.id = ? AND et.slug = ? AND et.user_id = ?`, qID, slug, user.ID).
Scan(¤t.ID, ¤t.EventTypeID, ¤t.Label, ¤t.Type,
&optRaw, &requiredInt, ¤t.Position)
if errors.Is(err, sql.ErrNoRows) {
h.writeError(w, http.StatusNotFound, "question not found")
return
}
if err != nil {
h.logger.ErrorContext(r.Context(), "update question: load", "error", err)
h.writeError(w, http.StatusInternalServerError, "internal error")
return
}
current.Required = requiredInt != 0
if optRaw.Valid {
_ = json.Unmarshal([]byte(optRaw.String), ¤t.Options)
}
// Apply partial updates.
if req.Label != nil {
current.Label = strings.TrimSpace(*req.Label)
if current.Label == "" {
h.writeError(w, http.StatusBadRequest, "label must not be empty")
return
}
}
if req.Type != nil {
switch *req.Type {
case "text", "checkbox", "select":
current.Type = *req.Type
default:
h.writeError(w, http.StatusBadRequest, "type must be one of: text, select, checkbox")
return
}
}
if req.Options != nil {
current.Options = req.Options
}
if current.Type == "select" && len(current.Options) == 0 {
h.writeError(w, http.StatusBadRequest, "options is required for type 'select'")
return
}
if req.Required != nil {
current.Required = *req.Required
}
if req.Position != nil {
current.Position = *req.Position
}
var optJSON *string
if current.Type == "select" {
b, _ := json.Marshal(current.Options)
s := string(b)
optJSON = &s
}
requiredSave := 0
if current.Required {
requiredSave = 1
}
if _, err := h.db.ExecContext(r.Context(), `
UPDATE event_type_questions
SET label = ?, type = ?, options = ?, required = ?, position = ?
WHERE id = ?`,
current.Label, current.Type, optJSON, requiredSave, current.Position, qID); err != nil {
h.logger.ErrorContext(r.Context(), "update question: save", "error", err)
h.writeError(w, http.StatusInternalServerError, "internal error")
return
}
h.writeJSON(w, http.StatusOK, current)
}
// DeleteQuestion handles DELETE /v1/event-types/{slug}/questions/{id} (admin).
func (h *Handler) DeleteQuestion(w http.ResponseWriter, r *http.Request) {
user, _ := userFromContext(r.Context())
slug := r.PathValue("slug")
qID := r.PathValue("id")
res, err := h.db.ExecContext(r.Context(), `
DELETE FROM event_type_questions
WHERE id = (
SELECT q.id FROM event_type_questions q
JOIN event_types et ON et.id = q.event_type_id
WHERE q.id = ? AND et.slug = ? AND et.user_id = ?
)`, qID, slug, user.ID)
if err != nil {
h.logger.ErrorContext(r.Context(), "delete question", "error", err)
h.writeError(w, http.StatusInternalServerError, "internal error")
return
}
if n, _ := res.RowsAffected(); n == 0 {
h.writeError(w, http.StatusNotFound, "question not found")
return
}
w.WriteHeader(http.StatusNoContent)
}
// GetBookingAnswers handles GET /v1/bookings/{id}/answers (admin).
// Returns the intake question answers for a booking owned by the caller.
func (h *Handler) GetBookingAnswers(w http.ResponseWriter, r *http.Request) {
user, _ := userFromContext(r.Context())
id := r.PathValue("id")
// Verify caller owns the booking.
var hostID string
err := h.db.QueryRowContext(r.Context(),
`SELECT host_id FROM bookings WHERE id = ?`, id).Scan(&hostID)
if errors.Is(err, sql.ErrNoRows) {
h.writeError(w, http.StatusNotFound, "booking not found")
return
}
if err != nil {
h.logger.ErrorContext(r.Context(), "get booking answers: lookup", "error", err)
h.writeError(w, http.StatusInternalServerError, "internal error")
return
}
if hostID != user.ID {
h.writeError(w, http.StatusNotFound, "booking not found")
return
}
rows, err := h.db.QueryContext(r.Context(), `
SELECT a.question_id, q.label, q.type, a.value
FROM booking_answers a
JOIN event_type_questions q ON q.id = a.question_id
WHERE a.booking_id = ?
ORDER BY q.position, q.id`, id)
if err != nil {
h.logger.ErrorContext(r.Context(), "get booking answers: query", "error", err)
h.writeError(w, http.StatusInternalServerError, "internal error")
return
}
defer rows.Close()
items := []answerJSON{}
for rows.Next() {
var a answerJSON
if err := rows.Scan(&a.QuestionID, &a.Label, &a.Type, &a.Value); err != nil {
h.logger.ErrorContext(r.Context(), "get booking answers: scan", "error", err)
h.writeError(w, http.StatusInternalServerError, "internal error")
return
}
items = append(items, a)
}
if err := rows.Err(); err != nil {
h.logger.ErrorContext(r.Context(), "get booking answers: rows", "error", err)
h.writeError(w, http.StatusInternalServerError, "internal error")
return
}
h.writeJSON(w, http.StatusOK, map[string]any{"items": items})
}
// scanQuestion scans a row from event_type_questions into a questionJSON.
type questionScanner interface {
Scan(dest ...any) error
}
func scanQuestion(s questionScanner) (*questionJSON, error) {
var q questionJSON
var optRaw sql.NullString
var requiredInt int
if err := s.Scan(&q.ID, &q.EventTypeID, &q.Label, &q.Type, &optRaw, &requiredInt, &q.Position); err != nil {
return nil, err
}
q.Required = requiredInt != 0
if optRaw.Valid && optRaw.String != "" {
_ = json.Unmarshal([]byte(optRaw.String), &q.Options)
}
return &q, nil
}
// validateAnswers loads the questions for an event type, checks that all required
// questions have answers, validates select-option values, and rejects answers for
// questions that don't belong to this event type. Returns the []booking.Answer
// slice ready for bookingSvc.Create, or writes an error response and returns an error.
// answerError is a client-fault validation failure from validateAnswersCore (unknown
// or duplicate question, missing required field, invalid select option). The REST
// wrapper maps it to 400; other errors (DB failures) map to 500. The MCP tool surfaces
// its message directly.
type answerError struct{ msg string }
func (e *answerError) Error() string { return e.msg }
// validateAnswers is the HTTP wrapper: it runs validateAnswersCore and translates the
// result into a status code (400 for client-fault answer errors, 500 otherwise).
func (h *Handler) validateAnswers(w http.ResponseWriter, r *http.Request, eventTypeID string, loc *i18n.Locale, rawAnswers []struct {
QuestionID string `json:"question_id"`
Value string `json:"value"`
}) ([]booking.Answer, error) {
in := make([]booking.Answer, len(rawAnswers))
for i, a := range rawAnswers {
in[i] = booking.Answer{QuestionID: a.QuestionID, Value: a.Value}
}
out, err := h.validateAnswersCore(r.Context(), eventTypeID, in, loc)
if err != nil {
var ae *answerError
if errors.As(err, &ae) {
h.writeError(w, http.StatusBadRequest, ae.msg)
} else {
h.logger.ErrorContext(r.Context(), "validate answers", "error", err)
h.writeError(w, http.StatusInternalServerError, "internal error")
}
return nil, err
}
return out, nil
}
// checkboxTicked reports whether a submitted checkbox value means "ticked". Liberal in
// what it accepts — the two booking surfaces have historically sent "yes" and "Yes", and
// MCP/API callers send whatever a model or integration picked — but validateAnswersCore is
// strict in what it stores, canonicalising to "yes"/"no". Anything unrecognised (including
// "no", "false", "") counts as unticked.
func checkboxTicked(v string) bool {
switch strings.ToLower(strings.TrimSpace(v)) {
case "yes", "true", "1", "on", "checked":
return true
}
return false
}
// validateAnswersCore validates submitted intake answers against an event type's
// questions and returns the canonical answer slice. Shared by the REST booking handler
// and the MCP create_booking tool — no HTTP coupling. Client-fault problems are
// returned as *answerError; DB failures as plain wrapped errors.
// loc translates the two client-fault messages a real booker can actually trigger
// (required field missing, invalid select option). The other two (unknown/duplicate
// question_id) are only reachable from a malformed client, so they stay English as API
// diagnostics. A nil loc is fine — i18n.Locale.T falls back to English — which is what
// the MCP tool path passes when the caller has no browser locale.
func (h *Handler) validateAnswersCore(ctx context.Context, eventTypeID string, rawAnswers []booking.Answer, loc *i18n.Locale) ([]booking.Answer, error) {
// Load all questions for this event type (label included for error messages).
rows, err := h.db.QueryContext(ctx, `
SELECT id, label, type, options, required
FROM event_type_questions WHERE event_type_id = ?`, eventTypeID)
if err != nil {
return nil, fmt.Errorf("validate answers: load questions: %w", err)
}
defer rows.Close()
type question struct {
id string
label string
qtype string
options []string
required bool
}
questions := map[string]question{}
for rows.Next() {
var q question
var optRaw sql.NullString
var reqInt int
if err := rows.Scan(&q.id, &q.label, &q.qtype, &optRaw, &reqInt); err != nil {
return nil, fmt.Errorf("validate answers: scan: %w", err)
}
q.required = reqInt != 0
if optRaw.Valid && optRaw.String != "" {
_ = json.Unmarshal([]byte(optRaw.String), &q.options)
}
questions[q.id] = q
}
if err := rows.Err(); err != nil {
return nil, fmt.Errorf("validate answers: rows: %w", err)
}
// Index submitted answers by question_id; reject duplicates and unknown IDs.
submitted := map[string]string{}
for _, a := range rawAnswers {
if _, ok := questions[a.QuestionID]; !ok {
return nil, &answerError{fmt.Sprintf("unknown question_id %q", a.QuestionID)}
}
if _, dup := submitted[a.QuestionID]; dup {
return nil, &answerError{fmt.Sprintf("duplicate answer for question_id %q", a.QuestionID)}
}
submitted[a.QuestionID] = a.Value
}
// Validate each question.
var out []booking.Answer
for _, q := range questions {
val, answered := submitted[q.id]
// Checkboxes are normalised and required-checked here rather than by the generic
// rule below, because "no" is a non-empty answer: the generic rule sees it as
// satisfied, so a required consent checkbox ("I agree to the terms") submitted
// unticked used to create the booking anyway. Normalising centrally also makes the
// stored value identical whichever surface produced it — the booking page sent
// "yes"/"no", the embed widget sent "Yes" or omitted the answer entirely, and MCP
// callers send whatever the model picked.
if q.qtype == "checkbox" {
ticked := answered && checkboxTicked(val)
if q.required && !ticked {
return nil, &answerError{loc.Tf("err_required_checkbox", q.label)}
}
if answered {
canonical := "no"
if ticked {
canonical = "yes"
}
out = append(out, booking.Answer{QuestionID: q.id, Value: canonical})
}
continue
}
if q.required && (!answered || strings.TrimSpace(val) == "") {
return nil, &answerError{loc.Tf("err_required_field", q.label)}
}
if q.qtype == "select" && answered && val != "" {
valid := false
for _, opt := range q.options {
if opt == val {
valid = true
break
}
}
if !valid {
return nil, &answerError{loc.Tf("err_invalid_option", q.label, val)}
}
}
if answered {
out = append(out, booking.Answer{QuestionID: q.id, Value: val})
}
}
return out, nil
}