Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions frontend/src/lib/prefs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ export const TIMEZONES = [
'Europe/Paris',
'Europe/Berlin',
'Europe/Amsterdam',
'Europe/Tallinn',
'America/New_York',
'America/Chicago',
'America/Denver',
Expand Down
49 changes: 44 additions & 5 deletions frontend/src/routes/availability/+page.svelte
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<script lang="ts">
import { onMount } from 'svelte';
import { api, type AvailabilityRule, type AvailabilityOverride } from '$lib/api';
import { api, type AvailabilityRule, type AvailabilityOverride, type EventType } from '$lib/api';
import { prefs, fmtDate, weekDays } from '$lib/prefs';
import { t, tr, localeTag } from '$lib/i18n';
import { Button, buttonVariants } from '$lib/components/ui/button';
Expand Down Expand Up @@ -33,7 +33,7 @@
}

// ── Weekly rules — 7-day model ────────────────────────────────────────────────
type DayBlock = { id: string; start_time: string; end_time: string; saving: boolean; error: string }
type DayBlock = { id: string; event_type_id: string, start_time: string; end_time: string; saving: boolean; error: string }
type DayState = { day_of_week: number; blocks: DayBlock[]; error: string }

let days: DayState[] = $state(
Expand All @@ -56,7 +56,7 @@
for (const day of days) { day.blocks = []; day.error = ''; }
for (const r of (res.items ?? [])) {
const day = days[r.day_of_week];
if (day) day.blocks.push({ id: r.id, start_time: r.start_time, end_time: r.end_time, saving: false, error: '' });
if (day) day.blocks.push({ id: r.id, event_type_id: r.event_type_id ?? 'null', start_time: r.start_time, end_time: r.end_time, saving: false, error: '' });
}
for (const day of days) {
day.blocks.sort((a, b) => a.start_time.localeCompare(b.start_time));
Expand All @@ -69,14 +69,13 @@
}

async function addBlock(day: DayState) {
day.blocks.push({ id: '', start_time: '09:00', end_time: '17:00', saving: true, error: '' });
day.blocks.push({ id: '', event_type_id: 'null', start_time: '09:00', end_time: '17:00', saving: true, error: '' });
// Operate on the element AS STORED in the reactive array (a proxy), not the literal we
// pushed — Svelte 5 proxies pushed objects, so mutating the local literal wouldn't update
// the UI (the "saving…" stuck-until-refresh bug).
const block = day.blocks[day.blocks.length - 1];
try {
const r = await api.post<AvailabilityRule>('/v1/availability-rules', {
day_of_week: day.day_of_week,
start_time: '09:00',
end_time: '17:00'
});
Comment on lines 78 to 81

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

day_of_week was dropped from this create payload, and CreateAvailabilityRule decodes a missing field as 0, so every block added from the UI is created on Sunday. Adding a block to Wednesday shows it on Sunday after refresh, and a second add collides with the (user_id, event_type_id, day_of_week, start_time, end_time) unique index and gets spliced back out with an error. Restore day_of_week: day.day_of_week.

Expand All @@ -100,6 +99,7 @@
block.saving = true;
try {
await api.patch(`/v1/availability-rules/${block.id}`, {
event_type_id: block.event_type_id === null ? "null" : block.event_type_id,
start_time: block.start_time,
end_time: block.end_time
});
Expand Down Expand Up @@ -274,7 +274,20 @@
}
}

let eventTypes: {id: string, name: string}[] = []
async function loadEventTypes() {
try {
const res = await api.get<{ items: EventType[] }>('/v1/event-types');
for (const r of (res.items ?? [])) {
eventTypes.push({id: r.id, name: r.name})
}
} catch (e: any) {

}
}

onMount(() => {
loadEventTypes()
loadRules();
loadOverrides();
});
Expand All @@ -288,6 +301,12 @@
// Time-of-day options for the start/end selects, formatted per the user's prefs.
let timeOptions = $derived(TIME_SLOTS.map((t) => ({ value: t, label: fmtTime(t) })));
function timeLabel(t: string) { return fmtTime(t); }
function eventName(id: string | null) {
if (id === null) {
return {id: null, name: "None"}
}
return eventTypes.find((et => et.id == id))
}
</script>

<ConfirmDialog
Expand Down Expand Up @@ -380,6 +399,26 @@
{:else if block.error}
<span class="text-xs text-destructive">{block.error}</span>
{/if}

<Select.Root
type="single"
bind:value={block.event_type_id}
onValueChange={() => updateBlock(block)}
disabled={block.saving || !block.id}
>
<Select.Trigger class="w-fit">
{#if block.event_type_id === "null"}
All
{:else}
{eventName(block.event_type_id)?.name ?? block.event_type_id}
{/if}
</Select.Trigger>
<Select.Content>
<Select.Item value="null" label="All">All</Select.Item>
{#each eventTypes as e}<Select.Item value={e.id} label={e.name}>{e.name}</Select.Item>{/each}
</Select.Content>
</Select.Root>

<Tooltip.Root>
<Tooltip.Trigger
class={buttonVariants({ variant: 'ghost', size: 'icon' })}
Expand Down
24 changes: 15 additions & 9 deletions internal/handler/availability.go
Original file line number Diff line number Diff line change
Expand Up @@ -123,9 +123,10 @@ func (h *Handler) UpdateAvailabilityRule(w http.ResponseWriter, r *http.Request)
r.Body = http.MaxBytesReader(w, r.Body, 32<<10)

var req struct {
DayOfWeek *int `json:"day_of_week"`
StartTime *string `json:"start_time"`
EndTime *string `json:"end_time"`
EventTypeId *string `json:"event_type_id"`
DayOfWeek *int `json:"day_of_week"`
StartTime *string `json:"start_time"`
EndTime *string `json:"end_time"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
h.writeError(w, http.StatusBadRequest, "invalid JSON")
Expand All @@ -137,11 +138,10 @@ func (h *Handler) UpdateAvailabilityRule(w http.ResponseWriter, r *http.Request)
}

var current availRuleJSON
var etID sql.NullString
err := h.db.QueryRowContext(r.Context(),
`SELECT id, event_type_id, day_of_week, start_time, end_time
FROM availability_rules WHERE id = ? AND user_id = ?`, id, user.ID).
Scan(&current.ID, &etID, &current.DayOfWeek, &current.StartTime, &current.EndTime)
Scan(&current.ID, &current.EventTypeID, &current.DayOfWeek, &current.StartTime, &current.EndTime)
if err == sql.ErrNoRows {
h.writeError(w, http.StatusNotFound, "rule not found")
return
Expand All @@ -151,8 +151,14 @@ func (h *Handler) UpdateAvailabilityRule(w http.ResponseWriter, r *http.Request)
h.writeError(w, http.StatusInternalServerError, "internal error")
return
}
if etID.Valid {
current.EventTypeID = &etID.String

if req.EventTypeId != nil {
etID := req.EventTypeId
if *etID == "null" {
current.EventTypeID = nil
} else {
current.EventTypeID = req.EventTypeId
}
}

if req.DayOfWeek != nil {
Expand All @@ -174,8 +180,8 @@ func (h *Handler) UpdateAvailabilityRule(w http.ResponseWriter, r *http.Request)
}

_, err = h.db.ExecContext(r.Context(),
`UPDATE availability_rules SET day_of_week=?, start_time=?, end_time=? WHERE id=? AND user_id=?`,
current.DayOfWeek, current.StartTime, current.EndTime, id, user.ID)
`UPDATE availability_rules SET event_type_id=?, day_of_week=?, start_time=?, end_time=? WHERE id=? AND user_id=?`,
current.EventTypeID, current.DayOfWeek, current.StartTime, current.EndTime, id, user.ID)
if err != nil {
if db.IsUniqueViolation(err) {
h.writeError(w, http.StatusConflict, "a rule for this day and time already exists")
Expand Down
34 changes: 33 additions & 1 deletion internal/handler/booking_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"fmt"
"io"
"log/slog"
"net"
"net/http"
"net/mail"
"net/url"
Expand All @@ -27,6 +28,34 @@ import (
"github.com/calnode/calnode/internal/zoom"
)

// clientIP extracts the most likely client IP from the request headers.
// It tries X-Real-Ip first (set by Traefik from PROXY protocol), then X-Forwarded-For,
// then falls back to the TCP remote address.
func clientIP(r *http.Request) string {
// X-Real-Ip is set by Traefik from the PROXY protocol source address.
if ip := net.ParseIP(strings.TrimSpace(r.Header.Get("X-Real-Ip"))); ip != nil {
return ip.String()
}

// X-Forwarded-For: client, proxy1, proxy2, ... The leftmost entry
// is the original client.
if xff := r.Header.Get("X-Forwarded-For"); xff != "" {
if i := strings.IndexByte(xff, ','); i >= 0 {
xff = xff[:i]
}
if ip := net.ParseIP(strings.TrimSpace(xff)); ip != nil {
return ip.String()
}
}

// Fallback: direct connection (or misconfigured proxy).
host, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
return strings.TrimSpace(r.RemoteAddr)
}
return host
}

// errInvalidBookerEmail is returned by normalizeBookerEmail for an address net/mail
// cannot parse. Callers map it to their own protocol (400 on the REST path, a short
// retry hint for the assistant).
Expand Down Expand Up @@ -1002,7 +1031,10 @@ func (h *Handler) CreateBooking(w http.ResponseWriter, r *http.Request) {
h.writeError(w, http.StatusServiceUnavailable, "payments are temporarily unavailable")
return
}
checkoutURL, err := h.startBookingCheckout(r.Context(), sc, b.ID, et.PriceCents, et.Currency, et.Name, req.EventTypeSlug, req.Email)

clientIp := clientIP(r)

checkoutURL, err := h.startBookingCheckout(r.Context(), sc, b.ID, et.PriceCents, et.Currency, et.Name, req.EventTypeSlug, req.Email, clientIp)
if err != nil {
h.logger.ErrorContext(r.Context(), "create booking: start checkout", "error", err, "booking_id", b.ID)
_ = h.bookingSvc.CancelByID(r.Context(), b.ID, "checkout failed")
Expand Down
4 changes: 2 additions & 2 deletions internal/handler/embed.js
Original file line number Diff line number Diff line change
Expand Up @@ -94,8 +94,8 @@
function dayKey(iso) { return new Intl.DateTimeFormat('en-CA', { timeZone: TZ, year: 'numeric', month: '2-digit', day: '2-digit' }).format(new Date(iso)); }
// locale is the resolved server-side locale (this.locale), not the browser's own
// ([]) — see the matching fix/comment in book.html / internal-docs/i18n-plan.md.
function timeLabel(iso, locale) { return new Intl.DateTimeFormat(locale || [], { timeZone: TZ, hour: 'numeric', minute: '2-digit' }).format(new Date(iso)); }
function shortDay(iso, locale) { return new Intl.DateTimeFormat(locale || [], { timeZone: TZ, weekday: 'short', month: 'short', day: 'numeric' }).format(new Date(iso)); }
function timeLabel(iso, locale) { return new Intl.DateTimeFormat("et-EE", { timeZone: TZ, hour: 'numeric', minute: '2-digit' }).format(new Date(iso)); }
function shortDay(iso, locale) { return new Intl.DateTimeFormat("et-EE", { timeZone: TZ, weekday: 'short', month: 'short', day: 'numeric' }).format(new Date(iso)); }
function ymd(d) { return d.getFullYear() + '-' + String(d.getMonth() + 1).padStart(2, '0') + '-' + String(d.getDate()).padStart(2, '0'); }
function startOfMonth(d) { return new Date(d.getFullYear(), d.getMonth(), 1); }
function endOfMonth(d) { return new Date(d.getFullYear(), d.getMonth() + 1, 0); }
Expand Down
2 changes: 1 addition & 1 deletion internal/handler/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import (
"github.com/calnode/calnode/internal/livekit"
"github.com/calnode/calnode/internal/llm"
"github.com/calnode/calnode/internal/mailer"
"github.com/calnode/calnode/internal/stripe"
stripe "github.com/calnode/calnode/internal/makecommerce"
"github.com/calnode/calnode/internal/webhook"
"github.com/calnode/calnode/internal/zoom"
)
Expand Down
Loading
Loading