Skip to content

Commit

Permalink
Merge pull request #74 from Js41637/feat/admin-events-list
Browse files Browse the repository at this point in the history
feat: Add admin page to view and manage all events
  • Loading branch information
CactusPuppy authored Nov 7, 2023
2 parents 5af304e + d1d6342 commit 06efbb9
Show file tree
Hide file tree
Showing 4 changed files with 239 additions and 14 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ node_modules
.env
.env.*
!.env.example
.idea/

# Supabase CLI information
supabase
Expand Down
12 changes: 12 additions & 0 deletions src/lib/components/_spinner.svelte
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<script lang="ts">
let customClass: string;
// noinspection ReservedWordAsName
export { customClass as class };
</script>
<div role="status">
<svg aria-hidden="true" class="mr-2 text-gray-200 animate-spin dark:text-gray-600 fill-blue-600 {customClass}" viewBox="0 0 100 101" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M100 50.5908C100 78.2051 77.6142 100.591 50 100.591C22.3858 100.591 0 78.2051 0 50.5908C0 22.9766 22.3858 0.59082 50 0.59082C77.6142 0.59082 100 22.9766 100 50.5908ZM9.08144 50.5908C9.08144 73.1895 27.4013 91.5094 50 91.5094C72.5987 91.5094 90.9186 73.1895 90.9186 50.5908C90.9186 27.9921 72.5987 9.67226 50 9.67226C27.4013 9.67226 9.08144 27.9921 9.08144 50.5908Z" fill="currentColor"/>
<path d="M93.9676 39.0409C96.393 38.4038 97.8624 35.9116 97.0079 33.5539C95.2932 28.8227 92.871 24.3692 89.8167 20.348C85.8452 15.1192 80.8826 10.7238 75.2124 7.41289C69.5422 4.10194 63.2754 1.94025 56.7698 1.05124C51.7666 0.367541 46.6976 0.446843 41.7345 1.27873C39.2613 1.69328 37.813 4.19778 38.4501 6.62326C39.0873 9.04874 41.5694 10.4717 44.0505 10.1071C47.8511 9.54855 51.7191 9.52689 55.5402 10.0491C60.8642 10.7766 65.9928 12.5457 70.6331 15.2552C75.2735 17.9648 79.3347 21.5619 82.5849 25.841C84.9175 28.9121 86.7997 32.2913 88.1811 35.8758C89.083 38.2158 91.5421 39.6781 93.9676 39.0409Z" fill="currentFill"/>
</svg>
<span class="sr-only">Loading...</span>
</div>
162 changes: 162 additions & 0 deletions src/routes/admin/events/+page.svelte
Original file line number Diff line number Diff line change
@@ -0,0 +1,162 @@
<script lang="ts">
import { page } from "$app/stores";
import { goto } from "$app/navigation";
import { onMount } from 'svelte';
import { writable } from 'svelte/store';
import { format } from "date-fns";
import WidthLimiter from "$lib/utils/WidthLimiter.svelte";
import Spinner from "$lib/components/_spinner.svelte";
import { FontAwesomeIcon } from "fontawesome-svelte";
import { faPlus, faPencil, faEye, faTrash } from "@fortawesome/free-solid-svg-icons";
import { enhance } from "$app/forms";
let isLoading = writable(true);
let events = writable([]);
let currentPage = 1;
let totalPages = 1;
let pageSize = 25;
async function fetchEvents(page: number) {
isLoading.set(true);
const response = await fetch(`/api/events?include_past=true&page=${page}&page_size=${pageSize}&order_by=id&order_direction=desc&v=2&ts=${Date.now()}`);
const data = await response.json();
events.set(data.data);
totalPages = data.meta.total_pages;
isLoading.set(false);
}
function changePage(delta: number) {
currentPage += delta;
fetchEvents(currentPage);
}
function formatDate(date?: string) {
if (!date) return "null";
const d1 = format(new Date(date), "EEEE do MMM yyyy");
const d2 = format(new Date(date), "yyyy-MM-dd h:mm a");
return `${d1}\n${d2}`;
}
function getState(event) {
if (event.date == null || event.end_date == null) return "Active";
const now = new Date();
const startDate = new Date(event.date);
const endDate = new Date(event.end_date);
if (now < startDate) return "Upcoming";
if (now > endDate) return "Ended";
return "Active";
}
onMount(() => {
// if the user isn't logged in, redirect them to the login page
if (!$page.data.session) {
return goto("/login");
}
fetchEvents(currentPage);
});
</script>

