Skip to content

Commit

Permalink
Merge pull request #32 from craigkai/testing
Browse files Browse the repository at this point in the history
Testing
  • Loading branch information
craigkai authored Jul 30, 2024
2 parents 0ff18ea + 7273d2d commit 1116409
Show file tree
Hide file tree
Showing 21 changed files with 444 additions and 307 deletions.
32 changes: 17 additions & 15 deletions src/components/Bracket.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -70,21 +70,23 @@
async function generateBracket() {
try {
if (matchesSubscription) await matchesSubscription.unsubscribe();
const res = await bracket.createBracketMatches(
tournament,
teams.teams,
matches.matches || []
);
if (!res) {
error('Failed to create matches');
} else {
// We need to wait to resub to the matches channel
await new Promise((r) => setTimeout(r, 1000));
matchesSubscription = await bracket.subscribeToMatches();
await bracket.load();
if (bracket.event_id) {
if (matchesSubscription) await matchesSubscription.unsubscribe();
const res = await bracket.createBracketMatches(
tournament,
teams.teams,
matches.matches || []
);
if (!res) {
error('Failed to create matches');
} else {
// We need to wait to resub to the matches channel
await new Promise((r) => setTimeout(r, 1000));
matchesSubscription = await bracket.subscribeToMatches();
await bracket.load(bracket.event_id);
}
}
} catch (err) {
error((err as HttpError).toString());
Expand Down
17 changes: 10 additions & 7 deletions src/components/EditMatch.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,22 @@
import { Label } from '$components/ui/label/index.js';
import { Input } from '$components/ui/input/index.js';
import * as Select from '$components/ui/select/index.js';
import { Matches } from '$lib/matches.svelte';
import { closeModal, updateMatch } from '$lib/helper.svelte';
import type { Brackets } from '$lib/brackets/brackets.svelte';
import type { Teams } from '$lib/teams.svelte';
import { error } from '@sveltejs/kit';
import { getContext } from 'svelte';
import type { Pool } from '$lib/pool/pool.svelte';
let {
matchId,
matches = $bindable(),
teams = $bindable()
}: { matchId: number; matches: Matches | Brackets; teams: Teams } = $props();
let { matchId, matches }: { matchId: number; matches: Pool | Brackets } = $props();
const teams = getContext('teams') as Teams;
let match = matches?.matches?.find((m) => m.id === matchId);
let match = $state(matches?.matches?.find((m) => m.id === matchId));
$effect(() => {
matches;
match = matches?.matches?.find((m) => m.id === matchId);
});
async function saveMatch() {
try {
Expand Down
6 changes: 3 additions & 3 deletions src/components/Header.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
<header class="w-full">
<!-- Navigation bar -->
<div class="bg-blue-500 dark:bg-slate-900 p-4">
<a href="/" class="flex">
<div href="/" class="flex">
<svg
class="h-20 w-20 p-2 dark:fill-blue-600"
fill="#000000"
Expand Down Expand Up @@ -56,8 +56,8 @@
<div class="absolute end-0">
<Hamburger bind:open --color="white" />
</div>
</a>
</div>

{#if open}
<nav
class="relative flex w-full items-center justify-between py-2 bg-white rounded text-neutral-600 shadow-lg hover:text-neutral-700 focus:text-neutral-700 dark:bg-gray-800 dark:text-gray-200 md:flex-wrap md:justify-start"
Expand Down
103 changes: 53 additions & 50 deletions src/components/Matches.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -13,17 +13,17 @@
import { onMount } from 'svelte';
let {
matches = $bindable(),
tournament = $bindable(),
teams = $bindable(),
readOnly = $bindable(false),
defaultTeam
defaultTeam,
teams,
tournament,
matches
}: {
matches: Matches;
tournament: Event;
teams: Teams;
readOnly: boolean;
defaultTeam: string | null;
teams: Teams;
tournament: Event;
matches: Matches;
} = $props();
let showGenerateMatchesAlert = $state(false);
Expand Down Expand Up @@ -83,6 +83,7 @@
return m.round;
}) ?? [0]
);
$inspect(rounds);
</script>

<div class="block text-gray-700 text-sm font-bold mb-4 flex">
Expand All @@ -108,54 +109,56 @@
</Table.Header>

<Table.Body>
{#each Array(rounds) as _, i}
{@const round = i + 1}
<Table.Row>
{#each Array(tournament.courts) as _, court}
{@const match = matches.matches.find(
(m: MatchRow) => m.court === court && m.round.toString() === round.toString()
)}
{#if match}
{@const matchComplete = match.team1_score !== null && match.team2_score !== null}
{@const teamsForMatch = [
match.public_matches_team1_fkey.name,
match.public_matches_team2_fkey.name
]}
{@const hasDefaultTeam = defaultTeam ? teamsForMatch.includes(defaultTeam) : false}
{@const defaultTeamWin =
match.public_matches_team1_fkey.name == defaultTeam
? (match.team1_score ?? 0) > (match.team2_score ?? 0)
: (match.team2_score ?? 0) > (match.team1_score ?? 0)}
{@const rowTdClass = defaultTeamWin
? 'border-solid border-2 border-green-400 bg-green-200 dark:bg-green-700 dark:border-green-700'
: 'border-solid border-2 border-red-400 bg-red-200 dark:bg-red-700 dark:border-red-700'}
{#if rounds}
{#each Array(rounds) as _, i}
{@const round = i + 1}
<Table.Row>
{#each Array(tournament.courts) as _, court}
{@const match = matches.matches.find(
(m: MatchRow) => m.court === court && m.round.toString() === round.toString()
)}
{#if match}
{@const matchComplete = match.team1_score !== null && match.team2_score !== null}
{@const teamsForMatch = [
match.public_matches_team1_fkey.name,
match.public_matches_team2_fkey.name
]}
{@const hasDefaultTeam = defaultTeam ? teamsForMatch.includes(defaultTeam) : false}
{@const defaultTeamWin =
match.public_matches_team1_fkey.name == defaultTeam
? (match.team1_score ?? 0) > (match.team2_score ?? 0)
: (match.team2_score ?? 0) > (match.team1_score ?? 0)}
{@const rowTdClass = defaultTeamWin
? 'border-solid border-2 border-green-400 bg-green-200 dark:bg-green-700 dark:border-green-700'
: 'border-solid border-2 border-red-400 bg-red-200 dark:bg-red-700 dark:border-red-700'}
<Table.Cell
class={hasDefaultTeam
? matchComplete
? 'p-2 ' + rowTdClass
: 'p-2 border-solid border-2 border-yellow-300 bg-yellow-200 dark:bg-gray-400 dark:border-gray-400'
: 'p-2'}
>
<ViewMatch {match} {readOnly} showWinLoss={!hasDefaultTeam} />
</Table.Cell>
{:else}
<Table.Cell class="p-2"></Table.Cell>
{/if}
{/each}
{#if tournament.refs === 'teams'}
{@const ref = matches.matches.find(
(m: MatchRow) => m.round.toString() === round.toString()
)?.public_matches_ref_fkey}
<Table.Cell
class={hasDefaultTeam
? matchComplete
? 'p-2 ' + rowTdClass
: 'p-2 border-solid border-2 border-yellow-300 bg-yellow-200 dark:bg-gray-400 dark:border-gray-400'
class={ref?.name == defaultTeam
? 'p-2 border-solid border-2 border-yellow-300 bg-yellow-200 dark:bg-gray-400 dark:border-gray-400'
: 'p-2'}
>
<ViewMatch {match} {readOnly} showWinLoss={!hasDefaultTeam} />
{ref?.name}
</Table.Cell>
{:else}
<Table.Cell class="p-2"></Table.Cell>
{/if}
{/each}
{#if tournament.refs === 'teams'}
{@const ref = matches.matches.find(
(m: MatchRow) => m.round.toString() === round.toString()
)?.public_matches_ref_fkey}
<Table.Cell
class={ref?.name == defaultTeam
? 'p-2 border-solid border-2 border-yellow-300 bg-yellow-200 dark:bg-gray-400 dark:border-gray-400'
: 'p-2'}
>
{ref?.name}
</Table.Cell>
{/if}
</Table.Row>
{/each}
</Table.Row>
{/each}
{/if}
</Table.Body>
</Table.Root>
{/if}
Expand Down
7 changes: 4 additions & 3 deletions src/components/Settings.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@
import CalendarIcon from 'lucide-svelte/icons/calendar';
export let data;
export let event_id;
export let eventId;
let form = superForm(data.form, {
validators: zodClient(formSchema),
Expand All @@ -41,6 +41,7 @@
onUpdated({ form }) {
if (form.valid) {
success(`Tournament settings updated`);
data.tournament.load(data.eventId);
}
}
});
Expand Down Expand Up @@ -72,7 +73,7 @@
<form
class="form-container dark:bg-gray-800 dark:text-gray-200 p-2 rounded"
method="POST"
action="?/{event_id === 'create' ? 'createEvent' : 'updateEvent'}"
action="?/{eventId === 'create' ? 'createEvent' : 'updateEvent'}"
use:enhance
>
<div class="form-field">
Expand Down Expand Up @@ -240,7 +241,7 @@
</div>
</form>

{#if event_id !== 'create'}
{#if eventId !== 'create'}
<form method="POST" action="?/deleteEvent" use:enhance>
<div class="flex justify-center">
<Button class="m-2 bg-red-500 hover:bg-red-700 dark:bg-red-700 dark:hover:bg-red-900"
Expand Down
24 changes: 13 additions & 11 deletions src/components/Teams.svelte
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
<script lang="ts">
import type { Teams } from '$lib/teams.svelte';
import { success, error } from '$lib/toast';
import { isHttpError, type HttpError } from '@sveltejs/kit';
import * as Table from '$components/ui/table';
import { Input } from '$components/ui/input/index.js';
import type { Teams } from '$lib/teams.svelte';
let { teams = $bindable() }: { teams: Teams } = $props();
const { teams = $bindable() }: { teams: Teams } = $props();
async function createTeam() {
if (teams.teams.findIndex((team) => team.name === newTeamName) !== -1) {
Expand All @@ -16,7 +16,7 @@
try {
const newTeam: Partial<TeamRow> = {
name: newTeamName,
event_id: teams.event_id
event_id: teams.eventId
};
await teams.create(newTeam);
Expand Down Expand Up @@ -44,15 +44,17 @@
}
async function loadEventTeams() {
try {
const res = await teams.load();
// @ts-ignore
currentTeams = res;
} catch (err) {
if (isHttpError(err)) {
error(err.body.message);
if (teams.eventId) {
try {
const res = await teams.load(teams.eventId);
// @ts-ignore
currentTeams = res;
} catch (err) {
if (isHttpError(err)) {
error(err.body.message);
}
error('Something has gone very wrong');
}
error('Something has gone very wrong');
}
}
let newTeamName = $state('');
Expand Down
4 changes: 2 additions & 2 deletions src/lib/brackets/brackets.svelte.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,9 @@ export class Brackets extends Matches {
type = 'bracket';

// Overload Matches load method to only load our bracket matches.
async load() {
async load(eventId: number): Promise<this> {
try {
const res = await this.databaseService.load(this.event_id, {
const res = await this.databaseService.load(eventId, {
column: 'type',
operator: 'eq',
value: 'bracket'
Expand Down
40 changes: 40 additions & 0 deletions src/lib/database/base.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import type { PostgrestResponse, PostgrestSingleResponse } from '@supabase/supabase-js';
import { error, type NumericRange } from '@sveltejs/kit';
import type { z } from 'zod';

export class Base {
// Private property for Supabase client
supabaseClient: supabaseClient;

// Constructor to initialize Supabase client
constructor(supabaseClient: supabaseClient) {
this.supabaseClient = supabaseClient;
}

validateAndHandleErrors<T>(
response: PostgrestResponse<T> | PostgrestSingleResponse<T>,
schema: z.ZodType<T, any, any>
): T {
this.handleDatabaseError(response as PostgrestResponse<T[]> | PostgrestResponse<T[][]>);

const result = schema.safeParse(response.data);
if (!result.success) {
const errorResponse = { status: 500, error: result.error } as unknown as PostgrestResponse<T>;
this.handleDatabaseError(errorResponse as PostgrestResponse<T[]> | PostgrestResponse<T[][]>);
}

return response.data as T;
}

// Method to handle database errors
handleDatabaseError<T>(response: PostgrestSingleResponse<T> | PostgrestResponse<T>): void {
// If there's an error in the response
if (response.error) {
// Log the status and error message
console.error(`Failed operation with status ${response.status}: ${response.error.message}`);
// Log the error details
console.error(response.error);
error(response.status as NumericRange<400, 599>, response.error);
}
}
}
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import { SupabaseDatabaseService } from '$lib/database/supabaseDatabaseService.svelte';
import type { PostgrestResponse, PostgrestSingleResponse } from '@supabase/supabase-js';
import { z } from 'zod';
import { eventsRowSchema, eventsUpdateSchema } from '$schemas/supabase';
import type { Infer } from 'sveltekit-superforms';
import type { FormSchema } from '$schemas/settingsSchema';
import { Base } from '$lib/database/base';

const EventsRowSchemaArray = z.array(eventsRowSchema);

export class EventSupabaseDatabaseService extends SupabaseDatabaseService {
export class EventSupabaseDatabaseService extends Base {
/**
* Create a new event in the database.
* @param {EventRow} input - The data for the new event.
Expand Down
Loading

0 comments on commit 1116409

Please sign in to comment.