18 Commits

Author SHA1 Message Date
Barf-Vader
4c91968582 fix: fix view report 2025-06-12 17:52:16 +01:00
Barf-Vader
8e49454b6f refactor: moved search into Navbar component 2025-06-12 17:33:47 +01:00
07742ad405 fix: fix function for signups 2025-06-12 16:48:41 +01:00
Temesgen, Tadios
9882594551 Merge branch 'r-merge' into 'master'
merge: Merged r-merge into master

See merge request gk1623/drp-48!17

Co-authored-by: Caspar Jojo Asaam <caspar@Caspars-MacBook-Pro-6597.local>
Co-authored-by: Caspar Jojo Asaam <caspar@dyn3159-95.wlan.ic.ac.uk>
2025-06-12 15:33:48 +00:00
Caspar Jojo Asaam
950ab5193a merge: Resolved merge conflicts
Co-Authored-By: Tadios Temesgen <tt2022@ic.ac.uk>
2025-06-12 16:21:20 +01:00
0c3d0a00b8 Merge branch 'logins' into 'master'
feat: logins and toggleable admin mode

See merge request gk1623/drp-48!15
2025-06-12 14:46:20 +00:00
788007c1cc feat: complete logins 2025-06-12 15:42:29 +01:00
3bdee89eed feat: initial logins 2025-06-12 15:42:29 +01:00
Caspar Jojo Asaam
30f44b0ac6 feat: Added current opening times to each study space on the main page. In the expanded card, you can view the opening times for the full week. Improved ui
Co-Authored-By: Tadios Temesgen <tt2022@ic.ac.uk>
2025-06-12 15:40:20 +01:00
Ling, Alex
b516196d38 Merge branch 'feat/feedback' into 'master'
Feat/feedback

See merge request gk1623/drp-48!13

Co-authored-by: Barf-Vader <47476490+Barf-Vader@users.noreply.github.com>
2025-06-12 14:34:35 +00:00
Barf-Vader
8a6f447202 fix: tag input now works 2025-06-12 15:30:32 +01:00
Barf-Vader
5b7f63f63f feat: Added feedback feature 2025-06-12 15:30:32 +01:00
Caspar Jojo Asaam
afe7b3078d feat: Added current opening times to each study space on the main page. In the expanded card, you can view the opening times for the full week. Improved ui
Co-Authored-By: Tadios Temesgen <tt2022@ic.ac.uk>
2025-06-12 14:59:22 +01:00
Caspar Jojo Asaam
7117f85ef7 feat: added migration for a study_space_hours table and allowed for the user to make time inputs when submitting a new space
Co-Authored-By: Tadios Temesgen <tt2022@ic.ac.uk>
2025-06-12 10:10:41 +01:00
Caspar Jojo Asaam
7c0f9b3f52 Merge branch 'fix/filter-by-tags' into 'master'
fix: Search bar on main page no longer overflows. Selected tags no longer...

See merge request gk1623/drp-48!14

Co-authored-by: TadiosT <tadios.temesgen@gmail.com>
2025-06-12 01:03:39 +00:00
TadiosT
8de3d9d48c fix: Fixed type and style errors.
Co-Authored By: Caspar Asaam <caspar@dyn3159-95.wlan.ic.ac.uk>
2025-06-12 00:48:49 +01:00
TadiosT
2c8d7e00b5 fix: Search bar on main page no longer overflows. Selected tags no longer appear in dropdown. Can no longer filter by contradiction tags.
Co-Authored By: Caspar Asaam <caspar@dyn3159-95.wlan.ic.ac.uk>
2025-06-12 00:41:50 +01:00
ed2721ff4c fix: re-enable typing in tag text box 2025-06-11 23:52:45 +01:00
26 changed files with 1588 additions and 521 deletions

