Repository navigation
Expand file tree
/
Copy pathapi_test.go
More file actions
833 lines (725 loc) · 28.3 KB
/
Copy pathapi_test.go
File metadata and controls
833 lines (725 loc) · 28.3 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
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
package handler_test
import (
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/calnode/calnode/internal/handler"
"github.com/calnode/calnode/internal/uid"
)
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
// setup bootstraps the workspace and returns (handler, plainAPIKey, userID).
func setupWorkspace(t *testing.T) (*handler.Handler, string, string) {
t.Helper()
h := newTestHandler(t)
body := `{"name":"Test User","email":"test@example.com","timezone":"UTC"}`
req := httptest.NewRequest(http.MethodPost, "/v1/setup", strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
rec := httptest.NewRecorder()
h.Setup(rec, req)
if rec.Code != http.StatusCreated {
t.Fatalf("setup: got %d — %s", rec.Code, rec.Body.String())
}
var resp struct {
APIKey string `json:"api_key"`
UserID string `json:"user_id"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
t.Fatalf("setup: decode response: %v", err)
}
return h, resp.APIKey, resp.UserID
}
func authReq(method, path, body, apiKey string) *http.Request {
var r *http.Request
if body != "" {
r = httptest.NewRequest(method, path, strings.NewReader(body))
r.Header.Set("Content-Type", "application/json")
} else {
r = httptest.NewRequest(method, path, nil)
}
r.Header.Set("X-API-Key", apiKey)
return r
}
// ---------------------------------------------------------------------------
// Response helpers
//
// Reading a body before checking the status hides the one thing that explains a
// failure, and `id := body["id"].(string)` on a body that has no id PANICS — which
// aborts the whole package, so a single bad request reports a nil-interface stack
// trace and no other handler test result at all.
//
// That is not hypothetical: a webhook create returning
// `400 webhook URL must not resolve to a private or loopback address` presented as an
// unrelated-looking panic, with the status and message nowhere on screen.
//
// These four keep a failure local and self-explaining. Each takes a `what` naming the
// call, so a test that makes several requests still says which one failed.
// ---------------------------------------------------------------------------
// mustStatus fails the test unless rec carries the wanted status, quoting the body.
func mustStatus(t *testing.T, rec *httptest.ResponseRecorder, want int, what string) {
t.Helper()
if rec.Code != want {
t.Fatalf("%s: status = %d; want %d — %s", what, rec.Code, want, rec.Body.String())
}
}
// mustJSON asserts the status first, then decodes the JSON body into a map.
func mustJSON(t *testing.T, rec *httptest.ResponseRecorder, want int, what string) map[string]any {
t.Helper()
mustStatus(t, rec, want, what)
var body map[string]any
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
t.Fatalf("%s: decode body: %v — %s", what, err, rec.Body.String())
}
return body
}
// mustCreated is mustJSON for 201, which is what most of these calls return.
func mustCreated(t *testing.T, rec *httptest.ResponseRecorder, what string) map[string]any {
t.Helper()
return mustJSON(t, rec, http.StatusCreated, what)
}
// mustString reads a string field, failing with the whole body when it is missing or of
// another type. The two-value assertion alone yields "" and defers the failure to
// something downstream — a 404 on an empty id — that cannot explain itself.
func mustString(t *testing.T, body map[string]any, key, what string) string {
t.Helper()
v, ok := body[key].(string)
if !ok {
t.Fatalf("%s: response has no string %q — %v", what, key, body)
}
return v
}
// seedEventType creates an event type via the HTTP handler.
func seedEventTypeHTTP(t *testing.T, h *handler.Handler, apiKey string) (slug, id string) {
t.Helper()
slug = "test-meeting-" + uid.New()[:8]
// max_active_bookings:0 = unlimited, so the many tests that create several
// bookings for one invitee aren't tripped by the per-invitee cap (default 1).
// The cap has its own dedicated test. max_future_days:0 = unlimited (capped at
// validateBookingTime's 365-day safety guard), so tests using far-future fixture
// dates aren't tripped by the 60-day default; that default has its own test too.
body := fmt.Sprintf(`{"slug":%q,"name":"Test Meeting","duration_minutes":30,"max_active_bookings":0,"max_future_days":0}`, slug)
req := authReq(http.MethodPost, "/v1/event-types", body, apiKey)
rec := httptest.NewRecorder()
h.RequireAuth(h.CreateEventType)(rec, req)
if rec.Code != http.StatusCreated {
t.Fatalf("seed event type: got %d — %s", rec.Code, rec.Body.String())
}
var resp struct {
ID string `json:"id"`
}
json.Unmarshal(rec.Body.Bytes(), &resp)
seedFullAvailability(t, h, apiKey)
return slug, resp.ID
}
// seedFullAvailability gives the workspace owner a wide-open weekly schedule (every
// day, 00:00-23:59, global — no event_type_id) so booking-creation tests that aren't
// specifically about availability rules don't also have to reason about day-of-week/
// hour matching. validateBookingTime (internal/handler/booking_handler.go) requires a
// host to have SOME configured availability before they're bookable, matching what
// /slots would ever have offered — a fresh host with zero rules is correctly
// unbookable in both places, but that's not what most of these tests are about.
func seedFullAvailability(t *testing.T, h *handler.Handler, apiKey string) {
t.Helper()
for day := 0; day < 7; day++ {
body := fmt.Sprintf(`{"day_of_week":%d,"start_time":"00:00","end_time":"23:59"}`, day)
req := authReq(http.MethodPost, "/v1/availability-rules", body, apiKey)
rec := httptest.NewRecorder()
h.RequireAuth(h.CreateAvailabilityRule)(rec, req)
if rec.Code != http.StatusCreated {
t.Fatalf("seed availability day %d: %d — %s", day, rec.Code, rec.Body.String())
}
}
}
// ---------------------------------------------------------------------------
// Setup
// ---------------------------------------------------------------------------
func TestSetup_success(t *testing.T) {
h := newTestHandler(t)
body := `{"name":"Alice","email":"alice@example.com","timezone":"Pacific/Auckland"}`
req := httptest.NewRequest(http.MethodPost, "/v1/setup", strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
rec := httptest.NewRecorder()
h.Setup(rec, req)
if rec.Code != http.StatusCreated {
t.Fatalf("status = %d; want 201 — %s", rec.Code, rec.Body.String())
}
var resp map[string]string
json.Unmarshal(rec.Body.Bytes(), &resp)
if !strings.HasPrefix(resp["api_key"], "cno_") {
t.Errorf("api_key = %q; want cno_ prefix", resp["api_key"])
}
if resp["user_id"] == "" {
t.Error("user_id is empty")
}
}
func TestSetup_alreadyConfigured(t *testing.T) {
h, _, _ := setupWorkspace(t)
body := `{"name":"Bob","email":"bob@example.com"}`
req := httptest.NewRequest(http.MethodPost, "/v1/setup", strings.NewReader(body))
rec := httptest.NewRecorder()
h.Setup(rec, req)
if rec.Code != http.StatusConflict {
t.Errorf("status = %d; want 409", rec.Code)
}
}
func TestSetup_missingFields(t *testing.T) {
h := newTestHandler(t)
req := httptest.NewRequest(http.MethodPost, "/v1/setup",
strings.NewReader(`{"name":"Alice"}`))
rec := httptest.NewRecorder()
h.Setup(rec, req)
if rec.Code != http.StatusBadRequest {
t.Errorf("status = %d; want 400", rec.Code)
}
}
// ---------------------------------------------------------------------------
// Auth middleware
// ---------------------------------------------------------------------------
func TestGetMe_returnsSetupUser(t *testing.T) {
h := newTestHandler(t)
body := `{"name":"Alice Tester","email":"alice@example.com","timezone":"Pacific/Auckland"}`
req := httptest.NewRequest(http.MethodPost, "/v1/setup", strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
rec := httptest.NewRecorder()
h.Setup(rec, req)
if rec.Code != http.StatusCreated {
t.Fatalf("setup: %d — %s", rec.Code, rec.Body.String())
}
var setup struct {
APIKey string `json:"api_key"`
}
json.Unmarshal(rec.Body.Bytes(), &setup)
req2 := authReq(http.MethodGet, "/v1/users/me", "", setup.APIKey)
rec2 := httptest.NewRecorder()
h.RequireAuth(h.GetMe)(rec2, req2)
if rec2.Code != http.StatusOK {
t.Fatalf("get me: %d — %s", rec2.Code, rec2.Body.String())
}
var me map[string]any
json.Unmarshal(rec2.Body.Bytes(), &me)
if me["email"] != "alice@example.com" {
t.Errorf("email = %v; want alice@example.com", me["email"])
}
if me["name"] != "Alice Tester" {
t.Errorf("name = %v; want Alice Tester", me["name"])
}
if me["timezone"] != "Pacific/Auckland" {
t.Errorf("timezone = %v; want Pacific/Auckland", me["timezone"])
}
if me["is_admin"] != true {
t.Errorf("is_admin = %v; want true", me["is_admin"])
}
}
func TestRequireAuth_noKey(t *testing.T) {
h, _, _ := setupWorkspace(t)
req := httptest.NewRequest(http.MethodGet, "/v1/users/me", nil)
rec := httptest.NewRecorder()
h.RequireAuth(h.GetMe)(rec, req)
if rec.Code != http.StatusUnauthorized {
t.Errorf("status = %d; want 401", rec.Code)
}
}
func TestRequireAuth_invalidKey(t *testing.T) {
h, _, _ := setupWorkspace(t)
req := authReq(http.MethodGet, "/v1/users/me", "", "cno_notavalidkey")
rec := httptest.NewRecorder()
h.RequireAuth(h.GetMe)(rec, req)
if rec.Code != http.StatusUnauthorized {
t.Errorf("status = %d; want 401", rec.Code)
}
}
func TestRequireAuth_validKey(t *testing.T) {
h, key, _ := setupWorkspace(t)
req := authReq(http.MethodGet, "/v1/users/me", "", key)
rec := httptest.NewRecorder()
h.RequireAuth(h.GetMe)(rec, req)
if rec.Code != http.StatusOK {
t.Errorf("status = %d; want 200 — %s", rec.Code, rec.Body.String())
}
}
func TestRequireAuth_bearerToken(t *testing.T) {
h, key, _ := setupWorkspace(t)
req := httptest.NewRequest(http.MethodGet, "/v1/users/me", nil)
req.Header.Set("Authorization", "Bearer "+key)
rec := httptest.NewRecorder()
h.RequireAuth(h.GetMe)(rec, req)
if rec.Code != http.StatusOK {
t.Errorf("status = %d; want 200", rec.Code)
}
}
// ---------------------------------------------------------------------------
// Event types
// ---------------------------------------------------------------------------
func TestCreateEventType_success(t *testing.T) {
h, key, _ := setupWorkspace(t)
body := `{"slug":"30-min-call","name":"30-Minute Call","duration_minutes":30,"routing_mode":"fixed"}`
req := authReq(http.MethodPost, "/v1/event-types", body, key)
rec := httptest.NewRecorder()
h.RequireAuth(h.CreateEventType)(rec, req)
if rec.Code != http.StatusCreated {
t.Fatalf("status = %d; want 201 — %s", rec.Code, rec.Body.String())
}
var et map[string]any
json.Unmarshal(rec.Body.Bytes(), &et)
if et["slug"] != "30-min-call" {
t.Errorf("slug = %v; want 30-min-call", et["slug"])
}
if et["duration_minutes"].(float64) != 30 {
t.Errorf("duration_minutes = %v; want 30", et["duration_minutes"])
}
}
func TestCreateEventType_duplicateSlug(t *testing.T) {
h, key, _ := setupWorkspace(t)
body := `{"slug":"my-slug","name":"First","duration_minutes":30}`
for _, wantCode := range []int{http.StatusCreated, http.StatusConflict} {
req := authReq(http.MethodPost, "/v1/event-types", body, key)
rec := httptest.NewRecorder()
h.RequireAuth(h.CreateEventType)(rec, req)
if rec.Code != wantCode {
t.Errorf("attempt: status = %d; want %d — %s", rec.Code, wantCode, rec.Body.String())
}
}
}
func TestListEventTypes(t *testing.T) {
h, key, _ := setupWorkspace(t)
for _, slug := range []string{"et-a", "et-b", "et-c"} {
body := fmt.Sprintf(`{"slug":%q,"name":"Meeting","duration_minutes":30}`, slug)
req := authReq(http.MethodPost, "/v1/event-types", body, key)
rec := httptest.NewRecorder()
h.RequireAuth(h.CreateEventType)(rec, req)
if rec.Code != http.StatusCreated {
t.Fatalf("create %s: %d", slug, rec.Code)
}
}
req := authReq(http.MethodGet, "/v1/event-types", "", key)
rec := httptest.NewRecorder()
h.RequireAuth(h.ListEventTypes)(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("list: status = %d — %s", rec.Code, rec.Body.String())
}
var resp struct {
Items []map[string]any `json:"items"`
}
json.Unmarshal(rec.Body.Bytes(), &resp)
if len(resp.Items) != 3 {
t.Errorf("len(items) = %d; want 3", len(resp.Items))
}
}
func TestGetEventType_notFound(t *testing.T) {
h, key, _ := setupWorkspace(t)
req := authReq(http.MethodGet, "/v1/event-types/nonexistent", "", key)
req.SetPathValue("slug", "nonexistent")
rec := httptest.NewRecorder()
h.RequireAuth(h.GetEventType)(rec, req)
if rec.Code != http.StatusNotFound {
t.Errorf("status = %d; want 404", rec.Code)
}
}
func TestPatchEventType(t *testing.T) {
h, key, _ := setupWorkspace(t)
slug, _ := seedEventTypeHTTP(t, h, key)
req := authReq(http.MethodPatch, "/v1/event-types/"+slug,
`{"name":"Updated Name","duration_minutes":45}`, key)
req.SetPathValue("slug", slug)
rec := httptest.NewRecorder()
h.RequireAuth(h.PatchEventType)(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("patch: status = %d — %s", rec.Code, rec.Body.String())
}
var et map[string]any
json.Unmarshal(rec.Body.Bytes(), &et)
if et["name"] != "Updated Name" {
t.Errorf("name = %v; want Updated Name", et["name"])
}
if et["duration_minutes"].(float64) != 45 {
t.Errorf("duration_minutes = %v; want 45", et["duration_minutes"])
}
}
func TestPatchEventType_emptyNameRejected(t *testing.T) {
h, key, _ := setupWorkspace(t)
slug, _ := seedEventTypeHTTP(t, h, key)
req := authReq(http.MethodPatch, "/v1/event-types/"+slug, `{"name":""}`, key)
req.SetPathValue("slug", slug)
rec := httptest.NewRecorder()
h.RequireAuth(h.PatchEventType)(rec, req)
if rec.Code != http.StatusBadRequest {
t.Errorf("status = %d; want 400 for empty name", rec.Code)
}
}
// TestPatchEventType_msgFields_nullVsEmptyString locks in the contract the admin UI's
// save button depends on: JSON null means "leave this field unchanged" (for partial-PATCH
// callers), while an empty string means "clear it". The event-types settings page always
// saves the whole form, so it must send "" (not null) to actually clear a blanked custom
// message — sending null there would silently keep the old value while the UI shows blank.
func TestPatchEventType_msgFields_nullVsEmptyString(t *testing.T) {
h, key, _ := setupWorkspace(t)
slug, _ := seedEventTypeHTTP(t, h, key)
patch := func(body string) map[string]any {
t.Helper()
req := authReq(http.MethodPatch, "/v1/event-types/"+slug, body, key)
req.SetPathValue("slug", slug)
rec := httptest.NewRecorder()
h.RequireAuth(h.PatchEventType)(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("patch %s: %d — %s", body, rec.Code, rec.Body.String())
}
var out map[string]any
json.Unmarshal(rec.Body.Bytes(), &out) //nolint:errcheck
return out
}
patch(`{"msg_greeting":"Custom hello","msg_confirmation":"Custom note"}`)
afterNull := patch(`{"msg_greeting":null,"msg_confirmation":null}`)
if afterNull["msg_greeting"] != "Custom hello" || afterNull["msg_confirmation"] != "Custom note" {
t.Errorf("null should leave fields unchanged, got msg_greeting=%v msg_confirmation=%v",
afterNull["msg_greeting"], afterNull["msg_confirmation"])
}
afterEmpty := patch(`{"msg_greeting":"","msg_confirmation":""}`)
if afterEmpty["msg_greeting"] != nil || afterEmpty["msg_confirmation"] != nil {
t.Errorf("empty string should clear the fields, got msg_greeting=%v msg_confirmation=%v",
afterEmpty["msg_greeting"], afterEmpty["msg_confirmation"])
}
}
func TestDeleteEventType(t *testing.T) {
h, key, _ := setupWorkspace(t)
slug, _ := seedEventTypeHTTP(t, h, key)
req := authReq(http.MethodDelete, "/v1/event-types/"+slug, "", key)
req.SetPathValue("slug", slug)
rec := httptest.NewRecorder()
h.RequireAuth(h.DeleteEventType)(rec, req)
if rec.Code != http.StatusNoContent {
t.Fatalf("delete: status = %d — %s", rec.Code, rec.Body.String())
}
// Confirm it's gone.
req2 := authReq(http.MethodGet, "/v1/event-types/"+slug, "", key)
req2.SetPathValue("slug", slug)
rec2 := httptest.NewRecorder()
h.RequireAuth(h.GetEventType)(rec2, req2)
if rec2.Code != http.StatusNotFound {
t.Errorf("after delete: status = %d; want 404", rec2.Code)
}
}
// ---------------------------------------------------------------------------
// Availability rules
// ---------------------------------------------------------------------------
func TestCreateAndListAvailabilityRule(t *testing.T) {
h, key, _ := setupWorkspace(t)
// Create Mon 09:00-17:00.
body := `{"day_of_week":1,"start_time":"09:00","end_time":"17:00"}`
req := authReq(http.MethodPost, "/v1/availability-rules", body, key)
rec := httptest.NewRecorder()
h.RequireAuth(h.CreateAvailabilityRule)(rec, req)
created := mustCreated(t, rec, "create rule")
ruleID := mustString(t, created, "id", "create rule")
if ruleID == "" {
t.Fatal("rule id is empty")
}
// List.
req2 := authReq(http.MethodGet, "/v1/availability-rules", "", key)
rec2 := httptest.NewRecorder()
h.RequireAuth(h.ListAvailabilityRules)(rec2, req2)
if rec2.Code != http.StatusOK {
t.Fatalf("list rules: %d", rec2.Code)
}
var list struct {
Items []map[string]any `json:"items"`
}
json.Unmarshal(rec2.Body.Bytes(), &list)
if len(list.Items) != 1 {
t.Errorf("len(items) = %d; want 1", len(list.Items))
}
// Delete.
req3 := authReq(http.MethodDelete, "/v1/availability-rules/"+ruleID, "", key)
req3.SetPathValue("id", ruleID)
rec3 := httptest.NewRecorder()
h.RequireAuth(h.DeleteAvailabilityRule)(rec3, req3)
if rec3.Code != http.StatusNoContent {
t.Errorf("delete rule: %d — %s", rec3.Code, rec3.Body.String())
}
}
// ---------------------------------------------------------------------------
// Slots
// ---------------------------------------------------------------------------
func TestGetSlots_noRules_returnsEmpty(t *testing.T) {
h, key, _ := setupWorkspace(t)
slug, _ := seedEventTypeHTTP(t, h, key)
// No availability rules set → no slots.
req := httptest.NewRequest(http.MethodGet,
"/v1/event-types/"+slug+"/slots?from=2026-06-15&to=2026-06-15&tz=UTC", nil)
req.SetPathValue("slug", slug)
rec := httptest.NewRecorder()
h.GetSlots(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("slots: %d — %s", rec.Code, rec.Body.String())
}
var resp struct {
Slots []any `json:"slots"`
}
json.Unmarshal(rec.Body.Bytes(), &resp)
if len(resp.Slots) != 0 {
t.Errorf("slots count = %d; want 0 (no rules set)", len(resp.Slots))
}
}
func TestGetSlots_withRules_returnsSlots(t *testing.T) {
h, key, userID := setupWorkspace(t)
// This test asserts the exact narrow window (09:00-17:00 Monday) a scoped rule
// produces, so it deliberately does NOT use seedEventTypeHTTP — that helper also
// seeds a wide-open global rule, which would union with the narrow one below and
// widen the effective window past what this test is asserting.
slug := "test-meeting-" + uid.New()[:8]
etBody := fmt.Sprintf(`{"slug":%q,"name":"Test Meeting","duration_minutes":30,"max_active_bookings":0,"max_future_days":0}`, slug)
etReq := authReq(http.MethodPost, "/v1/event-types", etBody, key)
etRec := httptest.NewRecorder()
h.RequireAuth(h.CreateEventType)(etRec, etReq)
if etRec.Code != http.StatusCreated {
t.Fatalf("create event type: %d — %s", etRec.Code, etRec.Body.String())
}
var etResp struct {
ID string `json:"id"`
}
json.Unmarshal(etRec.Body.Bytes(), &etResp)
etID := etResp.ID
body := fmt.Sprintf(`{"event_type_id":%q,"day_of_week":1,"start_time":"09:00","end_time":"17:00"}`, etID)
ruleReq := authReq(http.MethodPost, "/v1/availability-rules", body, key)
ruleRec := httptest.NewRecorder()
h.RequireAuth(h.CreateAvailabilityRule)(ruleRec, ruleReq)
if ruleRec.Code != http.StatusCreated {
t.Fatalf("create rule: %d — %s", ruleRec.Code, ruleRec.Body.String())
}
monday := nextMonday()
req := httptest.NewRequest(http.MethodGet,
"/v1/event-types/"+slug+"/slots?from="+monday+"&to="+monday+"&tz=UTC", nil)
req.SetPathValue("slug", slug)
rec := httptest.NewRecorder()
h.GetSlots(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("slots: %d — %s", rec.Code, rec.Body.String())
}
var resp struct {
Slots []slotResp `json:"slots"`
}
json.Unmarshal(rec.Body.Bytes(), &resp)
if len(resp.Slots) == 0 {
t.Errorf("slots: got 0; want >0 (rule set for Monday)")
}
// Verify first slot starts at 09:00 UTC.
if len(resp.Slots) > 0 {
start, err := time.Parse(time.RFC3339, resp.Slots[0].Start)
if err != nil {
t.Fatalf("parse first slot start: %v", err)
}
if start.UTC().Hour() != 9 || start.UTC().Minute() != 0 {
t.Errorf("first slot = %v; want 09:00 UTC", start)
}
// Each slot should carry the host's user ID.
if len(resp.Slots[0].HostIDs) != 1 || resp.Slots[0].HostIDs[0] != userID {
t.Errorf("host_ids = %v; want [%s]", resp.Slots[0].HostIDs, userID)
}
}
}
func TestGetSlots_notFound(t *testing.T) {
h, _, _ := setupWorkspace(t)
req := httptest.NewRequest(http.MethodGet,
"/v1/event-types/does-not-exist/slots?from=2026-06-15&to=2026-06-15", nil)
req.SetPathValue("slug", "does-not-exist")
rec := httptest.NewRecorder()
h.GetSlots(rec, req)
if rec.Code != http.StatusNotFound {
t.Errorf("status = %d; want 404", rec.Code)
}
}
func TestGetSlots_invalidTZ(t *testing.T) {
h, key, _ := setupWorkspace(t)
slug, _ := seedEventTypeHTTP(t, h, key)
req := httptest.NewRequest(http.MethodGet,
"/v1/event-types/"+slug+"/slots?tz=Not/ATimezone", nil)
req.SetPathValue("slug", slug)
rec := httptest.NewRecorder()
h.GetSlots(rec, req)
if rec.Code != http.StatusBadRequest {
t.Errorf("status = %d; want 400", rec.Code)
}
}
type slotResp struct {
Start string `json:"start"`
End string `json:"end"`
HostIDs []string `json:"host_ids"`
}
// ---------------------------------------------------------------------------
// Bookings
// ---------------------------------------------------------------------------
func TestCreateBooking_success(t *testing.T) {
h, key, _ := setupWorkspace(t)
slug, etID := seedEventTypeHTTP(t, h, key)
// Add availability rule.
body := fmt.Sprintf(`{"event_type_id":%q,"day_of_week":1,"start_time":"09:00","end_time":"17:00"}`, etID)
ruleReq := authReq(http.MethodPost, "/v1/availability-rules", body, key)
ruleRec := httptest.NewRecorder()
h.RequireAuth(h.CreateAvailabilityRule)(ruleRec, ruleReq)
if ruleRec.Code != http.StatusCreated {
t.Fatalf("create rule: %d", ruleRec.Code)
}
bookBody := fmt.Sprintf(`{"event_type_slug":%q,"start_at":"2026-06-15T09:00:00Z","name":"Alice","email":"alice@example.com"}`, slug)
req := httptest.NewRequest(http.MethodPost, "/v1/bookings", strings.NewReader(bookBody))
req.Header.Set("Content-Type", "application/json")
rec := httptest.NewRecorder()
h.CreateBooking(rec, req)
if rec.Code != http.StatusCreated {
t.Fatalf("create booking: %d — %s", rec.Code, rec.Body.String())
}
var b map[string]any
json.Unmarshal(rec.Body.Bytes(), &b)
if b["status"] != "confirmed" {
t.Errorf("status = %v; want confirmed", b["status"])
}
if b["id"] == "" {
t.Error("id is empty")
}
}
func TestCreateBooking_doubleBooked(t *testing.T) {
h, key, _ := setupWorkspace(t)
slug, _ := seedEventTypeHTTP(t, h, key)
create := func() int {
body := fmt.Sprintf(`{"event_type_slug":%q,"start_at":"2026-06-15T09:00:00Z","name":"Alice","email":"alice@example.com"}`, slug)
req := httptest.NewRequest(http.MethodPost, "/v1/bookings", strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
rec := httptest.NewRecorder()
h.CreateBooking(rec, req)
return rec.Code
}
if got := create(); got != http.StatusCreated {
t.Fatalf("first booking: %d; want 201", got)
}
if got := create(); got != http.StatusConflict {
t.Errorf("second booking: %d; want 409", got)
}
}
func TestGetBooking_public(t *testing.T) {
h, key, _ := setupWorkspace(t)
slug, _ := seedEventTypeHTTP(t, h, key)
// Create.
body := fmt.Sprintf(`{"event_type_slug":%q,"start_at":"2026-06-15T10:00:00Z","name":"Bob","email":"bob@example.com"}`, slug)
req := httptest.NewRequest(http.MethodPost, "/v1/bookings", strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
rec := httptest.NewRecorder()
h.CreateBooking(rec, req)
created := mustCreated(t, rec, "create booking")
bookingID := mustString(t, created, "id", "create booking")
// Get without auth key.
req2 := httptest.NewRequest(http.MethodGet, "/v1/bookings/"+bookingID, nil)
req2.SetPathValue("id", bookingID)
rec2 := httptest.NewRecorder()
h.GetBooking(rec2, req2)
if rec2.Code != http.StatusOK {
t.Fatalf("get booking: %d — %s", rec2.Code, rec2.Body.String())
}
var b map[string]any
json.Unmarshal(rec2.Body.Bytes(), &b)
if b["id"] != bookingID {
t.Errorf("id = %v; want %s", b["id"], bookingID)
}
}
func TestCancelBooking(t *testing.T) {
h, key, _ := setupWorkspace(t)
slug, _ := seedEventTypeHTTP(t, h, key)
// Create booking.
body := fmt.Sprintf(`{"event_type_slug":%q,"start_at":"2026-06-15T11:00:00Z","name":"Carol","email":"carol@example.com"}`, slug)
req := httptest.NewRequest(http.MethodPost, "/v1/bookings", strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
rec := httptest.NewRecorder()
h.CreateBooking(rec, req)
created := mustCreated(t, rec, "create booking")
bookingID := mustString(t, created, "id", "create booking")
// Cancel.
cancelReq := authReq(http.MethodPost, "/v1/bookings/"+bookingID+"/cancel",
`{"reason":"can't make it"}`, key)
cancelReq.SetPathValue("id", bookingID)
cancelRec := httptest.NewRecorder()
h.RequireAuth(h.CancelBooking)(cancelRec, cancelReq)
if cancelRec.Code != http.StatusOK {
t.Fatalf("cancel: %d — %s", cancelRec.Code, cancelRec.Body.String())
}
var cancelled map[string]any
json.Unmarshal(cancelRec.Body.Bytes(), &cancelled)
if cancelled["status"] != "cancelled" {
t.Errorf("status = %v; want cancelled", cancelled["status"])
}
}
func TestListBookings(t *testing.T) {
h, key, _ := setupWorkspace(t)
slug, _ := seedEventTypeHTTP(t, h, key)
// Create two bookings.
for _, startAt := range []string{"2026-06-15T09:00:00Z", "2026-06-15T10:00:00Z"} {
body := fmt.Sprintf(`{"event_type_slug":%q,"start_at":%q,"name":"Alice","email":"alice@example.com"}`, slug, startAt)
req := httptest.NewRequest(http.MethodPost, "/v1/bookings", strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
rec := httptest.NewRecorder()
h.CreateBooking(rec, req)
if rec.Code != http.StatusCreated {
t.Fatalf("create: %d — %s", rec.Code, rec.Body.String())
}
}
req := authReq(http.MethodGet, "/v1/bookings", "", key)
rec := httptest.NewRecorder()
h.RequireAuth(h.ListBookings)(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("list: %d — %s", rec.Code, rec.Body.String())
}
var resp struct {
Items []map[string]any `json:"items"`
}
json.Unmarshal(rec.Body.Bytes(), &resp)
if len(resp.Items) != 2 {
t.Errorf("len(items) = %d; want 2", len(resp.Items))
}
}
func TestListBookings_includesAttendeeAndSlug(t *testing.T) {
h, key, _ := setupWorkspace(t)
slug, _ := seedEventTypeHTTP(t, h, key)
body := fmt.Sprintf(`{"event_type_slug":%q,"start_at":"2026-06-20T09:00:00Z","name":"Alice Smith","email":"alice@example.com"}`, slug)
req := httptest.NewRequest(http.MethodPost, "/v1/bookings", strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
rec := httptest.NewRecorder()
h.CreateBooking(rec, req)
if rec.Code != http.StatusCreated {
t.Fatalf("create booking: %d — %s", rec.Code, rec.Body.String())
}
listReq := authReq(http.MethodGet, "/v1/bookings", "", key)
listRec := httptest.NewRecorder()
h.RequireAuth(h.ListBookings)(listRec, listReq)
if listRec.Code != http.StatusOK {
t.Fatalf("list bookings: %d — %s", listRec.Code, listRec.Body.String())
}
var listResp struct {
Items []struct {
EventTypeSlug string `json:"event_type_slug"`
Attendees []struct {
Name string `json:"name"`
Email string `json:"email"`
} `json:"attendees"`
} `json:"items"`
}
if err := json.Unmarshal(listRec.Body.Bytes(), &listResp); err != nil {
t.Fatalf("unmarshal: %v", err)
}
if len(listResp.Items) != 1 {
t.Fatalf("want 1 item; got %d", len(listResp.Items))
}
b := listResp.Items[0]
if b.EventTypeSlug != slug {
t.Errorf("event_type_slug = %q; want %q", b.EventTypeSlug, slug)
}
if len(b.Attendees) != 1 {
t.Fatalf("want 1 attendee; got %d", len(b.Attendees))
}
if b.Attendees[0].Name != "Alice Smith" {
t.Errorf("attendee name = %q; want Alice Smith", b.Attendees[0].Name)
}
if b.Attendees[0].Email != "alice@example.com" {
t.Errorf("attendee email = %q; want alice@example.com", b.Attendees[0].Email)
}
}