diff --git a/CHANGELOG.md b/CHANGELOG.md index 6eec3898..1149229b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -32,6 +32,17 @@ exact tag (`ghcr.io/calnode/calnode:0.1.0`) if you need stability between upgrad ### Added +- **Delete a booking for an erasure request.** Owners and admins can now permanently remove a + booking from the Bookings list (trash icon, confirmation dialog; `DELETE /v1/bookings/{id}`). + It removes the booking with its attendees, answers, manage links and host assignments, plus the + rows that name the person without a cascade: webhook deliveries and their queued jobs, reminder + jobs, idempotency records, transcripts and notes. It sends no email and fires no webhook. + Offered only where it is safe: an upcoming booking must be cancelled first (so the booker is + told and the calendar event goes); paid bookings keep their record; recordings must be deleted + first (they are files in object storage); and a cancelled booking whose calendar event removal + is still pending is refused until the reconciler has removed it. A past meeting's event stays on + the host's calendar, because removing it through the provider would email the guest; the + dialog says so. Database backups keep the data until their own retention ends. - **German without du or Sie (`de-x-neutral`).** An opt-in wording variant of the German booker catalogue that addresses nobody: "Tag auswählen" rather than "Wählen Sie einen Tag". It is for operators whose own site is informal, where the formal widget stands out diff --git a/frontend/src/lib/i18n/en.json b/frontend/src/lib/i18n/en.json index d14b9130..cd1233a2 100644 --- a/frontend/src/lib/i18n/en.json +++ b/frontend/src/lib/i18n/en.json @@ -188,7 +188,8 @@ "hideResponses": "Hide responses", "showResponses": "Show responses", "reschedule": "Reschedule", - "cancel": "Cancel booking" + "cancel": "Cancel booking", + "delete": "Delete booking" }, "cancelReschedule": "Cancel reschedule", "details": { @@ -221,6 +222,20 @@ "status": { "confirmed": "confirmed", "cancelled": "cancelled" + }, + "confirmDelete": { + "title": "Delete this booking permanently?", + "description": "Removes the booking with the attendee's name, email and answers, for a data deletion request. No one is notified. A calendar event of a past meeting stays on your calendar; delete it there without notifying guests. This can't be undone.", + "confirm": "Delete permanently", + "cancel": "Keep booking" + }, + "delete": { + "error": { + "cancel_first": "Cancel the upcoming booking first, then delete it.", + "paid_booking": "Paid bookings keep their record and cannot be deleted here.", + "recordings_first": "Delete the recordings of this booking first (Recordings).", + "calendar_pending": "The calendar event is still being removed. Try again in a few minutes." + } } }, "availability": { diff --git a/frontend/src/lib/i18n/fr.json b/frontend/src/lib/i18n/fr.json index 46ca13d0..eed0a8cb 100644 --- a/frontend/src/lib/i18n/fr.json +++ b/frontend/src/lib/i18n/fr.json @@ -188,7 +188,8 @@ "hideResponses": "Masquer les réponses", "showResponses": "Afficher les réponses", "reschedule": "Reprogrammer", - "cancel": "Annuler la réservation" + "cancel": "Annuler la réservation", + "delete": "Supprimer la réservation" }, "cancelReschedule": "Annuler la reprogrammation", "details": { @@ -221,6 +222,20 @@ "status": { "confirmed": "confirmée", "cancelled": "annulée" + }, + "confirmDelete": { + "title": "Supprimer définitivement cette réservation ?", + "description": "Supprime la réservation avec le nom, l'e-mail et les réponses du participant, par exemple pour une demande d'effacement. Personne n'est notifié. L'événement d'une réunion passée reste dans votre agenda ; supprimez-le là-bas sans notifier les invités. Action irréversible.", + "confirm": "Supprimer définitivement", + "cancel": "Conserver la réservation" + }, + "delete": { + "error": { + "cancel_first": "Annulez d'abord la réservation à venir, puis supprimez-la.", + "paid_booking": "Les réservations payées conservent leur trace et ne peuvent pas être supprimées ici.", + "recordings_first": "Supprimez d'abord les enregistrements de cette réservation (Enregistrements).", + "calendar_pending": "L'événement d'agenda est encore en cours de suppression. Réessayez dans quelques minutes." + } } }, "availability": { diff --git a/frontend/src/routes/bookings/+page.svelte b/frontend/src/routes/bookings/+page.svelte index 272a6abc..93971fe4 100644 --- a/frontend/src/routes/bookings/+page.svelte +++ b/frontend/src/routes/bookings/+page.svelte @@ -218,6 +218,38 @@ } } + // Permanent erasure for a data-deletion request (owner/admin only). Offered where the + // server can do it: cancelled or already-ended free bookings. The server re-checks and + // answers 409 with a code naming the step to take first (recordings, calendar pending). + let deleteOpen = $state(false); + let pendingDeleteId = $state(null); + const deleteErrorCodes = ['cancel_first', 'paid_booking', 'recordings_first', 'calendar_pending']; + + function canDelete(b: Booking): boolean { + if (!isAdmin || b.payment_status) return false; + return b.status === 'cancelled' || new Date(b.end_at).getTime() <= Date.now(); + } + + function requestDelete(id: string) { + pendingDeleteId = id; + deleteOpen = true; + } + + async function deleteBooking() { + const id = pendingDeleteId; + if (!id) return; + try { + await api.del(`/v1/bookings/${id}`); + if (expandedId === id) expandedId = null; + await load(); + } catch (e: any) { + error = deleteErrorCodes.includes(e.message) ? $t(`bookings.delete.error.${e.message}`) : e.message; + } finally { + deleteOpen = false; + pendingDeleteId = null; + } + } + function startReschedule(b: Booking) { reschedulingId = b.id; reschedulingSlug = b.event_type_slug ?? ''; @@ -516,6 +548,19 @@ {/if} {/if} + + {#if canDelete(b)} + + requestDelete(b.id)} + aria-label={$t('bookings.tooltip.delete')} + > + + + {$t('bookings.tooltip.delete')} + + {/if} @@ -667,3 +712,13 @@ destructive onConfirm={cancel} /> + + diff --git a/internal/booking/delete.go b/internal/booking/delete.go new file mode 100644 index 00000000..cf317aad --- /dev/null +++ b/internal/booking/delete.go @@ -0,0 +1,114 @@ +package booking + +import ( + "context" + "database/sql" + "errors" + "fmt" + "time" +) + +// Errors returned by Delete when a booking must not be erased yet. Each names the step +// that comes first, so the admin UI can say what to do instead of a bare refusal. +var ( + // ErrDeleteUpcoming: a confirmed booking that has not ended yet. Deleting it would make + // the meeting vanish for the host while the booker still holds the invite; cancel it + // first (which tells the booker, removes the calendar event, refunds and fires the + // cancellation webhook), then delete. + ErrDeleteUpcoming = errors.New("booking: cancel the upcoming booking before deleting it") + // ErrDeletePaid: the booking carries a payment record. Payment records have their own + // retention duties, so this path refuses rather than silently dropping one. + ErrDeletePaid = errors.New("booking: a paid booking keeps its record") + // ErrDeleteRecordings: recordings are files in object storage; removing only the row + // would orphan the file. Delete them on the Recordings page first. + ErrDeleteRecordings = errors.New("booking: delete the booking's recordings first") + // ErrDeleteCalendarPending: the booking was cancelled but a host's calendar event is still + // recorded as present (removal failed and the reconciler will retry). Deleting the row now + // would lose the id needed to remove that event, leaving it on the calendar for good. + ErrDeleteCalendarPending = errors.New("booking: the cancelled booking's calendar event is still being removed") +) + +// Delete permanently erases a booking and the personal data stored with it, for an +// erasure request (GDPR Art. 17). It sends no email and fires no webhook: the person +// asked for their data to be removed, not to be told about a cancellation. +// +// Removed in one transaction: +// - the booking row, and by ON DELETE CASCADE its attendees, form answers, manage +// tokens and host assignments; +// - rows that reference it without a cascade: webhook deliveries (their payload holds +// the attendee's name and email) and the jobs that would deliver them, reminder jobs, +// idempotency records (their stored response holds the booking), transcripts and notes. +// +// Not touched: a calendar event that still exists for a past booking stays on the host's +// calendar (removing it through the provider would email the guest a cancellation), and +// database backups keep the data until their own retention ends. Both are documented for +// the operator. +func (s *Service) Delete(ctx context.Context, id string, now time.Time) error { + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return fmt.Errorf("booking: delete: begin: %w", err) + } + defer func() { _ = tx.Rollback() }() + + var status, endStr, paymentStatus string + err = tx.QueryRowContext(ctx, + `SELECT status, end_at, payment_status FROM bookings WHERE id = ?`, id). + Scan(&status, &endStr, &paymentStatus) + if errors.Is(err, sql.ErrNoRows) { + return ErrNotFound + } + if err != nil { + return fmt.Errorf("booking: delete: load: %w", err) + } + endAt, err := time.Parse(time.RFC3339Nano, endStr) + if err != nil { + return fmt.Errorf("booking: delete: parse end_at %q: %w", endStr, err) + } + if status != "cancelled" && endAt.After(now) { + return ErrDeleteUpcoming + } + if paymentStatus != "" && paymentStatus != "none" { + return ErrDeletePaid + } + + var n int + if err := tx.QueryRowContext(ctx, + `SELECT COUNT(*) FROM recordings WHERE booking_id = ?`, id).Scan(&n); err != nil { + return fmt.Errorf("booking: delete: count recordings: %w", err) + } + if n > 0 { + return ErrDeleteRecordings + } + if status == "cancelled" { + if err := tx.QueryRowContext(ctx, ` + SELECT COUNT(*) FROM booking_hosts + WHERE booking_id = ? AND COALESCE(external_event_id, '') != ''`, id).Scan(&n); err != nil { + return fmt.Errorf("booking: delete: count calendar events: %w", err) + } + if n > 0 { + return ErrDeleteCalendarPending + } + } + + // Order matters: jobs point at webhook deliveries by id inside their JSON payload, and + // webhook_deliveries.booking_id references bookings without a cascade. + steps := []struct{ what, query string }{ + {"webhook jobs", `DELETE FROM jobs WHERE type = 'webhook.deliver' + AND json_extract(payload, '$.webhook_delivery_id') IN (SELECT id FROM webhook_deliveries WHERE booking_id = ?)`}, + {"booking jobs", `DELETE FROM jobs WHERE json_valid(payload) AND json_extract(payload, '$.booking_id') = ?`}, + {"webhook deliveries", `DELETE FROM webhook_deliveries WHERE booking_id = ?`}, + {"idempotency keys", `DELETE FROM idempotency_keys WHERE booking_id = ?`}, + {"transcripts", `DELETE FROM transcripts WHERE booking_id = ?`}, + {"notes", `DELETE FROM notes WHERE booking_id = ?`}, + {"booking", `DELETE FROM bookings WHERE id = ?`}, + } + for _, step := range steps { + if _, err := tx.ExecContext(ctx, step.query, id); err != nil { + return fmt.Errorf("booking: delete %s: %w", step.what, err) + } + } + if err := tx.Commit(); err != nil { + return fmt.Errorf("booking: delete: commit: %w", err) + } + return nil +} diff --git a/internal/handler/booking_delete_test.go b/internal/handler/booking_delete_test.go new file mode 100644 index 00000000..16711226 --- /dev/null +++ b/internal/handler/booking_delete_test.go @@ -0,0 +1,216 @@ +package handler_test + +import ( + "database/sql" + "fmt" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/calnode/calnode/internal/handler" +) + +// createBookingForDelete books the seeded slot through the public endpoint, then moves the +// booking to now+offset, which frees the slot for the next one and keeps the tests +// independent of today's date. +func createBookingForDelete(t *testing.T, h *handler.Handler, database *sql.DB, slug, email string, offset time.Duration) string { + t.Helper() + body := fmt.Sprintf(`{"event_type_slug":%q,"start_at":"2026-06-15T11:00:00Z","name":"Carol","email":%q}`, slug, email) + req := httptest.NewRequest(http.MethodPost, "/v1/bookings", strings.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + rec := httptest.NewRecorder() + h.CreateBooking(rec, req) + id := mustString(t, mustCreated(t, rec, "create booking"), "id", "create booking") + setBookingWindow(t, database, id, offset) + return id +} + +func deleteBooking(h *handler.Handler, id, key string) *httptest.ResponseRecorder { + req := authReq(http.MethodDelete, "/v1/bookings/"+id, "", key) + req.SetPathValue("id", id) + rec := httptest.NewRecorder() + h.RequireAuth(h.DeleteBooking)(rec, req) + return rec +} + +func countRows(t *testing.T, database *sql.DB, query string, args ...any) int { + t.Helper() + var n int + if err := database.QueryRow(query, args...).Scan(&n); err != nil { + t.Fatalf("count %q: %v", query, err) + } + return n +} + +// setBookingWindow moves a booking to the given time (relative to now), so the tests do +// not depend on today's date. +func setBookingWindow(t *testing.T, database *sql.DB, id string, start time.Duration) { + t.Helper() + s := time.Now().UTC().Add(start) + if _, err := database.Exec(`UPDATE bookings SET start_at = ?, end_at = ? WHERE id = ?`, + s.Format(time.RFC3339Nano), s.Add(30*time.Minute).Format(time.RFC3339Nano), id); err != nil { + t.Fatal(err) + } +} + +// TestDeleteBooking_erasesBookingAndEverythingThatNamesThePerson: a past booking is +// removed together with every row that holds the attendee's data, and only those; +// a second booking stays untouched. Nothing new is queued (no webhook, no email job). +func TestDeleteBooking_erasesBookingAndEverythingThatNamesThePerson(t *testing.T) { + h, database, key, _ := setupWorkspaceWithDB(t) + slug, _ := seedEventTypeHTTP(t, h, key) + id := createBookingForDelete(t, h, database, slug, "carol@example.com", -48*time.Hour) + other := createBookingForDelete(t, h, database, slug, "dana@example.com", -24*time.Hour) + + var ownerID string + if err := database.QueryRow(`SELECT host_id FROM bookings WHERE id = ?`, id).Scan(&ownerID); err != nil { + t.Fatal(err) + } + // Data that references the booking without a cascade, as the real paths write it. + for _, q := range []string{ + `INSERT INTO webhooks (id, user_id, url, events, secret_enc) VALUES ('wh1', '` + ownerID + `', 'https://example.test/hook', '["booking.created"]', 'x')`, + `INSERT INTO webhook_deliveries (id, webhook_id, booking_id, event, payload, status) VALUES ('d1', 'wh1', '` + id + `', 'booking.created', '{"attendee_email":"carol@example.com"}', 'success')`, + `INSERT INTO webhook_deliveries (id, webhook_id, booking_id, event, payload, status) VALUES ('d2', 'wh1', '` + other + `', 'booking.created', '{"attendee_email":"dana@example.com"}', 'success')`, + `INSERT INTO jobs (id, type, payload, run_at) VALUES ('j1', 'webhook.deliver', '{"webhook_delivery_id":"d1"}', '2030-01-01T00:00:00Z')`, + `INSERT INTO jobs (id, type, payload, run_at) VALUES ('j2', 'webhook.deliver', '{"webhook_delivery_id":"d2"}', '2030-01-01T00:00:00Z')`, + `INSERT INTO jobs (id, type, payload, run_at) VALUES ('j3', 'reminder.send', '{"booking_id":"` + id + `"}', '2030-01-01T00:00:00Z')`, + `INSERT INTO idempotency_keys (idempotency_key, request_hash, status_code, response_body, booking_id, created_at) VALUES ('k1', 'h', 201, '{"email":"carol@example.com"}', '` + id + `', '2026-01-01')`, + `INSERT INTO notes (id, booking_id, content) VALUES ('n1', '` + id + `', 'Carol wants a call back')`, + } { + if _, err := database.Exec(q); err != nil { + t.Fatalf("seed: %v\n%s", err, q) + } + } + if countRows(t, database, `SELECT COUNT(*) FROM booking_attendees WHERE booking_id = ?`, id) == 0 { + t.Fatal("fixture: booking has no attendee row") + } + + rec := deleteBooking(h, id, key) + if rec.Code != http.StatusNoContent { + t.Fatalf("delete: %d — %s", rec.Code, rec.Body.String()) + } + + for _, q := range []string{ + `SELECT COUNT(*) FROM bookings WHERE id = ?`, + `SELECT COUNT(*) FROM booking_attendees WHERE booking_id = ?`, + `SELECT COUNT(*) FROM booking_answers WHERE booking_id = ?`, + `SELECT COUNT(*) FROM booking_manage_tokens WHERE booking_id = ?`, + `SELECT COUNT(*) FROM booking_hosts WHERE booking_id = ?`, + `SELECT COUNT(*) FROM webhook_deliveries WHERE booking_id = ?`, + `SELECT COUNT(*) FROM idempotency_keys WHERE booking_id = ?`, + `SELECT COUNT(*) FROM notes WHERE booking_id = ?`, + `SELECT COUNT(*) FROM jobs WHERE json_extract(payload, '$.booking_id') = ?`, + } { + if n := countRows(t, database, q, id); n != 0 { + t.Errorf("%s: %d rows left", q, n) + } + } + if n := countRows(t, database, `SELECT COUNT(*) FROM jobs WHERE id = 'j1'`); n != 0 { + t.Errorf("webhook job for the deleted booking's delivery is still queued") + } + if n := countRows(t, database, `SELECT COUNT(*) FROM bookings WHERE id = ?`, other); n != 1 { + t.Errorf("the other booking was touched") + } + if n := countRows(t, database, `SELECT COUNT(*) FROM jobs WHERE id = 'j2'`); n != 1 { + t.Errorf("the other booking's webhook job was removed") + } + if n := countRows(t, database, `SELECT COUNT(*) FROM webhook_deliveries WHERE id = 'd2'`); n != 1 { + t.Errorf("the other booking's webhook delivery was removed") + } + // Deleting queues nothing: no webhook delivery and no job for the deleted booking. + // (Counting all jobs would race with the asynchronous side effects of the bookings + // created above, which may still be enqueuing their own webhooks.) + if n := countRows(t, database, `SELECT COUNT(*) FROM webhook_deliveries WHERE event = 'booking.cancelled'`); n != 0 { + t.Errorf("delete fired a cancellation webhook") + } + + // Gone means gone: a second delete is a 404, not a silent success. + if rec := deleteBooking(h, id, key); rec.Code != http.StatusNotFound { + t.Errorf("second delete: %d; want 404", rec.Code) + } +} + +// TestDeleteBooking_refusesWhatMustComeFirst: each refusal names the step to take first. +func TestDeleteBooking_refusesWhatMustComeFirst(t *testing.T) { + h, database, key, _ := setupWorkspaceWithDB(t) + slug, _ := seedEventTypeHTTP(t, h, key) + + t.Run("upcoming confirmed booking: cancel first", func(t *testing.T) { + id := createBookingForDelete(t, h, database, slug, "up@example.com", 72*time.Hour) + rec := deleteBooking(h, id, key) + if rec.Code != http.StatusConflict || !strings.Contains(rec.Body.String(), "cancel_first") { + t.Fatalf("delete upcoming: %d — %s", rec.Code, rec.Body.String()) + } + // Once cancelled, it can be deleted (no calendar connected, so nothing pending). + if _, err := database.Exec(`UPDATE bookings SET status = 'cancelled' WHERE id = ?`, id); err != nil { + t.Fatal(err) + } + if rec := deleteBooking(h, id, key); rec.Code != http.StatusNoContent { + t.Fatalf("delete after cancel: %d — %s", rec.Code, rec.Body.String()) + } + }) + + t.Run("cancelled booking whose calendar event is still being removed", func(t *testing.T) { + id := createBookingForDelete(t, h, database, slug, "cal@example.com", 72*time.Hour) + if _, err := database.Exec(`UPDATE bookings SET status = 'cancelled' WHERE id = ?`, id); err != nil { + t.Fatal(err) + } + if _, err := database.Exec(`UPDATE booking_hosts SET external_event_id = 'evt_1' WHERE booking_id = ?`, id); err != nil { + t.Fatal(err) + } + rec := deleteBooking(h, id, key) + if rec.Code != http.StatusConflict || !strings.Contains(rec.Body.String(), "calendar_pending") { + t.Fatalf("delete with pending calendar event: %d — %s", rec.Code, rec.Body.String()) + } + }) + + t.Run("paid booking keeps its record", func(t *testing.T) { + id := createBookingForDelete(t, h, database, slug, "paid@example.com", -72*time.Hour) + if _, err := database.Exec(`UPDATE bookings SET payment_status = 'paid' WHERE id = ?`, id); err != nil { + t.Fatal(err) + } + rec := deleteBooking(h, id, key) + if rec.Code != http.StatusConflict || !strings.Contains(rec.Body.String(), "paid_booking") { + t.Fatalf("delete paid: %d — %s", rec.Code, rec.Body.String()) + } + }) + + t.Run("recordings first", func(t *testing.T) { + id := createBookingForDelete(t, h, database, slug, "rec@example.com", -96*time.Hour) + if _, err := database.Exec(`INSERT INTO recordings (id, booking_id, room, egress_id, status, object_key) VALUES ('r1', ?, 'booking-x', 'eg1', 'complete', 'recordings/x.mp4')`, id); err != nil { + t.Fatal(err) + } + rec := deleteBooking(h, id, key) + if rec.Code != http.StatusConflict || !strings.Contains(rec.Body.String(), "recordings_first") { + t.Fatalf("delete with recording: %d — %s", rec.Code, rec.Body.String()) + } + if n := countRows(t, database, `SELECT COUNT(*) FROM bookings WHERE id = ?`, id); n != 1 { + t.Errorf("refused delete still removed the booking") + } + }) + + t.Run("unknown booking", func(t *testing.T) { + if rec := deleteBooking(h, "does-not-exist", key); rec.Code != http.StatusNotFound { + t.Fatalf("delete unknown: %d", rec.Code) + } + }) +} + +// TestDeleteBooking_adminOnly: a member cannot erase bookings, not even their own. +func TestDeleteBooking_adminOnly(t *testing.T) { + h, database, _, _ := setupWorkspaceWithDB(t) + database.Exec(`INSERT INTO users (id,email,name,iana_timezone,is_admin) VALUES ('u2','miri@example.com','Miri','UTC',0)`) //nolint:errcheck + const memberKey = "cno_memberkey" + database.Exec(`INSERT INTO api_keys (id,user_id,name,key_hash,created_at) VALUES ('k2','u2','test',?,'2024-01-01')`, sha256HexForTest(memberKey)) //nolint:errcheck + slug, _ := seedEventTypeHTTP(t, h, memberKey) + id := createBookingForDelete(t, h, database, slug, "carol@example.com", -48*time.Hour) + + if rec := deleteBooking(h, id, memberKey); rec.Code != http.StatusForbidden { + t.Fatalf("member delete: %d; want 403", rec.Code) + } + if n := countRows(t, database, `SELECT COUNT(*) FROM bookings WHERE id = ?`, id); n != 1 { + t.Errorf("forbidden delete removed the booking") + } +} diff --git a/internal/handler/booking_handler.go b/internal/handler/booking_handler.go index 74b51170..337ba4ee 100644 --- a/internal/handler/booking_handler.go +++ b/internal/handler/booking_handler.go @@ -1821,6 +1821,38 @@ func (h *Handler) CancelBooking(w http.ResponseWriter, r *http.Request) { go h.cancelSideEffects(*b) // #nosec G118 -- deliberately its own context.Background(); see cancelSideEffects' doc comment } +// DeleteBooking handles DELETE /v1/bookings/{id} (owner/admin only): permanently erases a +// booking and the personal data stored with it, for an erasure request. No email, no +// webhook. booking.Service.Delete lists exactly what is removed and what is refused; the +// refusals come back as 409 with a stable code the admin UI turns into the next step. +func (h *Handler) DeleteBooking(w http.ResponseWriter, r *http.Request) { + user, ok := h.requireAdmin(w, r) + if !ok { + return + } + id := r.PathValue("id") + err := h.bookingSvc.Delete(r.Context(), id, time.Now().UTC()) + switch { + case err == nil: + // Who and which id only: the point of this call is that the person's data is gone. + h.logger.InfoContext(r.Context(), "booking deleted on request", "booking_id", id, "by", user.ID) + w.WriteHeader(http.StatusNoContent) + case errors.Is(err, booking.ErrNotFound): + h.writeError(w, http.StatusNotFound, "booking not found") + case errors.Is(err, booking.ErrDeleteUpcoming): + h.writeError(w, http.StatusConflict, "cancel_first") + case errors.Is(err, booking.ErrDeletePaid): + h.writeError(w, http.StatusConflict, "paid_booking") + case errors.Is(err, booking.ErrDeleteRecordings): + h.writeError(w, http.StatusConflict, "recordings_first") + case errors.Is(err, booking.ErrDeleteCalendarPending): + h.writeError(w, http.StatusConflict, "calendar_pending") + default: + h.logger.ErrorContext(r.Context(), "delete booking", "error", err, "booking_id", id) + h.writeError(w, http.StatusInternalServerError, "internal error") + } +} + // cancelSideEffects removes every assigned host's calendar event, notifies each // host, emails the attendee, and fires the webhook for a cancelled booking. Runs // in its own context so it can be launched in a goroutine after the response is diff --git a/internal/server/server.go b/internal/server/server.go index 8190241c..7a6ba252 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -524,6 +524,7 @@ func New(ctx context.Context, cfg *config.Config, db *sql.DB, logger *slog.Logge mux.HandleFunc("GET /v1/bookings/{id}", bookingRL(h.GetBooking)) mux.HandleFunc("GET /v1/bookings", h.RequireAuth(h.ListBookings)) mux.HandleFunc("POST /v1/bookings/{id}/cancel", h.RequireAuth(h.CancelBooking)) + mux.HandleFunc("DELETE /v1/bookings/{id}", h.RequireAuth(h.DeleteBooking)) mux.HandleFunc("PATCH /v1/bookings/{id}/reschedule", h.RequireAuth(h.RescheduleBooking)) mux.HandleFunc("POST /v1/bookings/{id}/reassign", h.RequireAuth(h.ReassignBooking)) mux.HandleFunc("GET /v1/bookings/{id}/answers", h.RequireAuth(h.GetBookingAnswers))