852
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -5,29 +5,50 @@
onclick?: (event: MouseEvent) => void; onclick?: (event: MouseEvent) => void;
disabled?: boolean; disabled?: boolean;
type?: "button" | "submit" | "reset"; type?: "button" | "submit" | "reset";
style?: "normal" | "red";
formaction?: string;
children?: Snippet; children?: Snippet;
} }
const { children, ...rest }: Props = $props(); interface LinkProps {
href: string;
type: "link";
style?: "normal" | "red";
children?: Snippet;
}
const { children, type, style = "normal", ...rest }: Props | LinkProps = $props();
</script> </script>
<button {...rest}> {#if type === "link"}
<a {...rest} class="button {style}">
{@render children?.()} {@render children?.()}
</button> </a>
{:else}
<button class="button {style}" {type} {...rest}>
{@render children?.()}
</button>
{/if}
<style> <style>
button { .button {
padding: 0.5rem 1rem; padding: 0.5rem 1rem;
border-radius: 0.5rem; border-radius: 0.5rem;
background: linear-gradient(-83deg, #3fb095, #49bd85);
box-shadow: 0rem 0rem 0.5rem #182125; box-shadow: 0rem 0rem 0.5rem #182125;
color: #eaffeb; color: #eaffeb;
border: none; border: none;
cursor: pointer; cursor: pointer;
text-decoration: none;
text-align: center;
} }
button:focus { .normal {
background: linear-gradient(-83deg, #3fb095, #49bd85);
}
.red {
background-color: #bd4949;
}
.button:focus {
outline: 2px solid #007bff; outline: 2px solid #007bff;
} }
button:disabled { .button:disabled {
background: linear-gradient(-18deg, #66697b, #4e4e5e); background: linear-gradient(-18deg, #66697b, #4e4e5e);
cursor: not-allowed; cursor: not-allowed;
} }

View File

@@ -0,0 +1,338 @@
<script lang="ts">
import crossUrl from "$lib/assets/cross.svg";
import type { Table } from "$lib";
import type { SupabaseClient } from "@supabase/supabase-js";
import type { Database } from "$lib/database.d.ts";
import { availableStudySpaceTags, wifiTags, powerOutletTags, volumeTags } from "$lib";
import { invalidate } from "$app/navigation";
type StudySpaceData = Omit<
Table<"study_spaces">,
"id" | "created_at" | "updated_at" | "building_location_old" | "building_location"
> & {
id?: string;
building_location?: google.maps.places.PlaceResult;
};
interface Props {
studySpaceData: StudySpaceData;
supabase: SupabaseClient<Database>;
hideFunc: () => void;
}
const { studySpaceData, supabase, hideFunc }: Props = $props();
let newStudySpaceData: StudySpaceData = $state({ ...studySpaceData });
let uploading = $state(false);
async function uploadFeedback() {
const { error: feedbackUpload } = await supabase
.from("study_spaces")
.update({
volume: newStudySpaceData.volume,
wifi: newStudySpaceData.wifi,
power: newStudySpaceData.power,
tags: newStudySpaceData.tags
})
.eq("id", newStudySpaceData.id ?? "");
invalidate("db:study_spaces");
if (feedbackUpload) return alert(`Error submitting feedback: ${feedbackUpload.message}`);
else alert("Feedback submitted successfully!");
}
// Tag
let tagFilter = $state("");
let tagFilterElem = $state<HTMLInputElement>();
let filteredTags = $derived(
availableStudySpaceTags
.filter((tag) => tag.toLowerCase().includes(tagFilter.toLowerCase()))
.filter((tag) => !newStudySpaceData.tags.includes(tag))
);
let dropdownVisible = $state(false);
function deleteTag(tagName: string) {
return () => {
newStudySpaceData.tags = newStudySpaceData.tags.filter((tag) => tag !== tagName);
};
}
function addTag(tagName: string) {
return () => {
if (!newStudySpaceData.tags.includes(tagName)) {
newStudySpaceData.tags.push(tagName);
}
tagFilter = "";
};
}
</script>
<div class="overlay">
<form
onsubmit={async (event) => {
event.preventDefault();
uploading = true;
await uploadFeedback();
uploading = false;
hideFunc();
}}
class="feedbackContainer"
>
<h1 class="submitHeader">Submit Feedback</h1>
<div class="compulsoryTags">
<div class="compulsoryContainer">
<label for="volume">Sound level:</label>
<select
bind:value={newStudySpaceData.volume}
name="volume"
class="compulsoryTagSelect"
>
<option value="" disabled selected>How noisy is it?</option>
{#each volumeTags as volumeTag (volumeTag)}
<option value={volumeTag}>{volumeTag}</option>
{/each}
</select>
</div>
<div class="compulsoryContainer">
<label for="powerOutlets">Power outlets:</label>
<select
bind:value={newStudySpaceData.power}
name="poweOutlets"
class="compulsoryTagSelect"
>
<option value="" disabled selected>Power outlets?</option>
{#each powerOutletTags as powerOutletTag (powerOutletTag)}
<option value={powerOutletTag}>{powerOutletTag}</option>
{/each}
</select>
</div>
<div class="compulsoryContainer">
<label for="wifi">Wifi:</label>
<select bind:value={newStudySpaceData.wifi} name="wifi" class="compulsoryTagSelect">
<option value="" disabled selected>How's the wifi?</option>
{#each wifiTags as wifiTag (wifiTag)}
<option value={wifiTag}>{wifiTag}</option>
{/each}
</select>
</div>
</div>
<label for="tags">Additional tags:</label>
<div class="tagDisplay">
{#each newStudySpaceData.tags as tagName (tagName)}
<button class="tag" onclick={deleteTag(tagName)} type="button">
{tagName}
<img src={crossUrl} alt="delete" /></button
>
{/each}
<input
type="text"
name="tagInput"
class="tagInput"
bind:value={tagFilter}
bind:this={tagFilterElem}
onfocus={() => {
dropdownVisible = true;
}}
onblur={() => {
dropdownVisible = false;
}}
onkeypress={(event) => {
if (event.key === "Enter") {
event.preventDefault();
const tag = filteredTags[0];
if (tag) addTag(tag)();
}
}}
placeholder="Add tags..."
/>
{#if dropdownVisible}
<div class="tagDropdown">
{#each filteredTags as avaliableTag (avaliableTag)}
<button
class="avaliableTag"
onclick={addTag(avaliableTag)}
onmousedown={(e) => {
// Keep input focused
e.preventDefault();
e.stopPropagation();
}}
type="button"
>
{avaliableTag}
</button>
{/each}
</div>
{/if}
</div>
<button disabled={uploading} class="submit">Submit</button>
<button type="button" class="exit" aria-label="exit" onclick={hideFunc}
><img src={crossUrl} alt="exit" /></button
>
</form>
</div>
<style>
.overlay {
display: flex;
width: 100%;
height: 100%;
position: fixed;
justify-content: center;
align-items: center;
background-color: rgba(8, 15, 18, 0.9);
z-index: 100;
}
.feedbackContainer {
display: flex;
flex-direction: column;
width: 80%;
gap: 0.5rem;
padding: 1rem;
background-color: #182125;
border-radius: 0.5rem;
box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.1);
color: #eaffeb;
position: absolute;
translate: 0 -3.5rem;
border: 2px solid #eaffeb;
}
.submitHeader {
width: 80%;
}
.submit {
width: 100%;
padding: 0.5rem;
border-radius: 0.5rem;
border: none;
background-color: #49bd85;
color: #ffffff;
font-size: 1rem;
cursor: pointer;
}
.exit {
position: absolute;
top: 0.1rem;
right: 0.1rem;
background: none;
border: none;
cursor: pointer;
}
.tagDisplay {
display: flex;
gap: 0.4rem;
flex-wrap: wrap;
align-items: left;
justify-content: left;
position: relative;
width: 100%;
height: auto;
padding: 0.5rem;
border-radius: 0.5rem;
border: 2px solid #eaffeb;
background: none;
color: #eaffeb;
font-size: 1rem;
}
.tagInput {
width: 100%;
height: 100%;
background: none;
color: #eaffeb;
font-size: 1rem;
border: none;
outline: none;
}
::placeholder {
color: #859a90;
opacity: 1;
}
.tag {
display: flex;
align-items: center;
border-radius: 0.25rem;
background-color: #2e4653;
color: #eaffeb;
font-size: 0.9rem;
cursor: pointer;
border-width: 0rem;
}
.tag img {
width: 1rem;
height: 1rem;
margin-left: 0.2rem;
}
.tagDropdown {
width: 100%;
display: flex;
gap: 0.4rem;
flex-wrap: wrap;
position: absolute;
background-color: #2e4653;
box-shadow: 1px 1px 0.5rem rgba(0, 0, 0, 0.5);
border-radius: 0.5rem;
overflow-y: auto;
max-height: 10rem;
top: 100%;
left: 50%;
transform: translateX(-50%);
}
.avaliableTag {
width: 100%;
text-align: left;
background: none;
border: none;
color: #eaffeb;
font-size: 0.9rem;
margin: 0%;
padding: 0 0.8rem 0.4rem;
}
.avaliableTag:first-child {
padding-top: 0.6rem;
background-color: hsl(201, 26%, 60%);
}
.avaliableTag:last-child {
padding-bottom: 0.6rem;
}
.compulsoryTags {
display: flex;
flex-direction: column;
gap: 0.4rem;
border-radius: 0.5rem;
background-color: none;
width: 100%;
font-size: 1rem;
}
.compulsoryContainer {
display: flex;
flex-direction: column;
align-items: left;
justify-content: top;
border-radius: 0.5rem;
background-color: none;
}
.compulsoryTagSelect {
width: 100%;
height: 100%;
padding: 0.5rem;
border-radius: 0.5rem;
border: 2px solid #eaffeb;
background: none;
color: #eaffeb;
font-size: 0.9rem;
text-align: left;
}
.compulsoryTagSelect option {
background-color: #2e4653;
color: #eaffeb;
}
</style>

View File

@@ -28,7 +28,6 @@
background: linear-gradient(-77deg, #2e4653, #223a37); background: linear-gradient(-77deg, #2e4653, #223a37);
box-shadow: 0rem 0rem 0.5rem #182125; box-shadow: 0rem 0rem 0.5rem #182125;
align-items: center; align-items: center;
overflow: hidden;
z-index: 100; z-index: 100;
} }

View File

@@ -0,0 +1,40 @@
<script lang="ts">
import type { Table } from "$lib";
import { formatTime } from "$lib";
interface Props {
hours: Table<"study_space_hours">[];
}
// Destructure hours with a safe default to avoid undefined
const { hours }: Props = $props();
// Determine today's index (0 = Sunday, 6 = Saturday)
const todayIndex = new Date().getDay();
// Find the hours entry matching today
const todayHours = hours.find((h) => h.day_of_week === todayIndex);
// Compute the display string for opening times
let openingDisplay = $state("");
if (todayHours) {
openingDisplay = todayHours.is_24_7
? "Open 24/7"
: `${formatTime(todayHours.opens_at)} - ${formatTime(todayHours.closes_at)}`;
} else {
openingDisplay = "Closed";
}
</script>
<div class="opening-times">
<strong>Today's Opening Times:</strong>
{openingDisplay}
</div>
<style>
.opening-times {
margin-top: 0.5rem;
font-size: 0.9rem;
color: #eaffeb;
}
</style>

View File

@@ -1,15 +1,17 @@
<script lang="ts"> <script lang="ts">
import CompulsoryTags from "./CompulsoryTags.svelte"; import CompulsoryTags from "./CompulsoryTags.svelte";
import OpeningTimes from "./OpeningTimes.svelte";
import type { Table } from "$lib"; import type { Table } from "$lib";
interface Props { interface Props {
space: Table<"study_spaces">; space: Table<"study_spaces">;
hours: Table<"study_space_hours">[];
alt: string; alt: string;
imgSrc: string; imgSrc: string;
href?: string; href?: string;
} }
const { space, alt, imgSrc, href }: Props = $props(); const { space, hours, alt, imgSrc, href }: Props = $props();
</script> </script>
<a class="card" {href}> <a class="card" {href}>
@@ -24,6 +26,7 @@
{/each} {/each}
</div> </div>
{/if} {/if}
<div class="openingTimesContainer"><OpeningTimes {hours} /></div>
</div> </div>
</a> </a>

View File

@@ -5,12 +5,13 @@
value?: string | null; value?: string | null;
placeholder?: string; placeholder?: string;
required?: boolean; required?: boolean;
type?: "text" | "password" | "email" | "number";
} }
let { inputElem = $bindable(), value = $bindable(), name, ...rest }: Props = $props(); let { inputElem = $bindable(), value = $bindable(), name, ...rest }: Props = $props();
</script> </script>
<input type="text" id={name} {name} bind:value bind:this={inputElem} {...rest} /> <input id={name} {name} bind:value bind:this={inputElem} {...rest} />
<style> <style>
input { input {

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

@@ -140,6 +140,68 @@ export type Database = {
} }
Relationships: [] Relationships: []
} }
users: {
Row: {
created_at: string
id: string
is_admin: boolean
updated_at: string
}
Insert: {
created_at?: string
id: string
is_admin?: boolean
updated_at?: string
}
Update: {
created_at?: string
id?: string
is_admin?: boolean
updated_at?: string
}
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: { Views: {
[_ in never]: never [_ in never]: never
@@ -269,4 +331,3 @@ export const Constants = {
Enums: {}, Enums: {},
}, },
} as const } as const

View File

@@ -8,7 +8,6 @@ export type Enum<T extends keyof Database["public"]["Enums"]> = Database["public
export const availableStudySpaceTags = [ export const availableStudySpaceTags = [
"Crowded", "Crowded",
"Group study", "Group study",
"24/7",
"Food allowed", "Food allowed",
"No food allowed", "No food allowed",
"Well lit", "Well lit",
@@ -43,3 +42,20 @@ export async function gmapsLoader() {
libraries: ["places"] libraries: ["places"]
}); });
} }
export function formatTime(time: string) {
const [h, m] = time.split(":").map(Number);
const date = new Date();
date.setHours(h, m);
return date.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" });
}
export const daysOfWeek = [
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday"
];

View File

@@ -1,9 +1,29 @@
import type { LayoutServerLoad } from "./$types"; import type { LayoutServerLoad } from "./$types";
export const load: LayoutServerLoad = async ({ locals: { safeGetSession }, cookies }) => { export const load: LayoutServerLoad = async ({
locals: { safeGetSession, supabase },
cookies,
depends
}) => {
depends("supabase:auth");
const { session } = await safeGetSession(); const { session } = await safeGetSession();
let adminMode = false;
if (session) {
const { data: userData, error: userError } = await supabase
.from("users")
.select("*")
.eq("id", session.user.id)
.single();
if (userError) {
console.error("Failed to fetch user data:", userError);
}
if (userData?.is_admin) {
adminMode = true;
}
}
return { return {
session, session,
adminMode,
cookies: cookies.getAll() cookies: cookies.getAll()
}; };
}; };

View File

@@ -2,14 +2,22 @@
import posthog from "posthog-js"; import posthog from "posthog-js";
import logoUrl from "$lib/assets/logo.svg"; import logoUrl from "$lib/assets/logo.svg";
import { onMount } from "svelte"; import { onMount } from "svelte";
import { invalidate } from "$app/navigation";
const { children } = $props(); let { data, children } = $props();
let { session, supabase } = $derived(data);
onMount(() => { onMount(() => {
posthog.init("phc_hTnel2Q8GKo0TgIBnFWBueJW1ATmCG9tJOtETnQTUdY", { posthog.init("phc_hTnel2Q8GKo0TgIBnFWBueJW1ATmCG9tJOtETnQTUdY", {
api_host: "https://eu.i.posthog.com", api_host: "https://eu.i.posthog.com",
person_profiles: "always" person_profiles: "always"
}); });
const { data } = supabase.auth.onAuthStateChange((_, newSession) => {
if (newSession?.expires_at !== session?.expires_at) {
invalidate("supabase:auth");
}
});
return () => data.subscription.unsubscribe();
}); });
</script> </script>
@@ -25,6 +33,7 @@
margin: 0; margin: 0;
padding: 0; padding: 0;
width: 100%; width: 100%;
overflow-x: hidden;
} }
:global(html) { :global(html) {

View File

@@ -40,5 +40,5 @@ export const load: LayoutLoad = async ({ data, depends, fetch }) => {
data: { user } data: { user }
} = await supabase.auth.getUser(); } = await supabase.auth.getUser();
return { session, supabase, user }; return { session, supabase, user, adminMode: data.adminMode };
}; };