<WidthLimiter vagueWidthInPx={700} class="w-full mx-auto px-2">
<h1 class="text-4xl mt-2 mb-4 font-bold tracking-tight text-center text-ow2-orange dark:text-ow2-light-orange">All Events</h1>

{#if $isLoading}
<div class="flex justify-center">
<Spinner class="w-10 h-10" />
</div>
{:else}
<div class="flex justify-center mb-4">
<a href={`/event/new`} data-sveltekit-reload>
<button
class="dark:text-white dark:bg-zinc-700 hover:dark:bg-zinc-600 hover:bg-zinc-400 text-black bg-zinc-300 rounded-lg px-3 py-2 cursor-pointer disabled:opacity-40 disabled:pointer-events-none">
<FontAwesomeIcon icon={faPlus}/><span class="pl-2">New Event</span>
</button>
</a>
</div>

<table class="table table-auto w-full rounded-lg overflow-hidden px-4 md:px-8 pt-6 pb-2 relative">
<thead class="bg-zinc-300 dark:bg-zinc-800 text-left">
<tr>
<th class="px-4 py-3">ID</th>
<th class="px-4 py-3">Title</th>
<th class="px-4 py-3">Date</th>
<th class="px-4 py-3">End Date</th>
<th class="px-4 py-3">Status</th>
<th class="px-4 py-3">Actions</th>
</tr>
</thead>
<tbody class="events_list bg-zinc-200 dark:bg-zinc-700">
{#each $events as event (event.id)}
<tr>
<td class="px-4 py-3 text-center">{event.id}</td>
<td class="px-4 py-3">{event.title}</td>
<td class="px-4 py-3 whitespace-pre">{formatDate(event.date)}</td>
<td class="px-4 py-3 whitespace-pre">{formatDate(event.end_date)}</td>
<td class="px-4 py-3 whitespace-pre">{getState(event)}</td>
<td class="px-2 py-3 text-center whitespace-nowrap">
<a href={`/event/${event.id}`}>
<button class="bg-zinc-800 bg-opacity-30 hover:bg-zinc-600 rounded-lg px-3 py-2">
<FontAwesomeIcon icon={faEye}/>
</button>
</a>

<a class="ml-0.5" href={`/event/${event.id}/edit`}>
<button class="bg-zinc-800 bg-opacity-30 hover:bg-zinc-600 rounded-lg px-3 py-2">
<FontAwesomeIcon icon={faPencil}/>
</button>
</a>

<form
class="inline-block ml-0.5"
action={`/event/${event.id}/destroy`}
method="POST"
use:enhance={({ cancel }) => {
if (!window.confirm(`Are you sure you want to delete '${event.title}'?`)) {
cancel();
}
return async ({ result }) => {
if (result.type === "success" || result.type === "redirect") {
changePage(0)
} else {
alert("Something went wrong. Sorry about that!");
}
};
}}
>
<button type="submit" class="bg-red-700 bg-opacity-50 hover:bg-red-600 rounded-lg px-3 py-2">
<FontAwesomeIcon icon={faTrash}/>
</button>
</form>
</td>
</tr>
{/each}
</tbody>
</table>
{/if}

<div class="flex justify-center mt-4 gap-3">
<button
on:click={() => changePage(-1)}
disabled={currentPage === 1 || $isLoading}
class="dark:text-white dark:bg-zinc-700 hover:dark:bg-zinc-600 hover:bg-zinc-400 text-black bg-zinc-300 rounded-lg px-4 py-2 cursor-pointer disabled:opacity-40 disabled:pointer-events-none">
Previous
</button>
<button
on:click={() => changePage(1)}
disabled={currentPage === totalPages || $isLoading}
class="dark:text-white dark:bg-zinc-700 hover:dark:bg-zinc-600 hover:bg-zinc-400 text-black bg-zinc-300 rounded-lg px-6 py-2 cursor-pointer disabled:opacity-40 disabled:pointer-events-none">
Next
</button>
</div>
</WidthLimiter>

<style>
.events_list tr:nth-child(even) {
background-color: rgba(0, 0, 0, 0.08);
}
</style>

78 changes: 64 additions & 14 deletions src/routes/api/events/+server.ts
Original file line number Diff line number Diff line change
@@ -1,35 +1,85 @@
import { error, json } from "@sveltejs/kit";
import { error, json, type RequestEvent } from "@sveltejs/kit"
import type { RequestHandler } from "@sveltejs/kit";
import { getSupabase } from "@supabase/auth-helpers-sveltekit";
import { formatISO } from "date-fns";
import { SUPABASE_TABLE_NAME } from '$env/static/private'

const DEFAULT_VERSION = 1;
const DEFAULT_PAGE_SIZE = 25;
const MAX_PAGE_SIZE = 25;

const SUPPORTED_ORDER_BY = ["date", "id"];
const SUPPORTED_VERSIONS = [1, 2];

export const GET: RequestHandler = async (request) => {
const { supabaseClient } = await getSupabase(request);
const { url: { searchParams }, setHeaders } = request;

let pageNum = Number.parseInt(searchParams.get("page"), 10) || 1;
pageNum = pageNum < 1 ? 1 : pageNum;

const DATES_PAGE_SIZE = 25;
const { setHeaders } = request;
const filters = getRequestFilters(request);

let query = supabaseClient.from(SUPABASE_TABLE_NAME)
.select("*")
.order("priority", {ascending: false})
.order("date", {ascending: true})
.select("*", { count: filters.version === 2 ? "exact" : undefined })

const includePast = searchParams.get("include_past") === "true";
if (!includePast) { query = query.or(`date.gte.${formatISO(new Date())},end_date.gte.${formatISO(new Date())},date.is.null`) }
// if there is no order by, use the default sort of priority and date which is used by the homepage
if (!filters.orderBy) {
query = query
.order("priority", { ascending: false })
.order("date", { ascending: true })
} else {
query = query.order(filters.orderBy, { ascending: filters.orderDirection === "asc" })
}

// if we aren't including past events, limit the query to only events that are currently happening or in the future
if (!filters.includePast) {
query = query.or(`date.gte.${formatISO(new Date())},end_date.gte.${formatISO(new Date())},date.is.null`)
}

query = query.range((pageNum - 1) * DATES_PAGE_SIZE, (pageNum * DATES_PAGE_SIZE) - 1);
query = query.range((filters.pageNum - 1) * filters.pageSize, (filters.pageNum * filters.pageSize) - 1);

const { data, error: err } = await query;
const { data, error: err, count, status } = await query;

if (err) throw error(500, "Database error");

setHeaders({
"cache-control": "public, max-age=60"
})

if (filters.version === 2) {
return json({
meta: {
total: count,
total_pages: Math.ceil(count / filters.pageSize)
},
data
});
}

return json(data);
}

function getRequestFilters (request: RequestEvent) {
const searchParams = request.url.searchParams;

let version = Number.parseInt(searchParams.get("v"), 10);
version = SUPPORTED_VERSIONS.includes(version) ? version : DEFAULT_VERSION;

let orderBy = searchParams.get("order_by");
orderBy = SUPPORTED_ORDER_BY.includes(orderBy) ? orderBy : null;

let pageNum = Number.parseInt(searchParams.get("page"), 10) || 1;
pageNum = pageNum < 1 ? 1 : pageNum;

let pageSize = Number.parseInt(searchParams.get("page_size"), 10) || DEFAULT_PAGE_SIZE;
pageSize = (pageSize < 1 || pageSize > MAX_PAGE_SIZE) ? DEFAULT_PAGE_SIZE : pageSize;

const orderDirection = searchParams.get("order_direction") === "desc" ? "desc" : "asc";
const includePast = searchParams.get("include_past") === "true";

return {
version,
orderBy,
pageNum,
pageSize,
orderDirection,
includePast
}
}

1 comment on commit 06efbb9

@vercel
Copy link

@vercel vercel bot commented on 06efbb9 Nov 7, 2023

Choose a reason for hiding this comment

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

Please sign in to comment.