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
6 changes: 6 additions & 0 deletions convex/_generated/api.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,8 @@ import type * as _model_tournaments__helpers_checkTournamentAuth from "../_model
import type * as _model_tournaments__helpers_checkTournamentVisibility from "../_model/tournaments/_helpers/checkTournamentVisibility.js";
import type * as _model_tournaments__helpers_deepenTournament from "../_model/tournaments/_helpers/deepenTournament.js";
import type * as _model_tournaments__helpers_getTournamentDeep from "../_model/tournaments/_helpers/getTournamentDeep.js";
import type * as _model_tournaments__helpers_getTournamentNextRound from "../_model/tournaments/_helpers/getTournamentNextRound.js";
import type * as _model_tournaments__helpers_getTournamentPlayerUserIds from "../_model/tournaments/_helpers/getTournamentPlayerUserIds.js";
import type * as _model_tournaments__helpers_getTournamentShallow from "../_model/tournaments/_helpers/getTournamentShallow.js";
import type * as _model_tournaments__helpers_getTournamentUserIds from "../_model/tournaments/_helpers/getTournamentUserIds.js";
import type * as _model_tournaments_fields from "../_model/tournaments/fields.js";
Expand All @@ -125,6 +127,7 @@ import type * as _model_tournaments_mutations_publishTournament from "../_model/
import type * as _model_tournaments_mutations_startTournament from "../_model/tournaments/mutations/startTournament.js";
import type * as _model_tournaments_mutations_startTournamentRound from "../_model/tournaments/mutations/startTournamentRound.js";
import type * as _model_tournaments_mutations_updateTournament from "../_model/tournaments/mutations/updateTournament.js";
import type * as _model_tournaments_queries_getAvailableTournamentActions from "../_model/tournaments/queries/getAvailableTournamentActions.js";
import type * as _model_tournaments_queries_getTournament from "../_model/tournaments/queries/getTournament.js";
import type * as _model_tournaments_queries_getTournamentOpenRound from "../_model/tournaments/queries/getTournamentOpenRound.js";
import type * as _model_tournaments_queries_getTournamentRankings from "../_model/tournaments/queries/getTournamentRankings.js";
Expand Down Expand Up @@ -301,6 +304,8 @@ declare const fullApi: ApiFromModules<{
"_model/tournaments/_helpers/checkTournamentVisibility": typeof _model_tournaments__helpers_checkTournamentVisibility;
"_model/tournaments/_helpers/deepenTournament": typeof _model_tournaments__helpers_deepenTournament;
"_model/tournaments/_helpers/getTournamentDeep": typeof _model_tournaments__helpers_getTournamentDeep;
"_model/tournaments/_helpers/getTournamentNextRound": typeof _model_tournaments__helpers_getTournamentNextRound;
"_model/tournaments/_helpers/getTournamentPlayerUserIds": typeof _model_tournaments__helpers_getTournamentPlayerUserIds;
"_model/tournaments/_helpers/getTournamentShallow": typeof _model_tournaments__helpers_getTournamentShallow;
"_model/tournaments/_helpers/getTournamentUserIds": typeof _model_tournaments__helpers_getTournamentUserIds;
"_model/tournaments/fields": typeof _model_tournaments_fields;
Expand All @@ -313,6 +318,7 @@ declare const fullApi: ApiFromModules<{
"_model/tournaments/mutations/startTournament": typeof _model_tournaments_mutations_startTournament;
"_model/tournaments/mutations/startTournamentRound": typeof _model_tournaments_mutations_startTournamentRound;
"_model/tournaments/mutations/updateTournament": typeof _model_tournaments_mutations_updateTournament;
"_model/tournaments/queries/getAvailableTournamentActions": typeof _model_tournaments_queries_getAvailableTournamentActions;
"_model/tournaments/queries/getTournament": typeof _model_tournaments_queries_getTournament;
"_model/tournaments/queries/getTournamentOpenRound": typeof _model_tournaments_queries_getTournamentOpenRound;
"_model/tournaments/queries/getTournamentRankings": typeof _model_tournaments_queries_getTournamentRankings;
Expand Down
6 changes: 2 additions & 4 deletions convex/_model/tournaments/_helpers/deepenTournament.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { Doc, Id } from '../../../_generated/dataModel';
import { QueryCtx } from '../../../_generated/server';
import { getStorageUrl } from '../../common/_helpers/getStorageUrl';
import { getTournamentNextRound } from './getTournamentNextRound';

/* eslint-disable @typescript-eslint/explicit-function-return-type */
/**
Expand Down Expand Up @@ -35,9 +36,6 @@ export const deepenTournament = async (
...c.players.filter((p) => p.active).map((p) => p.userId),
], [] as Id<'users'>[]);

// Computed properties (easy to do, but used so frequently, it's nice to include them by default)
const nextRound = (tournament.currentRound ?? tournament.lastRound ?? -1) + 1;

return {
...tournament,
logoUrl,
Expand All @@ -49,7 +47,7 @@ export const deepenTournament = async (
activePlayerUserIds,
maxPlayers : tournament.maxCompetitors * tournament.competitorSize,
useTeams: tournament.competitorSize > 1,
nextRound: nextRound < tournament.roundCount ? nextRound : undefined,
nextRound: getTournamentNextRound(tournament),
};
};

Expand Down
14 changes: 14 additions & 0 deletions convex/_model/tournaments/_helpers/getTournamentNextRound.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { Doc } from '../../../_generated/dataModel';

/**
* Gets the next round of a tournament.
*
* @param tournament - Raw Tournament document
* @returns The next round if there will be one, otherwise undefined
*/
export const getTournamentNextRound = (
tournament: Doc<'tournaments'>,
): number | undefined => {
const nextRound = (tournament.currentRound ?? tournament.lastRound ?? -1) + 1;
return nextRound < tournament.roundCount ? nextRound : undefined;
};
25 changes: 25 additions & 0 deletions convex/_model/tournaments/_helpers/getTournamentPlayerUserIds.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { Id } from '../../../_generated/dataModel';
import { QueryCtx } from '../../../_generated/server';

/**
* Get a list of user IDs for the players of a tournament.
*
* @param ctx - Convex query context
* @param tournamentId - ID of the tournament
* @param activeOnly - Limit to active players
* @returns Array of user IDs
*/
export const getTournamentPlayerUserIds = async (
ctx: QueryCtx,
tournamentId: Id<'tournaments'>,
activeOnly = false,
): Promise<Id<'users'>[]> => {
const tournamentCompetitors = await ctx.db.query('tournamentCompetitors').withIndex(
'by_tournament_id',
(q) => q.eq('tournamentId', tournamentId),
).collect();
return tournamentCompetitors.reduce((acc, c) => [
...acc,
...c.players.filter((p) => activeOnly ? p.active : true).map((p) => p.userId),
], [] as Id<'users'>[]);
};
4 changes: 4 additions & 0 deletions convex/_model/tournaments/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,10 @@ export {
} from './mutations/updateTournament';

// Queries
export {
getAvailableTournamentActions,
getAvailableTournamentActionsArgs,
} from './queries/getAvailableTournamentActions';
export {
getTournament,
getTournamentArgs,
Expand Down
91 changes: 91 additions & 0 deletions convex/_model/tournaments/queries/getAvailableTournamentActions.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
import { getAuthUserId } from '@convex-dev/auth/server';
import { Infer, v } from 'convex/values';

import { QueryCtx } from '../../../_generated/server';
import { TournamentActionKey } from '..';
import { checkTournamentVisibility } from '../_helpers/checkTournamentVisibility';
import { getTournamentNextRound } from '../_helpers/getTournamentNextRound';
import { getTournamentPlayerUserIds } from '../_helpers/getTournamentPlayerUserIds';

export const getAvailableTournamentActionsArgs = v.object({
id: v.id('tournaments'),
});

/**
* Gets a list of tournament actions which are available to a user.
*
* @param ctx - Convex query context
* @param args - Convex query args
* @param args.id - ID of the tournament
* @returns An array of TournamentActionKey(s)
*/
export const getAvailableTournamentActions = async (
ctx: QueryCtx,
args: Infer<typeof getAvailableTournamentActionsArgs>,
): Promise<TournamentActionKey[]> => {
const tournament = await ctx.db.get(args.id);
if (!tournament) {
return [];
}

// --- CHECK AUTH ----
const userId = await getAuthUserId(ctx);
if (!(await checkTournamentVisibility(ctx, tournament))) {
return [];
}

// ---- GATHER DATA ----
const nextRound = getTournamentNextRound(tournament);
const nextRoundPairings = await ctx.db.query('tournamentPairings')
.withIndex('by_tournament_id', (q) => q.eq('tournamentId', args.id))
.collect();
const nextRoundPairingCount = (nextRoundPairings ?? []).length;
const playerUserIds = await getTournamentPlayerUserIds(ctx, tournament._id);

const isOrganizer = !!userId && tournament.organizerUserIds.includes(userId);
const isPlayer = !!userId && playerUserIds.includes(userId);

const hasCurrentRound = tournament.currentRound !== undefined;
const hasNextRound = nextRound !== undefined;

// ---- PRIMARY ACTIONS ----
const actions: TournamentActionKey[] = [];

if (isOrganizer && ['draft', 'published'].includes(tournament.status)) {
actions.push(TournamentActionKey.Edit);
}

if (isOrganizer && tournament.status === 'draft') {
actions.push(TournamentActionKey.Delete);
}

if (isOrganizer && tournament.status === 'draft') {
actions.push(TournamentActionKey.Publish);
}

if (isOrganizer && tournament.status === 'published') { // TODO: Check for at least 2 competitors
actions.push(TournamentActionKey.Start);
}

if (isOrganizer && !hasCurrentRound && hasNextRound && nextRoundPairingCount === 0) {
actions.push(TournamentActionKey.ConfigureRound);
}

if (isOrganizer && !hasCurrentRound && hasNextRound && nextRoundPairingCount > 0) {
actions.push(TournamentActionKey.StartRound);
}

if ((isOrganizer || isPlayer) && hasCurrentRound) { // TODO: Don't show if all matches checked in
actions.push(TournamentActionKey.SubmitMatchResult);
}

if (isOrganizer && hasCurrentRound) {
actions.push(TournamentActionKey.EndRound);
}

if (isOrganizer && !hasCurrentRound) {
actions.push(TournamentActionKey.End);
}

return actions;
};
5 changes: 5 additions & 0 deletions convex/tournaments.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,11 @@ export const getTournamentRankings = query({
handler: model.getTournamentRankings,
});

export const getAvailableTournamentActions = query({
args: model.getAvailableTournamentActionsArgs,
handler: model.getAvailableTournamentActions,
});

export const createTournament = mutation({
args: model.createTournamentArgs,
handler: model.createTournament,
Expand Down
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "combat-command",
"private": true,
"version": "0.0.0",
"version": "1.8.5",
"type": "module",
"scripts": {
"dev": "npm-run-all --parallel dev:frontend dev:backend",
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,3 @@
import { useQuery } from 'convex/react';

import { api } from '~/api';
import { Identity } from '~/components/IdentityBadge';
import { getUserDisplayNameString } from '~/utils/common/getUserDisplayNameString';
import { FowV4MatchResultDetailsData } from './FowV4MatchResultDetails.types';
Expand All @@ -15,14 +12,9 @@ export const usePlayerName = (
identity: Identity,
loading?: boolean,
): UserPlayerNameResult => {
const { user, userId, placeholder } = identity;

// TODO: Replace with a service hook
const queryUser = useQuery(api.users.getUser, userId ? {
id: userId,
} : 'skip');
const { user, placeholder } = identity;

if (loading || (userId && !queryUser)) {
if (loading) {
return {
loading: true,
};
Expand All @@ -34,13 +26,6 @@ export const usePlayerName = (
displayName: getUserDisplayNameString(user),
};
}

if (userId && queryUser) {
return {
loading: false,
displayName: getUserDisplayNameString(queryUser),
};
}

if (placeholder) {
return {
Expand All @@ -62,14 +47,12 @@ export const usePlayerNames = (
): UserPlayerNamesResult => {
const { displayName: player0DisplayName, loading: player0Loading } = usePlayerName({
user: matchResult.player0User,
userId: matchResult.player0UserId,
placeholder: matchResult.player0Placeholder ? {
displayName: matchResult.player0Placeholder,
} : undefined,
});
const { displayName: player1DisplayName, loading: player1Loading } = usePlayerName({
user: matchResult.player1User,
userId: matchResult.player1UserId,
placeholder: matchResult.player1Placeholder ? {
displayName: matchResult.player1Placeholder,
} : undefined,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { MatchResult, User } from '~/api';

export type FowV4MatchResultDetailsData = Pick<MatchResult, 'player0User' | 'player0UserId' | 'player0Placeholder' | 'player1User' | 'player1UserId' | 'player1Placeholder'> & {
export type FowV4MatchResultDetailsData = Pick<MatchResult, 'player0User' | 'player0Placeholder' | 'player1User' | 'player1Placeholder'> & {
player0User?: User;
player1User?: User;
details: Omit<MatchResult['details'], 'missionName' | 'player0Score' | 'player1Score'> & {
Expand Down
25 changes: 3 additions & 22 deletions src/components/IdentityBadge/IdentityBadge.hooks.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,6 @@ import { Ghost, HelpCircle } from 'lucide-react';
import { TournamentCompetitor } from '~/api';
import { Avatar } from '~/components/generic/Avatar';
import { FlagCircle } from '~/components/generic/FlagCircle';
import { useGetTournamentCompetitor } from '~/services/tournamentCompetitors';
import { useGetUser } from '~/services/users';
import { getCountryName } from '~/utils/common/getCountryName';
import { getUserDisplayNameString } from '~/utils/common/getUserDisplayNameString';
import { Identity } from './IdentityBadge.types';
Expand Down Expand Up @@ -39,13 +37,10 @@ const getCompetitorDisplayName = (competitor: TournamentCompetitor): ReactElemen
};

export const useIdentityElements = (identity: Identity, loading?: boolean): ReactElement[] => {
const { user, userId, competitor, competitorId, placeholder } = identity;
const { user, competitor, placeholder } = identity;

const { data: queryUser } = useGetUser(userId ? { id: userId } : 'skip');
const { data: queryCompetitor } = useGetTournamentCompetitor(competitorId ? { id: competitorId } : 'skip');

// Render loading skeleton if explicitly loading or an ID was provided and it is fetching
if (loading || (userId && !queryUser) || competitorId && !queryCompetitor) {
// Render loading skeleton if explicitly loading
if (loading) {
return [
<Avatar loading />,
<span>Loading...</span>,
Expand All @@ -59,27 +54,13 @@ export const useIdentityElements = (identity: Identity, loading?: boolean): Reac
];
}

if (userId && queryUser) {
return [
<Avatar url={queryUser?.avatarUrl} />,
<span>{getUserDisplayNameString(queryUser)}</span>,
];
}

if (competitor) {
return [
getCompetitorAvatar(competitor),
getCompetitorDisplayName(competitor),
];
}

if (competitorId && queryCompetitor) {
return [
getCompetitorAvatar(queryCompetitor),
getCompetitorDisplayName(queryCompetitor),
];
}

if (placeholder) {
return [
<Avatar icon={placeholder.icon ?? <Ghost />} muted />,
Expand Down
Loading