View File

@@ -5,7 +5,7 @@ export const load: PageServerLoad = async ({ depends, locals: { supabase } }) =>
depends("db:study_spaces"); depends("db:study_spaces");
const { data: studySpaces, error: err } = await supabase const { data: studySpaces, error: err } = await supabase
.from("study_spaces") .from("study_spaces")
.select("*, study_space_images(*)"); .select("*, study_space_images(*), study_space_hours(*)");
if (err) error(500, "Failed to load study spaces"); if (err) error(500, "Failed to load study spaces");
return { return {

View File

@@ -3,33 +3,92 @@
import defaultImg from "$lib/assets/study_space.png"; import defaultImg from "$lib/assets/study_space.png";
import crossUrl from "$lib/assets/cross.svg"; import crossUrl from "$lib/assets/cross.svg";
import Navbar from "$lib/components/Navbar.svelte"; import Navbar from "$lib/components/Navbar.svelte";
import { allTags } from "$lib"; import { allTags, volumeTags, wifiTags, powerOutletTags } from "$lib";
import Button from "$lib/components/Button.svelte";
const { data } = $props(); const { data } = $props();
const { studySpaces, supabase } = $derived(data); const { studySpaces, supabase, session, adminMode } = $derived(data);
let selectedTags = $state<string[]>([]); let selectedTags = $state<string[]>([]);
let tagFilter = $state(""); let tagFilter = $state("");
let openingFilter = $state("");
let closingFilter = $state("");
let tagFilterElem = $state<HTMLInputElement>(); let tagFilterElem = $state<HTMLInputElement>();
function categorySelected(category: string[]) {
return category.some((tag) => selectedTags.includes(tag));
}
let filteredTags = $derived( let filteredTags = $derived(
allTags allTags
.filter((tag) => tag.toLowerCase().includes(tagFilter.toLowerCase())) .filter((tag) => tag.toLowerCase().includes(tagFilter.toLowerCase()))
.filter((tag) => allTags.includes(tag)) .filter((tag) => !selectedTags.includes(tag))
.filter((tag) => {
if (selectedTags.includes(tag)) return false;
if (categorySelected(volumeTags) && volumeTags.includes(tag)) return false;
if (categorySelected(wifiTags) && wifiTags.includes(tag)) return false;
if (categorySelected(powerOutletTags) && powerOutletTags.includes(tag))
return false;
return true;
})
); );
// Convert "HH:MM" or "HH:MM:SS" to minutes since midnight
function toMinutes(timeStr: string): number {
const [h, m] = timeStr.slice(0, 5).split(":").map(Number);
return h * 60 + m;
}
// Combine tag and time filtering
let filteredStudySpaces = $derived( let filteredStudySpaces = $derived(
selectedTags.length === 0 studySpaces
? studySpaces // tag filtering
: studySpaces.filter((space) => { .filter((space) => {
if (selectedTags.length === 0) return true;
const allTags = [ const allTags = [
...(space.tags || []), ...(space.tags || []),
space.volume, space.volume,
space.wifi, space.wifi,
space.power space.power
].filter(Boolean); ].filter(Boolean);
return selectedTags.every((tag) => allTags.includes(tag)); return selectedTags.every((tag) => allTags.includes(tag));
}) })
// opening time filter
.filter((space) => {
if (!openingFilter) return true;
const entry = space.study_space_hours?.find(
(h) => h.day_of_week === new Date().getDay()
);
if (!entry) return false;
if (entry.is_24_7) return true;
const openMin = toMinutes(entry.opens_at);
let closeMin = toMinutes(entry.closes_at);
// Treat midnight as end of day and handle overnight spans
if (closeMin === 0) closeMin = 24 * 60;
if (closeMin <= openMin) closeMin += 24 * 60;
const filterMin = toMinutes(openingFilter);
// Include spaces open at the filter time
return filterMin >= openMin && filterMin < closeMin;
})
// closing time filter
.filter((space) => {
if (!closingFilter) return true;
const entry = space.study_space_hours?.find(
(h) => h.day_of_week === new Date().getDay()
);
if (!entry) return false;
if (entry.is_24_7) return true;
const openMin = toMinutes(entry.opens_at);
let closeMin = toMinutes(entry.closes_at);
if (closeMin === 0) closeMin = 24 * 60;
if (closeMin <= openMin) closeMin += 24 * 60;
const filterMin =
toMinutes(closingFilter) === 0 ? 24 * 60 : toMinutes(closingFilter);
// Include spaces still open at the filter time
return filterMin > openMin && filterMin <= closeMin;
})
); );
let dropdownVisible = $state(false); let dropdownVisible = $state(false);
@@ -51,15 +110,7 @@
</script> </script>
<Navbar> <Navbar>
<a href="/space/new/edit"> <div class="navActions">
<img src={crossUrl} alt="new" class="new-space" />
</a>
</Navbar>
<main>
<a href="/space/reports" class="checkReports">Check Reports</a>
<div class="tag-filter-container">
<form>
<div class="tagDisplay"> <div class="tagDisplay">
{#each selectedTags as tagName (tagName)} {#each selectedTags as tagName (tagName)}
<button class="tag" onclick={deleteTag(tagName)} type="button"> <button class="tag" onclick={deleteTag(tagName)} type="button">
@@ -81,6 +132,7 @@
}} }}
onkeypress={(event) => { onkeypress={(event) => {
if (event.key === "Enter") { if (event.key === "Enter") {
event.preventDefault();
const tag = filteredTags[0]; const tag = filteredTags[0];
if (tag) addTag(tag)(); if (tag) addTag(tag)();
} }
@@ -106,9 +158,30 @@
</div> </div>
{/if} {/if}
</div> </div>
</form> {#if session}
<a href="/space/new/edit">
<img src={crossUrl} alt="new" class="new-space" />
</a>
{/if}
</div> </div>
</Navbar>
<main>
<div class="time-filter-container">
<label>
Open from:
<input type="time" bind:value={openingFilter} />
</label>
<label>
Open until:
<input type="time" bind:value={closingFilter} />
</label>
</div>
{#if adminMode}
<div class="checkReports">
<Button href="/space/reports" type="link" style="red">Check Reports</Button>
</div>
{/if}
{#each filteredStudySpaces as studySpace (studySpace.id)} {#each filteredStudySpaces as studySpace (studySpace.id)}
{@const imgUrl = {@const imgUrl =
studySpace.study_space_images.length > 0 studySpace.study_space_images.length > 0
@@ -121,10 +194,19 @@
href="/space/{studySpace.id}" href="/space/{studySpace.id}"
imgSrc={imgUrl} imgSrc={imgUrl}
space={studySpace} space={studySpace}
hours={studySpace.study_space_hours}
/> />
{/each} {/each}
</main> </main>
<footer>
{#if session}
<Button onclick={() => supabase.auth.signOut()}>Signout</Button>
{:else}
<Button href="/auth" type="link">Login / Signup</Button>
{/if}
</footer>
<style> <style>
main { main {
display: grid; display: grid;
@@ -137,24 +219,49 @@
margin: 0 auto; margin: 0 auto;
} }
footer {
display: flex;
flex-direction: column;
max-width: 600px;
width: 100%;
padding: 1rem;
margin: 0 auto;
}
.new-space { .new-space {
transform: rotate(45deg); transform: rotate(45deg);
} }
.tag-filter-container { .navActions {
grid-column: 1 / -1;
display: flex; display: flex;
justify-content: center; height: 100%;
margin-bottom: 1rem; width: 100%;
align-items: center;
padding-left: 2rem;
gap: 1rem;
z-index: 200;
} }
form { .time-filter-container {
grid-column: 1 / -1;
display: flex; display: flex;
flex-direction: column; gap: 1rem;
padding: 1.5rem; justify-content: center;
margin-bottom: 0.5rem;
}
.time-filter-container label {
display: flex;
align-items: center;
gap: 0.5rem; gap: 0.5rem;
max-width: 32rem; font-size: 1rem;
margin: 0 auto; color: #eaffeb;
}
.time-filter-container input[type="time"] {
background: none;
border: 2px solid #eaffeb;
border-radius: 0.5rem;
padding: 0.25rem 0.5rem;
color: #eaffeb;
} }
.tagDisplay { .tagDisplay {
@@ -174,8 +281,8 @@
font-size: 1rem; font-size: 1rem;
} }
.tagInput { .tagInput {
width: 100%; flex: 1 1 100%;
height: 100%; min-width: 10rem;
background: none; background: none;
color: #eaffeb; color: #eaffeb;
font-size: 1rem; font-size: 1rem;
@@ -216,6 +323,7 @@
top: 100%; top: 100%;
left: 50%; left: 50%;
transform: translateX(-50%); transform: translateX(-50%);
z-index: 1000;
} }
.avaliableTag { .avaliableTag {
@@ -237,14 +345,9 @@
} }
.checkReports { .checkReports {
grid-column: 1 / -1; grid-column: 1 / -1;
display: block; display: flex;
text-align: center; flex-direction: column;
color: #ffeaea;
font-size: 1.2rem; font-size: 1.2rem;
text-decoration: none;
padding: 0.5rem;
background-color: #bd4949;
border-radius: 0.5rem;
} }
@media (max-width: 20rem) { @media (max-width: 20rem) {

View File

@@ -0,0 +1,14 @@
<script lang="ts">
import Navbar from "$lib/components/Navbar.svelte";
import crossUrl from "$lib/assets/cross.svg";
const { children } = $props();
</script>
<Navbar>
<a href="/">
<img src={crossUrl} alt="close" />
</a>
</Navbar>
{@render children?.()}

View File

@@ -0,0 +1,30 @@
import { redirect, error } from "@sveltejs/kit";
import type { Actions } from "./$types";
export const actions: Actions = {
signup: async ({ request, locals: { supabase } }) => {
const formData = await request.formData();
const email = formData.get("email") as string;
const password = formData.get("password") as string;
const { error: authError } = await supabase.auth.signUp({ email, password });
if (authError) {
error(400, "Failed to sign up: " + authError.message);
} else {
redirect(303, "/");
}
},
login: async ({ request, locals: { supabase } }) => {
const formData = await request.formData();
const email = formData.get("email") as string;
const password = formData.get("password") as string;
const { error: authError } = await supabase.auth.signInWithPassword({ email, password });
if (authError) {
error(400, "Failed to log in: " + authError.message);
} else {
redirect(303, "/");
}
}
};

View File

@@ -0,0 +1,36 @@
<script lang="ts">
import Button from "$lib/components/Button.svelte";
import Text from "$lib/components/inputs/Text.svelte";
</script>
<form method="POST" action="?/login">
<label for="email">Email</label>
<Text type="email" name="email" placeholder="your@email.com" />
<label for="password">Password</label>
<Text type="password" name="password" placeholder="*********" />
<div class="actions">
<Button type="submit">Login</Button>
<Button formaction="?/signup">Signup</Button>
</div>
</form>
<style>
form {
display: flex;
flex-direction: column;
gap: 0.5rem;
max-width: 600px;
margin: 1rem auto;
}
label {
margin-top: 0.5rem;
}
.actions {
display: grid;
margin-top: 0.5rem;
grid-template-columns: 1fr 1fr;
gap: 1rem;
}
</style>

View File

@@ -1,10 +1,11 @@
import { error } from "@sveltejs/kit"; import { error } from "@sveltejs/kit";
import type { PageServerLoad } from "./$types"; import type { PageServerLoad } from "./$types";
export const load: PageServerLoad = async ({ params, locals: { supabase } }) => { export const load: PageServerLoad = async ({ depends, params, locals: { supabase } }) => {
depends("db:study_spaces");
const { data: space, error: err } = await supabase const { data: space, error: err } = await supabase
.from("study_spaces") .from("study_spaces")
.select("*, study_space_images(*)") .select("*, study_space_images(*), study_space_hours(*)")
.eq("id", params.id) .eq("id", params.id)
.single(); .single();
if (err) error(500, "Failed to load study space"); if (err) error(500, "Failed to load study space");

View File

@@ -5,13 +5,13 @@
import Carousel from "$lib/components/Carousel.svelte"; import Carousel from "$lib/components/Carousel.svelte";
import CompulsoryTags from "$lib/components/CompulsoryTags.svelte"; import CompulsoryTags from "$lib/components/CompulsoryTags.svelte";
import Report from "$lib/components/Report.svelte"; import Report from "$lib/components/Report.svelte";
import Feedback from "$lib/components/Feedback.svelte";
import { onMount } from "svelte"; import { onMount } from "svelte";
import { gmapsLoader } from "$lib"; import { gmapsLoader, daysOfWeek, formatTime } from "$lib";
import Button from "$lib/components/Button.svelte";
const { data } = $props(); const { data } = $props();
const { space, supabase } = $derived(data); const { space, supabase, adminMode } = $derived(data);
let adminMode = $state(true);
const place = $derived(space.building_location as google.maps.places.PlaceResult); const place = $derived(space.building_location as google.maps.places.PlaceResult);
const imgUrls = $derived( const imgUrls = $derived(
@@ -25,10 +25,15 @@
); );
let isReportVisible = $state(false); let isReportVisible = $state(false);
function hideFunc() { function hideReport() {
isReportVisible = false; isReportVisible = false;
} }
let isFeedbackPromptVisible = $state(false);
function hideFeedbackPrompt() {
isFeedbackPromptVisible = false;
}
let mapElem = $state<HTMLDivElement>(); let mapElem = $state<HTMLDivElement>();
onMount(async () => { onMount(async () => {
if (!mapElem) return console.error("Map element not found"); if (!mapElem) return console.error("Map element not found");
@@ -45,6 +50,13 @@
map map
}); });
}); });
const hoursByDay = $derived(new Map(space.study_space_hours.map((h) => [h.day_of_week, h])));
const openingEntries = daysOfWeek.map((day, idx) => ({
day,
entry: hoursByDay.get(idx)
}));
</script> </script>
<Navbar> <Navbar>
@@ -53,7 +65,17 @@
</a> </a>
</Navbar> </Navbar>
{#if isReportVisible}<Report {data} studySpaceId={space.id} {hideFunc} /> {#if isReportVisible}<Report {data} studySpaceId={space.id} hideFunc={hideReport} />
{/if}
{#if isFeedbackPromptVisible}
<Feedback
studySpaceData={{
...space,
building_location: place
}}
{supabase}
hideFunc={hideFeedbackPrompt}
/>
{/if} {/if}
<main> <main>
<Carousel urls={imgUrls} /> <Carousel urls={imgUrls} />
@@ -77,6 +99,22 @@
</div> </div>
{/if} {/if}
<hr /> <hr />
<div class="subtitle">Opening Times:</div>
{#each openingEntries as { day, entry } (entry)}
<div class="opening-entry">
<span class="day">{day}:</span>
<span class="times">
{#if entry}
{entry.is_24_7
? "Open All Day"
: `${formatTime(entry.opens_at)} ${formatTime(entry.closes_at)}`}
{:else}
Closed
{/if}
</span>
</div>
{/each}
<div class="subtitle">Where it is:</div> <div class="subtitle">Where it is:</div>
<p class="addrContainer"> <p class="addrContainer">
{#if place.name} {#if place.name}
@@ -87,17 +125,24 @@
{/each} {/each}
</p> </p>
<div class="addrMap" bind:this={mapElem}></div> <div class="addrMap" bind:this={mapElem}></div>
{#if adminMode}
<a href={`/space/${space.id}/edit`} class="editButton">Edit</a>
{:else}
<button <button
type="button" type="button"
class="reportButton" class="feedbackButton"
onclick={() => { onclick={() => {
isReportVisible = true; isFeedbackPromptVisible = true;
}}>Report</button }}
> >
Help categorise this space
</button>
<div class="actions">
{#if adminMode}
<Button href="/space/{space.id}/edit" type="link">Edit</Button>
{:else}
<Button onclick={() => (isReportVisible = true)} style="red">Report</Button>
{/if} {/if}
</div>
</main> </main>
<style> <style>
@@ -124,6 +169,7 @@
border: none; border: none;
margin: 0 auto; margin: 0 auto;
} }
.nameContainer { .nameContainer {
z-index: 10; z-index: 10;
display: block; display: block;
@@ -195,21 +241,9 @@
border-radius: 0.5rem; border-radius: 0.5rem;
border: 2px solid #eaffeb; border: 2px solid #eaffeb;
} }
.reportButton { .feedbackButton {
width: 100%; width: 100%;
padding: 0.4rem; padding: 0.7rem;
border-radius: 0.5rem;
border: none;
background-color: #bd4949;
color: #ffffff;
font-size: 1rem;
cursor: pointer;
margin-top: 1rem;
}
.editButton {
width: 100%;
padding: 0.4rem;
border-radius: 0.5rem; border-radius: 0.5rem;
border: none; border: none;
background-color: #49bd85; background-color: #49bd85;
@@ -217,7 +251,31 @@
font-size: 1rem; font-size: 1rem;
cursor: pointer; cursor: pointer;
margin-top: 1rem; margin-top: 1rem;
text-decoration: none;
text-align: center; text-align: center;
} }
.actions {
display: flex;
flex-direction: column;
padding-top: 1rem;
}
.opening-entry {
display: grid;
grid-template-columns: auto 1fr;
gap: 0.75rem;
padding: 0.5rem 1.4rem;
align-items: center;
}
.opening-entry .day {
font-weight: bold;
color: #ffffff;
white-space: nowrap;
}
.opening-entry .times {
font-family: monospace;
background-color: rgba(255, 255, 255, 0.1);
padding: 0.25rem 0.5rem;
border-radius: 0.25rem;
color: #eaffeb;
}
</style> </style>

View File

@@ -8,6 +8,12 @@ type StudySpaceData = Omit<
> & { > & {
id?: string; id?: string;
building_location?: google.maps.places.PlaceResult; building_location?: google.maps.places.PlaceResult;
opening_times?: {
day_of_week: number;
opens_at: string;
closes_at: string;
is_24_7: boolean;
}[];
}; };
export const load: PageServerLoad = async ({ params, locals: { supabase } }) => { export const load: PageServerLoad = async ({ params, locals: { supabase } }) => {
@@ -34,6 +40,13 @@ export const load: PageServerLoad = async ({ params, locals: { supabase } }) =>
const studySpaceData = space as StudySpaceData & Partial<typeof space>; const studySpaceData = space as StudySpaceData & Partial<typeof space>;
const images = studySpaceData.study_space_images || []; 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")
.eq("study_space_id", params.id)
.order("day_of_week", { ascending: true });
if (hoursErr) error(500, "Failed to load opening times");
studySpaceData.opening_times = hours;
delete studySpaceData.created_at; delete studySpaceData.created_at;
delete studySpaceData.updated_at; delete studySpaceData.updated_at;

View File

@@ -11,7 +11,8 @@
wifiTags, wifiTags,
powerOutletTags, powerOutletTags,
volumeTags, volumeTags,
gmapsLoader gmapsLoader,
daysOfWeek
} from "$lib"; } from "$lib";
import { onMount } from "svelte"; import { onMount } from "svelte";
import type { Json } from "$lib/database.js"; import type { Json } from "$lib/database.js";
@@ -21,9 +22,24 @@
const { space, images } = $derived(data); const { space, images } = $derived(data);
const studySpaceData = $state({ const studySpaceData = $state({
opening_times: daysOfWeek.map((_, index) => ({
day_of_week: index,
opens_at: "",
closes_at: "",
is_24_7: false
})),
...space ...space
}); });
$effect(() => {
if (!space) return;
const { opening_times, ...rest } = space;
Object.assign(studySpaceData, rest);
if (opening_times) {
studySpaceData.opening_times = opening_times;
}
});
let scrollPosition = $state(0); let scrollPosition = $state(0);
const existingImages = $derived( const existingImages = $derived(
Promise.all( Promise.all(
@@ -46,11 +62,13 @@
if (!spaceImgs || spaceImgs.length < 1) return alert("Please select an image file."); if (!spaceImgs || spaceImgs.length < 1) return alert("Please select an image file.");
if (!studySpaceData.building_location) return alert("Please select a building location."); if (!studySpaceData.building_location) return alert("Please select a building location.");
const { opening_times, ...spacePayload } = studySpaceData;
const { data: studySpaceInsert, error: studySpaceError } = await supabase const { data: studySpaceInsert, error: studySpaceError } = await supabase
.from("study_spaces") .from("study_spaces")
.upsert( .upsert(
{ {
...studySpaceData, ...spacePayload,
building_location: studySpaceData.building_location as Json building_location: studySpaceData.building_location as Json
}, },
{ {
@@ -102,6 +120,23 @@
.select(); .select();
if (imageInsertError) return alert(`Error creating image: ${imageInsertError.message}`); if (imageInsertError) return alert(`Error creating image: ${imageInsertError.message}`);
const { error: deleteErr } = await supabase
.from("study_space_hours")
.delete()
.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
}))
);
if (hoursErr) return alert(`Error saving opening times: ${hoursErr.message}`);
alert("Thank you for your contribution!"); alert("Thank you for your contribution!");
// Redirect to the new study space page // Redirect to the new study space page
await goto(`/space/${studySpaceInsert.id}`, { await goto(`/space/${studySpaceInsert.id}`, {
@@ -161,6 +196,20 @@
}); });
spaceImgs = dt.files; 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";
}
</script> </script>
<Navbar> <Navbar>
@@ -254,6 +303,39 @@
</div> </div>
</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)}
/>
<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>
{/each}
</div>
<label for="tags">Additional tags:</label> <label for="tags">Additional tags:</label>
<div class="tagDisplay"> <div class="tagDisplay">
{#each studySpaceData.tags as tagName (tagName)} {#each studySpaceData.tags as tagName (tagName)}
@@ -275,8 +357,8 @@
dropdownVisible = false; dropdownVisible = false;
}} }}
onkeypress={(event) => { onkeypress={(event) => {
event.preventDefault();
if (event.key === "Enter") { if (event.key === "Enter") {
event.preventDefault();
const tag = filteredTags[0]; const tag = filteredTags[0];
if (tag) addTag(tag)(); if (tag) addTag(tag)();
} }
@@ -488,4 +570,36 @@
.additionalImages input { .additionalImages input {
display: none; display: none;
} }
/* Opening times layout and inputs styling */
.opening-times {
display: flex;
flex-direction: column;
gap: 0.5rem;
}
.opening-time-item {
display: flex;
align-items: center;
gap: 0.5rem;
}
.opening-time-item label {
margin-top: 0;
width: 6rem;
}
.opening-time-item input[type="time"] {
padding: 0.5rem;
height: 2.5rem;
border-radius: 0.5rem;
border: 2px solid #eaffeb;
background: none;
color: #eaffeb;
}
.opening-time-item span {
margin: 0 0.5rem;
color: #eaffeb;
}
</style> </style>

View File

@@ -0,0 +1,14 @@
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
opens_at TIME NOT NULL,
closes_at TIME NOT NULL,
is_24_7 BOOLEAN DEFAULT FALSE,
created_at timestamp with time zone DEFAULT now(),
updated_at timestamp with time zone DEFAULT now()
);
CREATE TRIGGER study_space_hours_updated_at
AFTER UPDATE ON study_space_hours
FOR EACH ROW EXECUTE FUNCTION handle_updated_at();

View File

@@ -0,0 +1,28 @@
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()
);
CREATE TRIGGER users_handle_updated_at
AFTER UPDATE ON users
FOR EACH ROW EXECUTE FUNCTION handle_updated_at();
-- Auto-create users when auth.users are created
CREATE FUNCTION handle_new_user()
RETURNS trigger
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path = ''
AS $$
BEGIN
INSERT INTO public.users (id, contact_email)
VALUES (NEW.id, NEW.email);
RETURN NEW;
END;
$$;
CREATE TRIGGER users_handle_new_user
AFTER INSERT ON auth.users
FOR EACH ROW EXECUTE FUNCTION handle_new_user();

View File

@@ -0,0 +1,12 @@
CREATE OR REPLACE FUNCTION handle_new_user()
RETURNS trigger
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path = ''
AS $$
BEGIN
INSERT INTO public.users (id)
VALUES (NEW.id);
RETURN NEW;
END;
$$;

View File

@@ -18,6 +18,7 @@ CREATE TABLE study_spaces (
volume text NOT NULL, volume text NOT NULL,
wifi text NOT NULL, wifi text NOT NULL,
power text NOT NULL, power text NOT NULL,
created_at timestamp with time zone DEFAULT now(), created_at timestamp with time zone DEFAULT now(),
updated_at timestamp with time zone DEFAULT now() updated_at timestamp with time zone DEFAULT now()
); );
@@ -39,6 +40,17 @@ CREATE TABLE reports (
content text content text
); );
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
opens_at TIME NOT NULL,
closes_at TIME NOT NULL,
is_24_7 BOOLEAN DEFAULT FALSE,
created_at timestamp with time zone DEFAULT now(),
updated_at timestamp with time zone DEFAULT now()
);
-- Triggers -- Triggers
CREATE TRIGGER study_spaces_updated_at CREATE TRIGGER study_spaces_updated_at
AFTER UPDATE ON study_spaces AFTER UPDATE ON study_spaces
@@ -51,3 +63,7 @@ FOR EACH ROW EXECUTE FUNCTION handle_updated_at();
CREATE TRIGGER reports_updated_at CREATE TRIGGER reports_updated_at
AFTER UPDATE ON reports AFTER UPDATE ON reports
FOR EACH ROW EXECUTE FUNCTION handle_updated_at(); FOR EACH ROW EXECUTE FUNCTION handle_updated_at();
CREATE TRIGGER study_space_hours_updated_at
AFTER UPDATE ON study_space_hours
FOR EACH ROW EXECUTE FUNCTION handle_updated_at();

View File

@@ -0,0 +1,28 @@
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(),
);
CREATE TRIGGER users_handle_updated_at
AFTER UPDATE ON users
FOR EACH ROW EXECUTE FUNCTION handle_updated_at();
-- Auto-create users when auth.users are created
CREATE FUNCTION handle_new_user()
RETURNS trigger
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path = ''
AS $$
BEGIN
INSERT INTO public.users (id)
VALUES (NEW.id);
RETURN NEW;
END;
$$;
CREATE TRIGGER users_handle_new_user
AFTER INSERT ON auth.users
FOR EACH ROW EXECUTE FUNCTION handle_new_user();