Skip to content
Merged
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
4 changes: 4 additions & 0 deletions frontend/src/lib/i18n/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -241,6 +241,10 @@
"addHours": "+ Add hours",
"addBlock": "Add block",
"saving": "saving…",
"eventTypes": {
"appliesTo": "Applies to",
"allEventTypes": "All event types"
},
"blockError": {
"endAfterStart": "End must be after start"
},
Expand Down
4 changes: 4 additions & 0 deletions frontend/src/lib/i18n/fr.json
Original file line number Diff line number Diff line change
Expand Up @@ -241,6 +241,10 @@
"addHours": "+ Ajouter des horaires",
"addBlock": "Ajouter un bloc",
"saving": "enregistrement…",
"eventTypes": {
"appliesTo": "S'applique à",
"allEventTypes": "Tous les types d'événements"
},
"blockError": {
"endAfterStart": "La fin doit être après le début"
},
Expand Down
53 changes: 49 additions & 4 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,7 +69,7 @@
}

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).
Expand Down Expand Up @@ -100,6 +100,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 +275,21 @@
}
}

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

}
}

onMount(() => {
loadEventTypes()
loadRules();
loadOverrides();
});
Expand All @@ -288,6 +303,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 +401,30 @@
{:else if block.error}
<span class="text-xs text-destructive">{block.error}</span>
{/if}

<span class="text-muted-foreground">|</span>
<div class="text-sm font-normal text-muted-foreground">
{$t('availability.eventTypes.appliesTo')}:
</div>
<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"}
{$t('availability.eventTypes.allEventTypes')}
{:else}
{eventName(block.event_type_id)?.name ?? block.event_type_id}
{/if}
</Select.Trigger>
<Select.Content>
<Select.Item value="null" label="All">{$t('availability.eventTypes.allEventTypes')}</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
25 changes: 16 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 json.RawMessage `json:"event_type_id"` // `nil` = leave alone, `null` = clear
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,15 @@ 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 {
var etId *string
if err := json.Unmarshal(req.EventTypeId, &etId); err != nil {
h.writeError(w, http.StatusBadRequest, "event_type_id must be a string")
return
}

current.EventTypeID = etId
}
Comment on lines +155 to 163

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.

The new absent-vs-null contract has no test. json.RawMessage is the only thing keeping the three cases apart — an omitted key stays nil, while an explicit null arrives as the four-byte literal and then unmarshals to a nil *string — and that is exactly the detail a later simplification back to *string would drop while every existing test stays green. availability_rule_test.go covers start_time, end_time, day_of_week, 404, 400 and 409 for this handler, but nothing sends event_type_id.

Technical details
# Cover the absent / null / string contract on PATCH

## Affected sites
- `internal/handler/availability.go:155-163` — `json.RawMessage` plus the second `json.Unmarshal` that turns it into `*string`.
- `internal/handler/availability_rule_test.go` — `updateTimes`, `updateDayOfWeek`, `notFound`, `invalidDayOfWeek`, `invalidHHMM`, `endNotAfterStart`, `conflictWith409`; none touches `event_type_id`.

## Evidence
Probed at `fe75122`: assign `{"event_type_id":"<id>"}` → 200 with the id; `{"start_time":"10:00"}` → assignment unchanged; `{"event_type_id":null}` → 200 with `event_type_id: null`, persisted by `GET /v1/availability-rules`.

## Required outcome
All three cases pinned by tests, so the raw-message handling cannot be reduced back to `*string` (which silently reintroduces "clear does nothing") without a red test.


if req.DayOfWeek != nil {
Expand All @@ -174,8 +181,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
Loading