Merge branch 'refactor/simpler-timings' into 'master'

Refactor/simpler timings

See merge request gk1623/drp-48!18

Co-authored-by: Barf-Vader <47476490+Barf-Vader@users.noreply.github.com>
This commit is contained in:
Ling, Alex
2025-06-13 02:11:41 +00:00
14 changed files with 399 additions and 141 deletions

View File

@@ -5,7 +5,7 @@
onclick?: (event: MouseEvent) => void;
disabled?: boolean;
type?: "button" | "submit" | "reset";
style?: "normal" | "red";
style?: "normal" | "red" | "invisible";
formaction?: string;
children?: Snippet;
}
@@ -45,6 +45,9 @@
.red {
background-color: #bd4949;
}
.invisible {
background: none;
}
.button:focus {
outline: 2px solid #007bff;
}

View File

@@ -12,7 +12,7 @@
"No Outlets": "compulsoryTagRed",
"Some Outlets": "compulsoryTagYellow",
"Good WiFi": "compulsoryTagGreen",
"Bad WiFi": "compulsoryTagRed",
"Bad/No WiFi": "compulsoryTagRed",
"Moderate WiFi": "compulsoryTagYellow",
"No WiFi": "compulsoryTagRed"
};

View File

@@ -18,7 +18,7 @@
// Compute the display string for opening times
let openingDisplay = $state("");
if (todayHours) {
openingDisplay = todayHours.is_24_7
openingDisplay = todayHours.open_today_status
? "Open 24/7"
: `${formatTime(todayHours.opens_at)} - ${formatTime(todayHours.closes_at)}`;
} else {

View File

@@ -0,0 +1,131 @@
<script lang="ts">
import { daysOfWeek } from "$lib";
import CrossUrl from "../../assets/cross.svg";
interface Props {
index: number;
openingValue: string;
closingValue: string;
openTodayStatus: boolean | null;
onHide?: () => void;
day: number; //0-6 for Sunday-Saturday, 7 for all days, 8 for all other days
}
let {
index,
openingValue = $bindable(),
closingValue = $bindable(),
openTodayStatus = $bindable(),
day = $bindable(),
onHide
}: Props = $props();
</script>
<div class="opening-time-item">
{#if day <= 6}
<select bind:value={day} class="dayOfWeek">
{#each [0, 1, 2, 3, 4, 5, 6] as dayNum (dayNum)}
<option value={dayNum}>{daysOfWeek[dayNum]}</option>
{/each}
</select>
{:else}
<label for={"opens-" + index} class="dayOfWeek">{daysOfWeek[day]}</label>
{/if}
<label for={"isAllDay-" + index}>
<input
id={"isAllDay-" + index}
class="checkbox"
type="checkbox"
bind:checked={
() => openTodayStatus === true, (v) => (openTodayStatus = v ? true : null)
}
/>
Open all day
</label>
<label for={"isclosed-" + index}>
<input
id={"isclosed-" + index}
class="checkbox"
type="checkbox"
bind:checked={
() => openTodayStatus === false, (v) => (openTodayStatus = v ? false : null)
}
/>
Closed
</label>
{#if onHide}
<button class="hideButton" onclick={onHide} type="button">
<img src={CrossUrl} alt="nah" />
</button>
{/if}
{#if openTodayStatus === null}
<div class="timeRange">
<input id={"opens-" + index} type="time" bind:value={openingValue} />
<span class="to">to</span>
<input id={"closes-" + index} type="time" bind:value={closingValue} />
</div>
{/if}
</div>
<style>
.opening-time-item {
display: flex;
flex-direction: row;
gap: 0.25rem 1rem;
padding: 0.5rem;
align-items: center;
flex-wrap: wrap;
position: relative;
}
input[type="time"] {
border: 2px solid #000000;
border-radius: 4px;
background: none;
color: #000000;
padding: 0.25rem;
flex: 1;
filter: brightness(0) saturate(100%) invert(98%) sepia(8%) saturate(555%) hue-rotate(54deg)
brightness(100%) contrast(102%);
}
input[type="checkbox"] {
margin: 0;
padding: 0;
}
.timeRange {
display: flex;
flex-direction: row;
gap: 0.5rem;
align-items: center;
width: 100%;
}
.dayOfWeek {
display: flex;
align-items: center;
font-weight: bold;
justify-content: center;
text-align: center;
border-radius: 0.25rem;
background-color: #eaffeb;
color: #2e4653;
cursor: pointer;
padding: 0.2rem 0.4rem;
font-size: 1rem;
}
.hideButton {
background: none;
border: none;
margin: 0 0.5% 0 auto;
width: 5%;
padding: 0;
overflow: visible;
}
.hideButton img {
width: 120%;
transform: scale(2);
}
</style>

83
src/lib/database.d.ts vendored
View File

@@ -69,6 +69,47 @@ export type Database = {
},
]
}
study_space_hours: {
Row: {
closes_at: string
created_at: string | null
day_of_week: number
id: string
open_today_status: boolean | null
opens_at: string
study_space_id: string | null
updated_at: string | null
}
Insert: {
closes_at: string
created_at?: string | null
day_of_week: number
id?: string
open_today_status?: boolean | null
opens_at: string
study_space_id?: string | null
updated_at?: string | null
}
Update: {
closes_at?: string
created_at?: string | null
day_of_week?: number
id?: string
open_today_status?: boolean | null
opens_at?: string
study_space_id?: string | null
updated_at?: string | null
}
Relationships: [
{
foreignKeyName: "study_space_hours_study_space_id_fkey"
columns: ["study_space_id"]
isOneToOne: false
referencedRelation: "study_spaces"
referencedColumns: ["id"]
},
]
}
study_space_images: {
Row: {
created_at: string | null
@@ -161,47 +202,6 @@ export type Database = {
}
Relationships: []
}
study_space_hours: {
Row: {
id: string
study_space_id: string
day_of_week: number
opens_at: string
closes_at: string
is_24_7: boolean
created_at: string | null
updated_at: string | null
}
Insert: {
id?: string
study_space_id: string
day_of_week: number
opens_at: string
closes_at: string
is_24_7: boolean
created_at?: string | null
updated_at?: string | null
}
Update: {
id?: string
study_space_id?: string
day_of_week?: number
opens_at?: string
closes_at?: string
is_24_7?: boolean
created_at?: string | null
updated_at?: string | null
}
Relationships: [
{
foreignKeyName: "study_space_hours_study_space_id_fkey"
columns: ["study_space_id"]
isOneToOne: false
referencedRelation: "study_spaces"
referencedColumns: ["id"]
},
]
}
}
Views: {
[_ in never]: never
@@ -331,3 +331,4 @@ export const Constants = {
Enums: {},
},
} as const

View File

@@ -57,5 +57,12 @@ export const daysOfWeek = [
"Wednesday",
"Thursday",
"Friday",
"Saturday"
"Saturday",
"All Days",
"All Other Days"
];
export function timeToMins(time: string) {
const [hour, min] = time.split(":");
return Number(hour) * 60 + Number(min);
}

View File

@@ -62,7 +62,7 @@
(h) => h.day_of_week === new Date().getDay()
);
if (!entry) return false;
if (entry.is_24_7) return true;
if (entry.open_today_status) return true;
const openMin = toMinutes(entry.opens_at);
let closeMin = toMinutes(entry.closes_at);
// Treat midnight as end of day and handle overnight spans
@@ -79,7 +79,7 @@
(h) => h.day_of_week === new Date().getDay()
);
if (!entry) return false;
if (entry.is_24_7) return true;
if (entry.open_today_status) return true;
const openMin = toMinutes(entry.opens_at);
let closeMin = toMinutes(entry.closes_at);
if (closeMin === 0) closeMin = 24 * 60;

View File

@@ -7,7 +7,7 @@
import Report from "$lib/components/Report.svelte";
import Feedback from "$lib/components/Feedback.svelte";
import { onMount } from "svelte";
import { gmapsLoader, daysOfWeek, formatTime } from "$lib";
import { gmapsLoader, daysOfWeek, formatTime, type Table } from "$lib";
import Button from "$lib/components/Button.svelte";
const { data } = $props();
@@ -51,12 +51,20 @@
});
});
const hoursByDay = $derived(new Map(space.study_space_hours.map((h) => [h.day_of_week, h])));
// Collect all timing entries
let timingsPerDay: Record<number, Table<"study_space_hours">[]> = {
0: [],
1: [],
2: [],
3: [],
4: [],
5: [],
6: []
};
const openingEntries = daysOfWeek.map((day, idx) => ({
day,
entry: hoursByDay.get(idx)
}));
for (const entry of space.study_space_hours) {
timingsPerDay[entry.day_of_week].push(entry);
}
</script>
<Navbar>
@@ -100,20 +108,26 @@
{/if}
<hr />
<div class="subtitle">Opening Times:</div>
{#each openingEntries as { day, entry } (entry)}
{#each Array(7).keys() as idx (idx)}
{@const entries = timingsPerDay[idx]}
<div class="opening-entry">
<span class="day">{day}:</span>
<span class="times">
{#if entry}
{entry.is_24_7
<span class="day">{daysOfWeek[idx]}</span>
<div class="times">
{#each entries as entry (entry)}
<span class="time">
{entry.open_today_status
? "Open All Day"
: entry.open_today_status === false
? "Closed"
: `${formatTime(entry.opens_at)} ${formatTime(entry.closes_at)}`}
{:else}
Closed
{/if}
</span>
{:else}
<span class="time">Not known</span>
{/each}
</div>
</div>
{/each}
<hr />
<div class="subtitle">Where it is:</div>
<p class="addrContainer">
@@ -167,7 +181,7 @@
background-color: #2e3c42;
width: 70%;
border: none;
margin: 0 auto;
margin: 1rem auto 0;
}
.nameContainer {
@@ -260,22 +274,30 @@
}
.opening-entry {
display: grid;
grid-template-columns: auto 1fr;
display: flex;
gap: 0.75rem;
padding: 0.5rem 1.4rem;
align-items: center;
background-color: #2e4653;
margin: 0.2rem;
border-radius: 0.5rem;
}
.opening-entry .day {
font-weight: bold;
color: #ffffff;
white-space: nowrap;
align-items: center;
justify-content: center;
}
.opening-entry .times {
display: flex;
flex-direction: column;
flex-wrap: wrap;
gap: 0.25rem 1.5rem;
flex: 1;
align-items: end;
}
.opening-entry .time {
font-family: monospace;
background-color: rgba(255, 255, 255, 0.1);
padding: 0.25rem 0.5rem;
border-radius: 0.25rem;
color: #eaffeb;
}
</style>

View File

@@ -12,7 +12,7 @@ type StudySpaceData = Omit<
day_of_week: number;
opens_at: string;
closes_at: string;
is_24_7: boolean;
open_today_status: boolean | null;
}[];
};
@@ -42,7 +42,7 @@ export const load: PageServerLoad = async ({ params, locals: { supabase } }) =>
const images = studySpaceData.study_space_images || [];
const { data: hours, error: hoursErr } = await supabase
.from("study_space_hours")
.select("day_of_week, opens_at, closes_at, is_24_7")
.select("day_of_week, opens_at, closes_at, open_today_status")
.eq("study_space_id", params.id)
.order("day_of_week", { ascending: true });
if (hoursErr) error(500, "Failed to load opening times");

View File

@@ -6,13 +6,15 @@
import crossUrl from "$lib/assets/cross.svg";
import Button from "$lib/components/Button.svelte";
import Images from "$lib/components/inputs/Images.svelte";
import OpeningTimesDay from "$lib/components/inputs/OpeningTimesDay.svelte";
import {
availableStudySpaceTags,
wifiTags,
powerOutletTags,
volumeTags,
gmapsLoader,
daysOfWeek
daysOfWeek,
timeToMins
} from "$lib";
import { onMount } from "svelte";
import type { Json } from "$lib/database.js";
@@ -21,13 +23,15 @@
const { supabase } = $derived(data);
const { space, images } = $derived(data);
interface OpeningTime {
day_of_week: number;
opens_at: string;
closes_at: string;
open_today_status: boolean | null;
}
const studySpaceData = $state({
opening_times: daysOfWeek.map((_, index) => ({
day_of_week: index,
opens_at: "",
closes_at: "",
is_24_7: false
})),
opening_times: [] as OpeningTime[],
...space
});
@@ -57,12 +61,83 @@
);
let spaceImgs = $state<FileList>();
let uploading = $state(false);
function checkTimings() {
console.log(studySpaceData.opening_times);
let cannotExist = [] as number[];
const opensAtMinsAll = timeToMins(allDays.opens_at);
const closesAtMinsAll = timeToMins(allDays.closes_at);
if (opensAtMinsAll >= closesAtMinsAll) {
alert(`Opening time for all days is after closing time.`);
return false;
}
for (const entry of studySpaceData.opening_times) {
if (cannotExist.includes(entry.day_of_week)) {
alert(
"You marked a day as either closed or open all day, and then provided another timing."
);
return false;
}
if (entry.open_today_status != null) {
cannotExist.push(entry.day_of_week);
}
const opensAtMins = timeToMins(entry.opens_at);
const closesAtMins = timeToMins(entry.closes_at);
if (opensAtMins >= closesAtMins) {
alert(`Opening time for ${daysOfWeek[entry.day_of_week]} is after closing time.`);
return false;
}
}
return true;
}
function genTimings(studySpaceId: string) {
const fullDayOfWeek = [0, 1, 2, 3, 4, 5, 6];
console.log(studySpaceData.opening_times, allDays);
// all day only
if (
studySpaceData.opening_times.length === 0 &&
((allDays.closes_at != "" && allDays.opens_at != "") ||
allDays.open_today_status != null)
) {
return fullDayOfWeek.map((day) => ({
study_space_id: studySpaceId,
day_of_week: day,
opens_at: allDays.open_today_status == null ? allDays.opens_at : "00:00",
closes_at: allDays.open_today_status == null ? allDays.closes_at : "00:00",
open_today_status: allDays.open_today_status
}));
}
// some days specified
const nonDefinedDays = fullDayOfWeek.filter(
(day) => !new Set(studySpaceData.opening_times.map((h) => h.day_of_week)).has(day)
);
return studySpaceData.opening_times
.map((h) => ({
study_space_id: studySpaceId,
day_of_week: h.day_of_week,
opens_at: h.opens_at,
closes_at: h.closes_at,
open_today_status: h.open_today_status
}))
.concat(
nonDefinedDays.map((day) => ({
study_space_id: studySpaceId,
day_of_week: day,
opens_at: allDays.opens_at,
closes_at: allDays.closes_at,
open_today_status: allDays.open_today_status
}))
);
}
async function uploadStudySpace() {
if (!checkTimings()) return;
if (!spaceImgs || spaceImgs.length < 1) return alert("Please select an image file.");
if (!studySpaceData.building_location) return alert("Please select a building location.");
const { opening_times, ...spacePayload } = studySpaceData;
const { ...spacePayload } = studySpaceData;
const { data: studySpaceInsert, error: studySpaceError } = await supabase
.from("study_spaces")
@@ -126,17 +201,16 @@
.eq("study_space_id", studySpaceInsert.id);
if (deleteErr) return alert(`Error clearing old hours: ${deleteErr.message}`);
const { error: hoursErr } = await supabase.from("study_space_hours").insert(
opening_times.map((h) => ({
study_space_id: studySpaceInsert.id,
day_of_week: h.day_of_week,
opens_at: h.opens_at,
closes_at: h.closes_at,
is_24_7: h.is_24_7
}))
);
// Nothing is provided
if (
(allDays.closes_at != "" && allDays.opens_at != "") ||
allDays.open_today_status != null
) {
const { error: hoursErr } = await supabase
.from("study_space_hours")
.insert(genTimings(studySpaceInsert.id));
if (hoursErr) return alert(`Error saving opening times: ${hoursErr.message}`);
}
alert("Thank you for your contribution!");
// Redirect to the new study space page
await goto(`/space/${studySpaceInsert.id}`, {
@@ -196,20 +270,12 @@
});
spaceImgs = dt.files;
});
// --- Helper functions for opening times ---
function toggle247(index: number) {
const ot = studySpaceData.opening_times[index];
if (ot.is_24_7) {
ot.opens_at = "00:00";
ot.closes_at = "00:00";
}
}
function updateTimes(index: number) {
const ot = studySpaceData.opening_times[index];
ot.is_24_7 = ot.opens_at === "00:00" && ot.closes_at === "00:00";
}
// Opening times
let allDays = $state({
opens_at: "",
closes_at: "",
open_today_status: null
});
</script>
<Navbar>
@@ -302,41 +368,43 @@
</select>
</div>
</div>
<label for="opening-times-label">Opening Times:</label>
<div class="opening-times">
{#each daysOfWeek as day, index (index)}
<div class="opening-time-item">
<label for={"opens-" + index}>{day}</label>
<input
id={"opens-" + index}
type="time"
bind:value={studySpaceData.opening_times[index].opens_at}
required
onchange={() => updateTimes(index)}
<label for="openingTimes">Opening times (Optional):</label>
<div class="allDaysTiming">
{#each studySpaceData.opening_times as opening_time, index (index)}
<OpeningTimesDay
{index}
bind:openingValue={opening_time.opens_at}
bind:closingValue={opening_time.closes_at}
bind:openTodayStatus={opening_time.open_today_status}
bind:day={opening_time.day_of_week}
onHide={() => {
studySpaceData.opening_times.splice(index, 1);
}}
/>
<span>to</span>
<input
id={"closes-" + index}
type="time"
bind:value={studySpaceData.opening_times[index].closes_at}
required
onchange={() => updateTimes(index)}
/>
<label for={"is247-" + index}>
<input
id={"is247-" + index}
type="checkbox"
bind:checked={studySpaceData.opening_times[index].is_24_7}
onchange={() => toggle247(index)}
/>
All day
</label>
</div>
<hr />
{/each}
<OpeningTimesDay
index={-1}
bind:openingValue={allDays.opens_at}
bind:closingValue={allDays.closes_at}
bind:openTodayStatus={allDays.open_today_status}
day={studySpaceData.opening_times.length === 0 ? 7 : 8}
/>
</div>
<Button
style="normal"
type="button"
onclick={() => {
studySpaceData.opening_times.push({
day_of_week: 0,
opens_at: "09:00",
closes_at: "17:00",
open_today_status: null
});
}}>Add new day</Button
>
<label for="tags">Additional tags:</label>
<label for="tags">Additional tags (Optional):</label>
<div class="tagDisplay">
{#each studySpaceData.tags as tagName (tagName)}
<button class="tag" onclick={deleteTag(tagName)} type="button">
@@ -385,7 +453,7 @@
{/if}
</div>
<label for="description">Optional brief description:</label>
<label for="description">Brief description (Optional):</label>
<Textarea
name="description"
bind:value={studySpaceData.description}
@@ -572,6 +640,24 @@
}
/* Opening times layout and inputs styling */
.allDaysTiming {
border-radius: 0.5rem;
background: none;
display: flex;
flex-direction: column;
flex-wrap: wrap;
gap: 0.5rem;
}
hr {
margin: 0%;
padding: 0;
width: 100%;
height: 2px;
border: none;
background-color: #eaffeb;
border-radius: 5rem;
}
.opening-times {
display: flex;
flex-direction: column;

View File

@@ -0,0 +1,5 @@
alter table "public"."study_space_hours" drop column "is_24_7";
alter table "public"."study_space_hours" add column "open_today_status" boolean;

View File

@@ -0,0 +1,3 @@
alter table "public"."study_space_hours" alter column "day_of_week" set not null;

View File

@@ -43,10 +43,10 @@ CREATE TABLE reports (
CREATE TABLE study_space_hours (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
study_space_id UUID REFERENCES study_spaces(id) ON DELETE CASCADE,
day_of_week INT CHECK (day_of_week BETWEEN 0 AND 6), -- 0 = Sunday, 6 = Saturday
day_of_week INT CHECK (day_of_week BETWEEN 0 AND 6) NOT NULL, -- 0 = Sunday, 6 = Saturday
opens_at TIME NOT NULL,
closes_at TIME NOT NULL,
is_24_7 BOOLEAN DEFAULT FALSE,
open_today_status BOOLEAN,
created_at timestamp with time zone DEFAULT now(),
updated_at timestamp with time zone DEFAULT now()
);

View File

@@ -2,7 +2,7 @@ CREATE TABLE users (
id uuid PRIMARY KEY REFERENCES auth.users ON DELETE CASCADE,
is_admin boolean NOT NULL DEFAULT false,
created_at timestamp with time zone NOT NULL DEFAULT now(),
updated_at timestamp with time zone NOT NULL DEFAULT now(),
updated_at timestamp with time zone NOT NULL DEFAULT now()
);
CREATE TRIGGER users_handle_updated_at